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

Add linter and formatter

grohith32759da1680133b
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 9ad2341c..d116fcec 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -14,6 +14,8 @@ Closes #(issue number)
- [ ] Tested on Intel/Apple Silicon Mac
- [ ] Tested on Apple Silicon Mac
- [ ] Tested on macOS [version]
+- [ ] Ran linter locally: `brew install swiftlint && swiftlint --strict --config .swiftlint.yml`
+- [ ] Ran formatter locally: `brew install swiftformat && swiftformat --lint --config .swiftformat Sources`
## Screenshots / Video
Add screenshots or Video recording of the app after you have made your changes
\ No newline at end of file
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index c5cef2fc..0225fe08 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -19,6 +19,18 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v4
+
+ - name: Install SwiftLint
+ run: brew install swiftlint
+
+ - name: Run SwiftLint (strict)
+ run: swiftlint --strict --config .swiftlint.yml
+
+ - name: Install SwiftFormat
+ run: brew install swiftformat
+
+ - name: Run SwiftFormat (lint)
+ run: swiftformat --lint --config .swiftformat Sources
- name: Setup Xcode
uses: maxim-lobanov/setup-xcode@v1
diff --git a/.swiftformat b/.swiftformat
new file mode 100644
index 00000000..54434bd0
--- /dev/null
+++ b/.swiftformat
@@ -0,0 +1,28 @@
+# Rule configurations
+--allman false
+--binarygrouping 4,8
+--commas always
+--comments indent
+--decimalgrouping 3,5
+--elseposition same-line
+--empty void
+--exponentcase lowercase
+--exponentgrouping disabled
+--fractiongrouping enabled
+--hexgrouping none
+--hexliteralcase lowercase
+--ifdef noindent
+--indent 4
+--indentcase false
+--linebreaks lf
+--octalgrouping 4,8
+--operatorfunc spaced
+--patternlet hoist
+--ranges nospace
+--self remove
+--semicolons inline
+--stripunusedargs closure-only
+--trimwhitespace always
+--wraparguments beforefirst
+--wrapcollections beforefirst
+--exclude .build,DerivedData,Fluid.xcodeproj
\ No newline at end of file
diff --git a/.swiftlint.yml b/.swiftlint.yml
new file mode 100644
index 00000000..36bda3eb
--- /dev/null
+++ b/.swiftlint.yml
@@ -0,0 +1,63 @@
+disabled_rules:
+ - colon # handled by SwiftFormat
+ - trailing_comma # handled by SwiftFormat
+ - explicit_type_interface
+ - closure_body_length
+
+opt_in_rules:
+ - anyobject_protocol
+ - attributes
+ - discouraged_optional_collection
+ - empty_count
+ - explicit_self
+ - fatal_error_message
+ - file_header
+ - first_where
+ - force_unwrapping
+ - literal_expression_end_indentation
+ - multiline_arguments
+ - pattern_matching_keywords
+ - redundant_type_annotation
+ - sorted_imports
+ - strict_fileprivate
+ - toggle_bool
+ - unavailable_function
+
+excluded:
+ - .build
+ - DerivedData
+ - Fluid.xcodeproj
+
+line_length:
+ warning: 120
+ error: 140
+ ignores_comments: true
+ ignores_urls: true
+
+identifier_name:
+ min_length: 3
+ excluded: [id, ui, ai, x, y]
+
+type_body_length:
+ warning: 450
+ error: 550
+ ignores_comments: true
+ ignores_empty_lines: true
+ allows_extensions: true
+
+file_length:
+ warning: 1000
+ error: 1200
+
+function_body_length:
+ warning: 80
+ error: 120
+
+custom_rules:
+ disallow_nslog:
+ regex: 'NSLog'
+ message: "Use DebugLogger.shared.* for consistency."
+ enforce_mark_spacing:
+ regex: '\/\/ MARK:(?! - )'
+ message: "Format section markers as `// MARK: - Section`."
+
diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxproj
index eeb52630..42b8403b 100644
--- a/Fluid.xcodeproj/project.pbxproj
+++ b/Fluid.xcodeproj/project.pbxproj
@@ -190,7 +190,6 @@
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
-
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
@@ -257,7 +256,6 @@
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
-
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
@@ -287,7 +285,7 @@
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
- DEVELOPMENT_TEAM = V4J43B279J;
+ DEVELOPMENT_TEAM = J67LH9U7BN;
ENABLE_APP_SANDBOX = NO;
ENABLE_CODE_COVERAGE = NO;
ENABLE_FILE_ACCESS_DOWNLOADS_FOLDER = readwrite;
@@ -304,7 +302,6 @@
ENABLE_RESOURCE_ACCESS_PRINTING = YES;
ENABLE_RESOURCE_ACCESS_USB = YES;
ENABLE_USER_SELECTED_FILES = readwrite;
-
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity";
@@ -342,7 +339,7 @@
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
- DEVELOPMENT_TEAM = V4J43B279J;
+ DEVELOPMENT_TEAM = J67LH9U7BN;
ENABLE_APP_SANDBOX = NO;
ENABLE_CODE_COVERAGE = NO;
ENABLE_FILE_ACCESS_DOWNLOADS_FOLDER = readwrite;
@@ -359,7 +356,6 @@
ENABLE_RESOURCE_ACCESS_PRINTING = YES;
ENABLE_RESOURCE_ACCESS_USB = YES;
ENABLE_USER_SELECTED_FILES = readwrite;
-
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity";
diff --git a/Sources/Fluid/AppDelegate.swift b/Sources/Fluid/AppDelegate.swift
index 81dcb823..4023bc23 100644
--- a/Sources/Fluid/AppDelegate.swift
+++ b/Sources/Fluid/AppDelegate.swift
@@ -1,14 +1,7 @@
-//
-// AppDelegate.swift
-// Fluid
-//
-// Created by Barathwaj Anandan on 9/22/25.
-//
-
-import AppUpdater
-import SwiftUI
import AppKit
+import AppUpdater
import PromiseKit
+import SwiftUI
class AppDelegate: NSObject, NSApplicationDelegate {
private var updater: AppUpdater?
@@ -30,43 +23,56 @@ class AppDelegate: NSObject, NSApplicationDelegate {
// Note: App UI is designed with dark color scheme in mind
// All gradients and effects are optimized for dark mode
}
-
+
// MARK: - Manual Update Check
+
@objc func checkForUpdatesManually() {
// Confirm invocation
print("🔎 Manual update check triggered")
NSLog("🔎 Manual update check triggered")
-
+
// We use SimpleUpdater for manual checks; AppUpdater instance is optional
-
+
// Get current app version for debugging
let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "unknown"
- DebugLogger.shared.info("Manual update check requested. Current version: \(currentVersion)", source: "AppDelegate")
+ DebugLogger.shared.info(
+ "Manual update check requested. Current version: \(currentVersion)",
+ source: "AppDelegate"
+ )
DebugLogger.shared.info("Checking repository: altic-dev/Fluid-oss", source: "AppDelegate")
print("🔍 DEBUG: Manual update check started - Current version: \(currentVersion)")
print("🔍 DEBUG: Repository: altic-dev/Fluid-oss")
-
+
Task { @MainActor in
do {
// Use our tolerant updater to handle v-prefixed tags and 2-part versions
try await SimpleUpdater.shared.checkAndUpdate(owner: "altic-dev", repo: "Fluid-oss")
// If we get here, an update was found; SimpleUpdater will relaunch on success
// Show a quick heads-up before app restarts
- self.showUpdateAlert(title: "Update Found!", message: "A new version is available and will be installed now.")
+ self.showUpdateAlert(
+ title: "Update Found!",
+ message: "A new version is available and will be installed now."
+ )
} catch {
if let pmkError = error as? PMKError, pmkError.isCancelled {
DebugLogger.shared.info("App is already up-to-date", source: "AppDelegate")
- self.showUpdateAlert(title: "No Updates", message: "You're already running the latest version of Fluid!")
+ self.showUpdateAlert(
+ title: "No Updates",
+ message: "You're already running the latest version of Fluid!"
+ )
} else {
DebugLogger.shared.error("Update check failed: \(error)", source: "AppDelegate")
- self.showUpdateAlert(title: "Update Check Failed", message: "Unable to check for updates. Please try again later.\n\nError: \(error.localizedDescription)")
+ self.showUpdateAlert(
+ title: "Update Check Failed",
+ message: "Unable to check for updates. Please try again later.\n\nError: \(error.localizedDescription)"
+ )
}
}
}
}
-
+
// MARK: - Automatic Update Check
-
+
private func checkForUpdatesAutomatically() {
// Check if we should perform an automatic update check
guard SettingsStore.shared.shouldCheckForUpdates() else {
@@ -74,37 +80,40 @@ class AppDelegate: NSObject, NSApplicationDelegate {
DebugLogger.shared.debug("Automatic update check skipped (\(reason))", source: "AppDelegate")
return
}
-
+
DebugLogger.shared.info("Scheduling automatic update check...", source: "AppDelegate")
-
+
// Delay check slightly to avoid slowing down app launch
Task {
// Wait 3 seconds after launch before checking
try? await Task.sleep(nanoseconds: 3_000_000_000)
-
+
DebugLogger.shared.info("Performing automatic update check for altic-dev/Fluid-oss", source: "AppDelegate")
-
+
do {
let result = try await SimpleUpdater.shared.checkForUpdate(owner: "altic-dev", repo: "Fluid-oss")
-
+
// Update the last check date regardless of result
await MainActor.run {
SettingsStore.shared.updateLastCheckDate()
}
-
+
if result.hasUpdate {
DebugLogger.shared.info("✅ Update available: \(result.latestVersion)", source: "AppDelegate")
// Show update notification on main thread
await MainActor.run {
- showUpdateNotification(version: result.latestVersion)
+ self.showUpdateNotification(version: result.latestVersion)
}
} else {
DebugLogger.shared.info("✅ App is up to date", source: "AppDelegate")
}
} catch {
// Silently log the error, don't bother the user with failed automatic checks
- DebugLogger.shared.debug("Automatic update check failed: \(error.localizedDescription)", source: "AppDelegate")
-
+ DebugLogger.shared.debug(
+ "Automatic update check failed: \(error.localizedDescription)",
+ source: "AppDelegate"
+ )
+
// Still update last check date to avoid hammering the API on failure
await MainActor.run {
SettingsStore.shared.updateLastCheckDate()
@@ -112,20 +121,20 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}
}
}
-
+
@MainActor
private func showUpdateNotification(version: String) {
DebugLogger.shared.info("Showing update notification for version \(version)", source: "AppDelegate")
-
+
let alert = NSAlert()
alert.messageText = "Update Available"
alert.informativeText = "Fluid \(version) is now available. Would you like to install it now?\n\nThe app will restart automatically after installation."
alert.alertStyle = .informational
alert.addButton(withTitle: "Install Now")
alert.addButton(withTitle: "Later")
-
+
let response = alert.runModal()
-
+
if response == .alertFirstButtonReturn {
DebugLogger.shared.info("User chose to install update now", source: "AppDelegate")
checkForUpdatesManually()
@@ -133,7 +142,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
DebugLogger.shared.info("User postponed update", source: "AppDelegate")
}
}
-
+
@MainActor
private func showUpdateAlert(title: String, message: String) {
print("🔔 Showing alert: \(title)")
@@ -157,7 +166,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
let now = Date().timeIntervalSince1970
let last = UserDefaults.standard.double(forKey: cooldownKey)
let oneDay: Double = 24 * 60 * 60
- if last > 0 && (now - last) < oneDay {
+ if last > 0, (now - last) < oneDay {
return
}
@@ -181,6 +190,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}
// MARK: - Session Debounce State
+
private enum AXPromptState {
static var hasPromptedThisSession: Bool = false
}
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 90ee4978..1a416859 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -1,17 +1,10 @@
-//
-// ContentView.swift
-// fluid
-//
-// Created by Barathwaj Anandan on 7/30/25.
-//
-
-import SwiftUI
import AppKit
import AVFoundation
import Combine
import CoreAudio
import CoreGraphics
import Security
+import SwiftUI
// MARK: - Sidebar Item Enum
@@ -30,14 +23,17 @@ enum SidebarItem: Hashable {
// MARK: - Minimal FluidAudio ASR Service (finalized text, macOS)
// MARK: - Saved Provider Model
+
// Removed deprecated inline service and model
// MARK: - Streaming Response Structures
+
private struct StreamingDelta: Codable { let role: String?; let content: String? }
private struct StreamingChoice: Codable { let index: Int?; let delta: StreamingDelta; let finish_reason: String? }
private struct StreamingChunk: Codable { let choices: [StreamingChoice] }
// MARK: - AI Processing Response Structures
+
// NOTE: Keep Codable types out of View methods to avoid SwiftUI/metadata blowups at launch.
private struct AIProcessingMessage: Codable { let role: String; let content: String }
private struct AIProcessingChoiceMessage: Codable { let role: String; let content: String }
@@ -54,7 +50,7 @@ struct ContentView: View {
@Environment(\.theme) private var theme
@State private var hotkeyManager: GlobalHotkeyManager? = nil
@State private var hotkeyManagerInitialized: Bool = false
-
+
@State private var appear = false
@State private var accessibilityEnabled = false
@State private var hotkeyShortcut: HotkeyShortcut = SettingsStore.shared.hotkeyShortcut
@@ -62,8 +58,8 @@ struct ContentView: View {
@State private var rewriteModeHotkeyShortcut: HotkeyShortcut = SettingsStore.shared.rewriteModeHotkeyShortcut
@State private var isCommandModeShortcutEnabled: Bool = SettingsStore.shared.commandModeShortcutEnabled
@State private var isRewriteModeShortcutEnabled: Bool = SettingsStore.shared.rewriteModeShortcutEnabled
- @State private var isRecordingForRewrite: Bool = false // Track if current recording is for rewrite mode
- @State private var isRecordingForCommand: Bool = false // Track if current recording is for command mode
+ @State private var isRecordingForRewrite: Bool = false // Track if current recording is for rewrite mode
+ @State private var isRecordingForCommand: Bool = false // Track if current recording is for command mode
@State private var isRecordingShortcut = false
@State private var isRecordingCommandModeShortcut = false
@State private var isRecordingRewriteShortcut = false
@@ -71,12 +67,12 @@ struct ContentView: View {
@State private var pendingModifierKeyCode: UInt16?
@State private var pendingModifierOnly = false
@FocusState private var isTranscriptionFocused: Bool
-
+
@State private var selectedSidebarItem: SidebarItem? = .welcome
- @State private var previousSidebarItem: SidebarItem? = nil // Track previous for mode transitions
+ @State private var previousSidebarItem: SidebarItem? = nil // Track previous for mode transitions
@State private var playgroundUsed: Bool = SettingsStore.shared.playgroundUsed
@State private var recordingAppInfo: (name: String, bundleId: String, windowTitle: String)? = nil
-
+
// Command Mode State
// @State private var showCommandMode: Bool = false
@@ -86,13 +82,13 @@ struct ContentView: View {
@State private var outputDevices: [AudioDevice.Device] = []
@State private var selectedInputUID: String = SettingsStore.shared.preferredInputDeviceUID ?? ""
@State private var selectedOutputUID: String = SettingsStore.shared.preferredOutputDeviceUID ?? ""
-
+
// AI Prompts Tab State
@State private var aiInputText: String = ""
@State private var aiOutputText: String = ""
@State private var isCallingAI: Bool = false
@State private var openAIBaseURL: String = "https://api.openai.com/v1"
-
+
@State private var enableDebugLogs: Bool = SettingsStore.shared.enableDebugLogs
@State private var pressAndHoldModeEnabled: Bool = SettingsStore.shared.pressAndHoldMode
@State private var enableStreamingPreview: Bool = SettingsStore.shared.enableStreamingPreview
@@ -106,8 +102,9 @@ struct ContentView: View {
private let accessibilityRestartFlagKey = "FluidVoice_AccessibilityRestartPending"
private let hasAutoRestartedForAccessibilityKey = "FluidVoice_HasAutoRestartedForAccessibility"
@State private var accessibilityPollingTask: Task<Void, Never>?
-
+
// MARK: - Voice Recognition Model Management
+
// Models scoped by provider (name -> [models])
@State private var availableModelsByProvider: [String: [String]] = [:]
@State private var selectedModelByProvider: [String: String] = [:]
@@ -115,101 +112,100 @@ struct ContentView: View {
@State private var selectedModel: String = "gpt-4.1" // derived from currentProvider
@State private var showingAddModel: Bool = false
@State private var newModelName: String = ""
-
+
// Model Reasoning Configuration
@State private var showingReasoningConfig: Bool = false
@State private var editingReasoningParamName: String = "reasoning_effort"
@State private var editingReasoningParamValue: String = "low"
@State private var editingReasoningEnabled: Bool = false
-
+
// MARK: - Provider Management
+
@State private var providerAPIKeys: [String: String] = [:] // [providerKey: apiKey]
@State private var currentProvider: String = "openai" // canonical key: "openai" | "groq" | "custom:<id>"
@State private var savedProviders: [SettingsStore.SavedProvider] = []
@State private var selectedProviderID: String = SettingsStore.shared.selectedProviderID
-
-
var body: some View {
- let splitView: AnyView = AnyView(
- NavigationSplitView {
- sidebarView
- .navigationSplitViewColumnWidth(min: 220, ideal: 250, max: 300)
- } detail: {
- detailView
- }
- )
+ let splitView = AnyView(NavigationSplitView {
+ self.sidebarView
+ .navigationSplitViewColumnWidth(min: 220, ideal: 250, max: 300)
+ } detail: {
+ self.detailView
+ })
let tracked = splitView.withMouseTracking(mouseTracker)
let env = tracked.environmentObject(mouseTracker)
let nav = env.onChange(of: menuBarManager.requestedNavigationDestination) { _, destination in
- handleMenuBarNavigation(destination)
+ self.handleMenuBarNavigation(destination)
}
return nav.onAppear {
- appear = true
- accessibilityEnabled = checkAccessibilityPermissions()
-
+ self.appear = true
+ self.accessibilityEnabled = self.checkAccessibilityPermissions()
+
// Handle any pending menu-bar navigation (e.g., Preferences clicked before window existed).
- handleMenuBarNavigation(menuBarManager.requestedNavigationDestination)
+ self.handleMenuBarNavigation(self.menuBarManager.requestedNavigationDestination)
// If a previous run set a pending restart, clear it now on fresh launch
- if UserDefaults.standard.bool(forKey: accessibilityRestartFlagKey) {
- UserDefaults.standard.set(false, forKey: accessibilityRestartFlagKey)
- showRestartPrompt = false
+ if UserDefaults.standard.bool(forKey: self.accessibilityRestartFlagKey) {
+ UserDefaults.standard.set(false, forKey: self.accessibilityRestartFlagKey)
+ self.showRestartPrompt = false
}
// Ensure no restart UI shows if we already have trust
- if accessibilityEnabled { showRestartPrompt = false }
-
+ if self.accessibilityEnabled { self.showRestartPrompt = false }
+
// Reset auto-restart flag if permission was revoked (allows re-triggering if user re-grants)
- if !accessibilityEnabled {
- UserDefaults.standard.set(false, forKey: hasAutoRestartedForAccessibilityKey)
+ if !self.accessibilityEnabled {
+ UserDefaults.standard.set(false, forKey: self.hasAutoRestartedForAccessibilityKey)
}
-
+
// Initialize menu bar after app is ready (prevents window server crash)
- menuBarManager.initializeMenuBar()
-
+ self.menuBarManager.initializeMenuBar()
+
// Configure menu bar manager with ASR service
- menuBarManager.configure(asrService: asr)
-
+ self.menuBarManager.configure(asrService: self.asr)
+
// CRITICAL FIX: Defer all audio subsystem initialization by 1.5 seconds.
- // There is a known race condition between CoreAudio's HALSystem initialization (triggered by
+ // There is a known race condition between CoreAudio's HALSystem initialization (triggered by
// AudioObjectAddPropertyListenerBlock) and SwiftUI's AttributeGraph metadata processing during app launch.
// This race causes an EXC_BAD_ACCESS (SIGSEGV) at 0x0.
// By waiting for the main runloop to settle and SwiftUI to finish its initial layout passes,
// we ensure the audio system initializes safely.
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
DebugLogger.shared.info("🔊 Starting delayed audio initialization...", source: "ContentView")
-
- audioObserver.startObserving()
- asr.initialize()
-
+
+ self.audioObserver.startObserving()
+ self.asr.initialize()
+
// Load available devices
- refreshDevices()
-
+ self.refreshDevices()
+
// Set default selection if empty
- if selectedInputUID.isEmpty, let defIn = AudioDevice.getDefaultInputDevice()?.uid { selectedInputUID = defIn }
- if selectedOutputUID.isEmpty, let defOut = AudioDevice.getDefaultOutputDevice()?.uid { selectedOutputUID = defOut }
-
+ if self.selectedInputUID.isEmpty,
+ let defIn = AudioDevice.getDefaultInputDevice()?.uid { self.selectedInputUID = defIn }
+ if self.selectedOutputUID.isEmpty,
+ let defOut = AudioDevice.getDefaultOutputDevice()?.uid { self.selectedOutputUID = defOut }
+
// Load saved preferences for UI display (but don't force system defaults)
// FluidVoice should NOT control system-wide audio routing
if let prefIn = SettingsStore.shared.preferredInputDeviceUID,
prefIn.isEmpty == false,
inputDevices.first(where: { $0.uid == prefIn }) != nil
{
- selectedInputUID = prefIn
+ self.selectedInputUID = prefIn
}
-
+
if let prefOut = SettingsStore.shared.preferredOutputDeviceUID,
prefOut.isEmpty == false,
outputDevices.first(where: { $0.uid == prefOut }) != nil
{
- selectedOutputUID = prefOut
+ self.selectedOutputUID = prefOut
}
-
+
DebugLogger.shared.info("✅ Audio subsystems initialized", source: "ContentView")
}
-
+
// Set up notch click callback for expanding command conversation
NotchOverlayManager.shared.onNotchClicked = {
// When notch is clicked in command mode, show expanded conversation
@@ -217,57 +213,57 @@ struct ContentView: View {
NotchOverlayManager.shared.showExpandedCommandOutput()
}
}
-
+
// Set up command mode callbacks for notch
NotchOverlayManager.shared.onCommandFollowUp = { [weak commandModeService] text in
await commandModeService?.processFollowUpCommand(text)
}
-
+
// Chat management callbacks
NotchOverlayManager.shared.onNewChat = { [weak commandModeService] in
commandModeService?.createNewChat()
}
-
+
NotchOverlayManager.shared.onSwitchChat = { [weak commandModeService] chatID in
commandModeService?.switchToChat(id: chatID)
}
-
+
NotchOverlayManager.shared.onClearChat = { [weak commandModeService] in
commandModeService?.deleteCurrentChat()
}
-
+
// Start polling for accessibility permission if not granted
- startAccessibilityPolling()
-
+ self.startAccessibilityPolling()
+
// Initialize hotkey manager with improved timing and validation
- initializeHotkeyManagerIfNeeded()
-
+ self.initializeHotkeyManagerIfNeeded()
+
// Note: Overlay is now managed by MenuBarManager (persists even when window closed)
-
+
// Devices loaded in delayed audio initialization block
// Device defaults and preferences handled in delayed block
-
+
// Preload ASR model on app startup (with small delay to let app initialize)
Task {
try? await Task.sleep(nanoseconds: 1_000_000_000) // 1 second delay
- await preloadASRModel()
+ await self.preloadASRModel()
}
-
+
// Load saved provider ID first
- selectedProviderID = SettingsStore.shared.selectedProviderID
-
+ self.selectedProviderID = SettingsStore.shared.selectedProviderID
+
// Establish provider context first
- updateCurrentProvider()
+ self.updateCurrentProvider()
- enableDebugLogs = SettingsStore.shared.enableDebugLogs
- availableModelsByProvider = SettingsStore.shared.availableModelsByProvider
- selectedModelByProvider = SettingsStore.shared.selectedModelByProvider
- providerAPIKeys = SettingsStore.shared.providerAPIKeys
- savedProviders = SettingsStore.shared.savedProviders
+ self.enableDebugLogs = SettingsStore.shared.enableDebugLogs
+ self.availableModelsByProvider = SettingsStore.shared.availableModelsByProvider
+ self.selectedModelByProvider = SettingsStore.shared.selectedModelByProvider
+ self.providerAPIKeys = SettingsStore.shared.providerAPIKeys
+ self.savedProviders = SettingsStore.shared.savedProviders
// Migration & cleanup: normalize provider keys and drop legacy flat lists
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" { newKey = lower }
@@ -276,49 +272,65 @@ struct ContentView: 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 selectedModelByProvider keys similarly and drop invalid selections
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)")
+ 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 without legacy flat-list fallback
if let saved = savedProviders.first(where: { $0.id == selectedProviderID }) {
// Use models from saved provider
- availableModels = saved.models
- openAIBaseURL = saved.baseURL
+ self.availableModels = saved.models
+ self.openAIBaseURL = saved.baseURL
} else if let stored = availableModelsByProvider[currentProvider], !stored.isEmpty {
// Use provider-specific stored list if present
- availableModels = stored
+ self.availableModels = stored
} else {
// Built-in defaults
- availableModels = defaultModels(for: providerKey(for: selectedProviderID))
+ self.availableModels = self.defaultModels(for: self.providerKey(for: self.selectedProviderID))
}
// Restore previously selected model if valid
if let sel = selectedModelByProvider[currentProvider], availableModels.contains(sel) {
- selectedModel = sel
+ self.selectedModel = sel
} else if let first = availableModels.first {
- selectedModel = first
+ self.selectedModel = first
}
-
+
NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .flagsChanged]) { event in
let eventModifiers = event.modifierFlags.intersection([.function, .command, .option, .control, .shift])
- let shortcutModifiers = hotkeyShortcut.modifierFlags.intersection([.function, .command, .option, .control, .shift])
-
- let isRecordingAnyShortcut = isRecordingShortcut || isRecordingCommandModeShortcut || isRecordingRewriteShortcut
- DebugLogger.shared.debug("NSEvent \(event.type) keyCode=\(event.keyCode) recordingShortcut=\(isRecordingShortcut) recordingCommand=\(isRecordingCommandModeShortcut) recordingRewrite=\(isRecordingRewriteShortcut)", source: "ContentView")
+ let shortcutModifiers = self.hotkeyShortcut.modifierFlags.intersection([
+ .function,
+ .command,
+ .option,
+ .control,
+ .shift,
+ ])
+
+ let isRecordingAnyShortcut = self.isRecordingShortcut || self.isRecordingCommandModeShortcut || self
+ .isRecordingRewriteShortcut
+ DebugLogger.shared
+ .debug(
+ "NSEvent \(event.type) keyCode=\(event.keyCode) recordingShortcut=\(self.isRecordingShortcut) recordingCommand=\(self.isRecordingCommandModeShortcut) recordingRewrite=\(self.isRecordingRewriteShortcut)",
+ source: "ContentView"
+ )
if event.type == .keyDown {
- if event.keyCode == hotkeyShortcut.keyCode && eventModifiers == shortcutModifiers {
- DebugLogger.shared.debug("NSEvent monitor: Global hotkey matched on keyDown, passing event through (GlobalHotkeyManager handles)", source: "ContentView")
+ if event.keyCode == self.hotkeyShortcut.keyCode && eventModifiers == shortcutModifiers {
+ DebugLogger.shared
+ .debug(
+ "NSEvent monitor: Global hotkey matched on keyDown, passing event through (GlobalHotkeyManager handles)",
+ source: "ContentView"
+ )
return event
}
@@ -326,110 +338,141 @@ struct ContentView: View {
if event.keyCode == 53 {
// Escape pressed - handle cancellation
var handled = false
-
+
// Close expanded command notch if visible (highest priority)
if NotchOverlayManager.shared.isCommandOutputExpanded {
- DebugLogger.shared.debug("NSEvent monitor: Escape pressed, closing expanded command notch", source: "ContentView")
+ DebugLogger.shared
+ .debug(
+ "NSEvent monitor: Escape pressed, closing expanded command notch",
+ source: "ContentView"
+ )
NotchOverlayManager.shared.hideExpandedCommandOutput()
handled = true
}
-
- if asr.isRunning {
- DebugLogger.shared.debug("NSEvent monitor: Escape pressed, cancelling ASR recording", source: "ContentView")
- asr.stopWithoutTranscription()
+
+ if self.asr.isRunning {
+ DebugLogger.shared.debug(
+ "NSEvent monitor: Escape pressed, cancelling ASR recording",
+ source: "ContentView"
+ )
+ self.asr.stopWithoutTranscription()
handled = true
}
-
+
// Close mode views if active
- if selectedSidebarItem == .commandMode || selectedSidebarItem == .rewriteMode {
- DebugLogger.shared.debug("NSEvent monitor: Escape pressed, closing mode view", source: "ContentView")
- selectedSidebarItem = .welcome
+ if self.selectedSidebarItem == .commandMode || self.selectedSidebarItem == .rewriteMode {
+ DebugLogger.shared.debug(
+ "NSEvent monitor: Escape pressed, closing mode view",
+ source: "ContentView"
+ )
+ self.selectedSidebarItem = .welcome
handled = true
}
-
+
if handled {
- return nil // Suppress beep
+ return nil // Suppress beep
}
}
- resetPendingShortcutState()
+ self.resetPendingShortcutState()
return event
}
-
+
let keyCode = event.keyCode
if keyCode == 53 {
- DebugLogger.shared.debug("NSEvent monitor: Escape pressed, cancelling shortcut recording", source: "ContentView")
- isRecordingShortcut = false
- isRecordingCommandModeShortcut = false
- isRecordingRewriteShortcut = false
- resetPendingShortcutState()
+ DebugLogger.shared.debug(
+ "NSEvent monitor: Escape pressed, cancelling shortcut recording",
+ source: "ContentView"
+ )
+ self.isRecordingShortcut = false
+ self.isRecordingCommandModeShortcut = false
+ self.isRecordingRewriteShortcut = false
+ self.resetPendingShortcutState()
return nil
}
-
- let combinedModifiers = pendingModifierFlags.union(eventModifiers)
+
+ let combinedModifiers = self.pendingModifierFlags.union(eventModifiers)
let newShortcut = HotkeyShortcut(keyCode: keyCode, modifierFlags: combinedModifiers)
- DebugLogger.shared.debug("NSEvent monitor: Recording new shortcut: \(newShortcut.displayString)", source: "ContentView")
-
- if isRecordingRewriteShortcut {
- rewriteModeHotkeyShortcut = newShortcut
+ DebugLogger.shared.debug(
+ "NSEvent monitor: Recording new shortcut: \(newShortcut.displayString)",
+ source: "ContentView"
+ )
+
+ if self.isRecordingRewriteShortcut {
+ self.rewriteModeHotkeyShortcut = newShortcut
SettingsStore.shared.rewriteModeHotkeyShortcut = newShortcut
- hotkeyManager?.updateRewriteModeShortcut(newShortcut)
- isRecordingRewriteShortcut = false
- } else if isRecordingCommandModeShortcut {
- commandModeHotkeyShortcut = newShortcut
+ self.hotkeyManager?.updateRewriteModeShortcut(newShortcut)
+ self.isRecordingRewriteShortcut = false
+ } else if self.isRecordingCommandModeShortcut {
+ self.commandModeHotkeyShortcut = newShortcut
SettingsStore.shared.commandModeHotkeyShortcut = newShortcut
- hotkeyManager?.updateCommandModeShortcut(newShortcut)
- isRecordingCommandModeShortcut = false
+ self.hotkeyManager?.updateCommandModeShortcut(newShortcut)
+ self.isRecordingCommandModeShortcut = false
} else {
- hotkeyShortcut = newShortcut
+ self.hotkeyShortcut = newShortcut
SettingsStore.shared.hotkeyShortcut = newShortcut
- hotkeyManager?.updateShortcut(newShortcut)
- isRecordingShortcut = false
+ self.hotkeyManager?.updateShortcut(newShortcut)
+ self.isRecordingShortcut = false
}
- resetPendingShortcutState()
+ self.resetPendingShortcutState()
DebugLogger.shared.debug("NSEvent monitor: Finished recording shortcut", source: "ContentView")
return nil
} else if event.type == .flagsChanged {
- if hotkeyShortcut.modifierFlags.isEmpty {
+ if self.hotkeyShortcut.modifierFlags.isEmpty {
let isModifierKeyPressed = eventModifiers.isEmpty == false
- if event.keyCode == hotkeyShortcut.keyCode && isModifierKeyPressed {
- DebugLogger.shared.debug("NSEvent monitor: Global hotkey matched on flagsChanged, passing event through (GlobalHotkeyManager handles)", source: "ContentView")
+ if event.keyCode == self.hotkeyShortcut.keyCode && isModifierKeyPressed {
+ DebugLogger.shared
+ .debug(
+ "NSEvent monitor: Global hotkey matched on flagsChanged, passing event through (GlobalHotkeyManager handles)",
+ source: "ContentView"
+ )
return event
}
}
guard isRecordingAnyShortcut else {
- resetPendingShortcutState()
+ self.resetPendingShortcutState()
return event
}
if eventModifiers.isEmpty {
- if pendingModifierOnly, let modifierKeyCode = pendingModifierKeyCode {
+ if self.pendingModifierOnly, let modifierKeyCode = pendingModifierKeyCode {
let newShortcut = HotkeyShortcut(keyCode: modifierKeyCode, modifierFlags: [])
- DebugLogger.shared.debug("NSEvent monitor: Recording modifier-only shortcut: \(newShortcut.displayString)", source: "ContentView")
-
- if isRecordingRewriteShortcut {
- rewriteModeHotkeyShortcut = newShortcut
+ DebugLogger.shared
+ .debug(
+ "NSEvent monitor: Recording modifier-only shortcut: \(newShortcut.displayString)",
+ source: "ContentView"
+ )
+
+ if self.isRecordingRewriteShortcut {
+ self.rewriteModeHotkeyShortcut = newShortcut
SettingsStore.shared.rewriteModeHotkeyShortcut = newShortcut
- hotkeyManager?.updateRewriteModeShortcut(newShortcut)
- isRecordingRewriteShortcut = false
- } else if isRecordingCommandModeShortcut {
- commandModeHotkeyShortcut = newShortcut
+ self.hotkeyManager?.updateRewriteModeShortcut(newShortcut)
+ self.isRecordingRewriteShortcut = false
+ } else if self.isRecordingCommandModeShortcut {
+ self.commandModeHotkeyShortcut = newShortcut
SettingsStore.shared.commandModeHotkeyShortcut = newShortcut
- hotkeyManager?.updateCommandModeShortcut(newShortcut)
- isRecordingCommandModeShortcut = false
+ self.hotkeyManager?.updateCommandModeShortcut(newShortcut)
+ self.isRecordingCommandModeShortcut = false
} else {
- hotkeyShortcut = newShortcut
+ self.hotkeyShortcut = newShortcut
SettingsStore.shared.hotkeyShortcut = newShortcut
- hotkeyManager?.updateShortcut(newShortcut)
- isRecordingShortcut = false
+ self.hotkeyManager?.updateShortcut(newShortcut)
+ self.isRecordingShortcut = false
}
- resetPendingShortcutState()
- DebugLogger.shared.debug("NSEvent monitor: Finished recording modifier shortcut", source: "ContentView")
+ self.resetPendingShortcutState()
+ DebugLogger.shared.debug(
+ "NSEvent monitor: Finished recording modifier shortcut",
+ source: "ContentView"
+ )
return nil
}
- resetPendingShortcutState()
- DebugLogger.shared.debug("NSEvent monitor: Modifiers released without recording, continuing to wait", source: "ContentView")
+ self.resetPendingShortcutState()
+ DebugLogger.shared
+ .debug(
+ "NSEvent monitor: Modifiers released without recording, continuing to wait",
+ source: "ContentView"
+ )
return nil
}
@@ -447,26 +490,30 @@ struct ContentView: View {
actualKeyCode = (event.keyCode == 56) ? 56 : 60 // 56 = left shift, 60 = right shift
}
- pendingModifierFlags = eventModifiers
- pendingModifierKeyCode = actualKeyCode
- pendingModifierOnly = true
- DebugLogger.shared.debug("NSEvent monitor: Modifier key pressed during recording, pending modifiers: \(pendingModifierFlags)", source: "ContentView")
+ self.pendingModifierFlags = eventModifiers
+ self.pendingModifierKeyCode = actualKeyCode
+ self.pendingModifierOnly = true
+ DebugLogger.shared
+ .debug(
+ "NSEvent monitor: Modifier key pressed during recording, pending modifiers: \(self.pendingModifierFlags)",
+ source: "ContentView"
+ )
return nil
}
-
+
return event
}
}
.onChange(of: accessibilityEnabled) { _, enabled in
- if enabled && hotkeyManager != nil && !hotkeyManagerInitialized {
+ if enabled && self.hotkeyManager != nil && !self.hotkeyManagerInitialized {
DebugLogger.shared.debug("Accessibility enabled, reinitializing hotkey manager", source: "ContentView")
- hotkeyManager?.reinitialize()
+ self.hotkeyManager?.reinitialize()
}
}
.onChange(of: selectedModel) { _, newValue in
if newValue != "__ADD_MODEL__" {
- selectedModelByProvider[currentProvider] = newValue
- SettingsStore.shared.selectedModelByProvider = selectedModelByProvider
+ self.selectedModelByProvider[self.currentProvider] = newValue
+ SettingsStore.shared.selectedModelByProvider = self.selectedModelByProvider
}
}
.onChange(of: selectedProviderID) { _, newValue in
@@ -474,95 +521,100 @@ struct ContentView: View {
}
.onChange(of: isCommandModeShortcutEnabled) { newValue in
SettingsStore.shared.commandModeShortcutEnabled = newValue
- hotkeyManager?.updateCommandModeShortcutEnabled(newValue)
-
+ self.hotkeyManager?.updateCommandModeShortcutEnabled(newValue)
+
if !newValue {
- isRecordingCommandModeShortcut = false
-
- if isRecordingForCommand {
- if asr.isRunning {
- asr.stopWithoutTranscription()
+ self.isRecordingCommandModeShortcut = false
+
+ if self.isRecordingForCommand {
+ if self.asr.isRunning {
+ self.asr.stopWithoutTranscription()
}
- isRecordingForCommand = false
- menuBarManager.setOverlayMode(.dictation)
+ self.isRecordingForCommand = false
+ self.menuBarManager.setOverlayMode(.dictation)
}
}
}
.onChange(of: isRewriteModeShortcutEnabled) { newValue in
SettingsStore.shared.rewriteModeShortcutEnabled = newValue
- hotkeyManager?.updateRewriteModeShortcutEnabled(newValue)
-
+ self.hotkeyManager?.updateRewriteModeShortcutEnabled(newValue)
+
if !newValue {
- isRecordingRewriteShortcut = false
-
- if isRecordingForRewrite {
- if asr.isRunning {
- asr.stopWithoutTranscription()
+ self.isRecordingRewriteShortcut = false
+
+ if self.isRecordingForRewrite {
+ if self.asr.isRunning {
+ self.asr.stopWithoutTranscription()
}
- isRecordingForRewrite = false
- rewriteModeService.clearState()
- menuBarManager.setOverlayMode(.dictation)
+ self.isRecordingForRewrite = false
+ self.rewriteModeService.clearState()
+ self.menuBarManager.setOverlayMode(.dictation)
}
}
}
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
let trusted = AXIsProcessTrusted()
- if trusted != accessibilityEnabled {
- accessibilityEnabled = trusted
+ if trusted != self.accessibilityEnabled {
+ self.accessibilityEnabled = trusted
}
}
- .overlay(alignment: .center) {
- }
-
+ .overlay(alignment: .center) {}
.alert(asr.errorTitle, isPresented: $asr.showError) {
- Button("OK", role: .cancel) { }
+ Button("OK", role: .cancel) {}
} message: {
- Text(asr.errorMessage)
+ Text(self.asr.errorMessage)
}
.onChange(of: 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.
// The saved preferences are only used when FluidVoice actively records.
- refreshDevices()
+ self.refreshDevices()
// Just sync the UI to show current system defaults (don't force them)
if let sysIn = AudioDevice.getDefaultInputDevice()?.uid {
- selectedInputUID = sysIn
+ self.selectedInputUID = sysIn
}
if let sysOut = AudioDevice.getDefaultOutputDevice()?.uid {
- selectedOutputUID = sysOut
+ self.selectedOutputUID = sysOut
}
}
.onDisappear {
- asr.stopWithoutTranscription()
+ self.asr.stopWithoutTranscription()
// Note: Overlay lifecycle is now managed by MenuBarManager
-
+
// Stop accessibility polling
- accessibilityPollingTask?.cancel()
- accessibilityPollingTask = nil
+ self.accessibilityPollingTask?.cancel()
+ self.accessibilityPollingTask = nil
}
.onChange(of: hotkeyShortcut) { _, newValue in
DebugLogger.shared.debug("Hotkey shortcut changed to \(newValue.displayString)", source: "ContentView")
- hotkeyManager?.updateShortcut(newValue)
+ self.hotkeyManager?.updateShortcut(newValue)
// Update initialization status after shortcut change
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.hotkeyManagerInitialized = self.hotkeyManager?.validateEventTapHealth() ?? false
- DebugLogger.shared.debug("Hotkey manager initialized: \(self.hotkeyManagerInitialized)", source: "ContentView")
+ DebugLogger.shared.debug(
+ "Hotkey manager initialized: \(self.hotkeyManagerInitialized)",
+ source: "ContentView"
+ )
}
}
.onChange(of: selectedSidebarItem) { _, newValue in
- handleModeTransition(from: previousSidebarItem, to: newValue)
- previousSidebarItem = newValue
+ self.handleModeTransition(from: self.previousSidebarItem, to: newValue)
+ self.previousSidebarItem = newValue
}
}
-
+
// MARK: - Mode Transition Handler
+
/// Centralized handler for sidebar mode transitions to ensure proper cleanup and state management
private func handleModeTransition(from oldValue: SidebarItem?, to newValue: SidebarItem?) {
- DebugLogger.shared.debug("Mode transition: \(String(describing: oldValue)) → \(String(describing: newValue))", source: "ContentView")
-
+ DebugLogger.shared.debug(
+ "Mode transition: \(String(describing: oldValue)) → \(String(describing: newValue))",
+ source: "ContentView"
+ )
+
// Clean up state from the previous mode
if let old = oldValue {
switch old {
@@ -573,22 +625,22 @@ struct ContentView: View {
NotchOverlayManager.shared.hideExpandedCommandOutput()
}
// Note: We don't clear command history here - user may want to return to it
-
+
case .rewriteMode:
// Clear rewrite state when leaving
rewriteModeService.clearState()
-
+
default:
break
}
}
-
+
// Set up state for the new mode
if let new = newValue {
switch new {
case .commandMode:
menuBarManager.setOverlayMode(.command)
-
+
case .rewriteMode:
// Check if in write mode (no original text) vs rewrite mode
if rewriteModeService.isWriteMode || rewriteModeService.originalText.isEmpty {
@@ -596,7 +648,7 @@ struct ContentView: View {
} else {
menuBarManager.setOverlayMode(.rewrite)
}
-
+
default:
// For all other views, set to dictation mode
menuBarManager.setOverlayMode(.dictation)
@@ -606,20 +658,19 @@ struct ContentView: View {
menuBarManager.setOverlayMode(.dictation)
}
}
-
+
@MainActor
private func handleMenuBarNavigation(_ destination: MenuBarNavigationDestination?) {
guard let destination else { return }
defer { menuBarManager.requestedNavigationDestination = nil }
-
+
switch destination {
case .preferences:
selectedSidebarItem = .preferences
}
}
- private func resetPendingShortcutState()
- {
+ private func resetPendingShortcutState() {
pendingModifierFlags = []
pendingModifierKeyCode = nil
pendingModifierOnly = false
@@ -631,17 +682,17 @@ struct ContentView: View {
Label("Welcome", systemImage: "house.fill")
.font(.system(size: 15, weight: .medium))
}
-
+
NavigationLink(value: SidebarItem.aiSettings) {
Label("AI Settings", systemImage: "sparkles")
.font(.system(size: 15, weight: .medium))
}
-
+
NavigationLink(value: SidebarItem.commandMode) {
Label("Command Mode", systemImage: "terminal.fill")
.font(.system(size: 15, weight: .medium))
}
-
+
NavigationLink(value: SidebarItem.rewriteMode) {
Label("Write Mode", systemImage: "pencil.and.outline")
.font(.system(size: 15, weight: .medium))
@@ -656,12 +707,12 @@ struct ContentView: View {
Label("Stats", systemImage: "chart.bar.fill")
.font(.system(size: 15, weight: .medium))
}
-
+
NavigationLink(value: SidebarItem.history) {
Label("History", systemImage: "clock.arrow.circlepath")
.font(.system(size: 15, weight: .medium))
}
-
+
NavigationLink(value: SidebarItem.preferences) {
Label("Preferences", systemImage: "gearshape.fill")
.font(.system(size: 15, weight: .medium))
@@ -677,24 +728,24 @@ struct ContentView: View {
.scrollContentBackground(.hidden)
.background {
ZStack {
- theme.palette.sidebarBackground
- Rectangle().fill(theme.materials.sidebar)
+ self.theme.palette.sidebarBackground
+ Rectangle().fill(self.theme.materials.sidebar)
}
.ignoresSafeArea()
}
.tint(theme.palette.accent)
}
-
+
private var detailView: some View {
ZStack {
- theme.palette.windowBackground
+ self.theme.palette.windowBackground
.ignoresSafeArea()
Rectangle()
- .fill(theme.materials.window)
+ .fill(self.theme.materials.window)
.ignoresSafeArea()
- detailContent
+ self.detailContent
.transition(.opacity)
}
.toolbar(.hidden, for: .automatic)
@@ -724,9 +775,9 @@ struct ContentView: View {
}
// MARK: - Welcome Guide
+
private var welcomeView: some View {
WelcomeView(
-
selectedSidebarItem: $selectedSidebarItem,
playgroundUsed: $playgroundUsed,
isTranscriptionFocused: $isTranscriptionFocused,
@@ -736,50 +787,52 @@ struct ContentView: View {
openAIBaseURL: openAIBaseURL,
availableModels: availableModels,
selectedModel: selectedModel,
- stopAndProcessTranscription: { await stopAndProcessTranscription() },
+ stopAndProcessTranscription: { await self.stopAndProcessTranscription() },
startRecording: startRecording,
isLocalEndpoint: isLocalEndpoint,
openAccessibilitySettings: openAccessibilitySettings
)
}
-
+
// MARK: - Microphone Permission View (Kept inline for RecordingView)
+
private var microphonePermissionView: some View {
VStack(alignment: .leading, spacing: 12) {
HStack(spacing: 12) {
// Status indicator
Circle()
- .fill(asr.micStatus == .authorized ? theme.palette.success : theme.palette.warning)
+ .fill(self.asr.micStatus == .authorized ? self.theme.palette.success : self.theme.palette.warning)
.frame(width: 10, height: 10)
-
+
VStack(alignment: .leading, spacing: 4) {
- Text(labelFor(status: asr.micStatus))
+ Text(self.labelFor(status: self.asr.micStatus))
.fontWeight(.medium)
- .foregroundStyle(asr.micStatus == .authorized ? theme.palette.primaryText : theme.palette.warning)
-
- if asr.micStatus != .authorized {
+ .foregroundStyle(self.asr.micStatus == .authorized ? self.theme.palette.primaryText : self.theme
+ .palette.warning)
+
+ if self.asr.micStatus != .authorized {
Text("Microphone access is required for voice recording")
.font(.caption)
.foregroundStyle(.secondary)
}
}
Spacer()
-
- microphoneActionButton
+
+ self.microphoneActionButton
}
-
+
// Step-by-step instructions when microphone is not authorized
- if asr.micStatus != .authorized {
- microphoneInstructionsView
+ if self.asr.micStatus != .authorized {
+ self.microphoneInstructionsView
}
}
}
-
+
private var microphoneActionButton: some View {
Group {
- if asr.micStatus == .notDetermined {
+ if self.asr.micStatus == .notDetermined {
Button {
- asr.requestMicAccess()
+ self.asr.requestMicAccess()
} label: {
HStack(spacing: 6) {
Image(systemName: "mic.fill")
@@ -789,9 +842,9 @@ struct ContentView: View {
}
.buttonStyle(GlassButtonStyle())
.buttonHoverEffect()
- } else if asr.micStatus == .denied {
+ } else if self.asr.micStatus == .denied {
Button {
- asr.openSystemSettingsForMic()
+ self.asr.openSystemSettingsForMic()
} label: {
HStack(spacing: 6) {
Image(systemName: "gear")
@@ -804,27 +857,27 @@ struct ContentView: View {
}
}
}
-
+
private var microphoneInstructionsView: some View {
VStack(alignment: .leading, spacing: 8) {
HStack(spacing: 8) {
Image(systemName: "info.circle.fill")
- .foregroundStyle(theme.palette.accent)
+ .foregroundStyle(self.theme.palette.accent)
.font(.caption)
Text("How to enable microphone access:")
.font(.caption)
.fontWeight(.medium)
.foregroundStyle(.secondary)
}
-
+
VStack(alignment: .leading, spacing: 4) {
- if asr.micStatus == .notDetermined {
- instructionStep(number: "1", text: "Click **Grant Access** above")
- instructionStep(number: "2", text: "Choose **Allow** in the system dialog")
- } else if asr.micStatus == .denied {
- instructionStep(number: "1", text: "Click **Open Settings** above")
- instructionStep(number: "2", text: "Find **FluidVoice** in the microphone list")
- instructionStep(number: "3", text: "Toggle **FluidVoice ON** to allow access")
+ if self.asr.micStatus == .notDetermined {
+ self.instructionStep(number: "1", text: "Click **Grant Access** above")
+ self.instructionStep(number: "2", text: "Choose **Allow** in the system dialog")
+ } else if self.asr.micStatus == .denied {
+ self.instructionStep(number: "1", text: "Click **Open Settings** above")
+ self.instructionStep(number: "2", text: "Find **FluidVoice** in the microphone list")
+ self.instructionStep(number: "3", text: "Toggle **FluidVoice ON** to allow access")
}
}
.padding(.leading, 4)
@@ -833,12 +886,12 @@ struct ContentView: View {
.background(theme.palette.accent.opacity(0.12))
.cornerRadius(8)
}
-
+
private func instructionStep(number: String, text: String) -> some View {
HStack(spacing: 8) {
Text(number + ".")
.font(.caption2)
- .foregroundStyle(theme.palette.accent)
+ .foregroundStyle(self.theme.palette.accent)
.fontWeight(.semibold)
.frame(width: 16)
Text(text)
@@ -848,9 +901,9 @@ struct ContentView: View {
}
// MARK: - Preferences View
+
private var preferencesView: some View {
SettingsView(
-
appear: $appear,
visualizerNoiseThreshold: $visualizerNoiseThreshold,
selectedInputUID: $selectedInputUID,
@@ -883,19 +936,18 @@ struct ContentView: View {
private var recordingView: some View {
RecordingView(
-
appear: $appear,
- stopAndProcessTranscription: { await stopAndProcessTranscription() },
+ stopAndProcessTranscription: { await self.stopAndProcessTranscription() },
startRecording: startRecording
)
}
-
+
private var commandModeView: some View {
CommandModeView(service: commandModeService, onClose: {
self.selectedSidebarItem = .welcome
})
}
-
+
private var rewriteModeView: some View {
RewriteModeView(service: rewriteModeService, onClose: {
self.selectedSidebarItem = .welcome
@@ -903,35 +955,35 @@ struct ContentView: View {
}
// MARK: - Meeting Transcription (Coming Soon)
- private var meetingToolsView: some View
- {
+
+ private var meetingToolsView: some View {
MeetingTranscriptionView(asrService: asr)
}
// MARK: - Stats View
+
private var statsView: some View {
StatsView()
}
-
// Audio settings merged into SettingsView
- private func refreshDevices()
- {
+ private func refreshDevices() {
inputDevices = AudioDevice.listInputDevices()
outputDevices = AudioDevice.listOutputDevices()
}
// MARK: - Model Management Functions
+
private func saveModels() { SettingsStore.shared.availableModels = 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)"
}
-
private func defaultModels(for providerKey: String) -> [String] {
switch providerKey {
@@ -941,8 +993,6 @@ struct ContentView: View {
}
}
-
-
private func updateCurrentProvider() {
// Map baseURL to canonical key for built-ins; else keep existing
let url = openAIBaseURL.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
@@ -951,17 +1001,18 @@ struct ContentView: View {
// For saved/custom, keep current or derive from selectedProviderID
currentProvider = providerKey(for: selectedProviderID)
}
-
+
private func saveSavedProviders() {
SettingsStore.shared.savedProviders = savedProviders
}
// MARK: - App Detection and Context-Aware Prompts
+
private func getCurrentAppInfo() -> (name: String, bundleId: String, windowTitle: String) {
if let frontmostApp = NSWorkspace.shared.frontmostApplication {
let name = frontmostApp.localizedName ?? "Unknown"
let bundleId = frontmostApp.bundleIdentifier ?? "unknown"
- let title = self.getFrontmostWindowTitle(ownerPid: frontmostApp.processIdentifier) ?? ""
+ let title = getFrontmostWindowTitle(ownerPid: frontmostApp.processIdentifier) ?? ""
return (name: name, bundleId: bundleId, windowTitle: title)
}
return (name: "Unknown", bundleId: "unknown", windowTitle: "")
@@ -981,116 +1032,117 @@ struct ContentView: View {
}
return nil
}
-
+
// MARK: - Commented out app-specific prompts - using general processing only
+
/*
- private func getContextualPrompt(for appInfo: (name: String, bundleId: String, windowTitle: String)) -> String {
- let appName = appInfo.name
- let bundleId = appInfo.bundleId.lowercased()
- let windowTitle = appInfo.windowTitle.lowercased()
-
- // Code editors and IDEs
- if bundleId.contains("xcode") || bundleId.contains("vscode") || bundleId.contains("sublime") ||
- bundleId.contains("atom") || bundleId.contains("jetbrains") || bundleId.contains("cursor") ||
- bundleId.contains("vim") || bundleId.contains("emacs") || appName.lowercased().contains("code")
- {
- return "Clean up this transcribed text for code editor \(appName). Make the smallest necessary mechanical edits; do not add or invent content or answer questions. Remove fillers and false starts. Correct programming terms and obvious transcription errors. Preserve meaning and tone."
- }
-
- // Email applications
- else if bundleId.contains("mail") || bundleId.contains("outlook") || bundleId.contains("thunderbird") ||
- bundleId.contains("airmail") || bundleId.contains("spark")
- {
- return "Clean up this transcribed text for email app \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix grammar, punctuation, and capitalization while preserving meaning and tone."
- }
-
- // Messaging and chat applications
- else if bundleId.contains("messages") || bundleId.contains("slack") || bundleId.contains("discord") ||
- bundleId.contains("telegram") || bundleId.contains("whatsapp") || bundleId.contains("signal") ||
- bundleId.contains("teams") || bundleId.contains("zoom")
- {
- return "Clean up this transcribed text for messaging app \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix basic grammar and clarity while keeping the casual tone."
- }
-
- // Document editors and word processors
- else if bundleId.contains("pages") || bundleId.contains("word") || bundleId.contains("docs") ||
- bundleId.contains("writer") || bundleId.contains("notion") || bundleId.contains("bear") ||
- bundleId.contains("ulysses") || bundleId.contains("scrivener")
- {
- return "Clean up this transcribed text for document editor \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix grammar, punctuation, and structure while preserving meaning."
- }
-
- // Note-taking applications
- else if bundleId.contains("notes") || bundleId.contains("obsidian") || bundleId.contains("roam") ||
- bundleId.contains("logseq") || bundleId.contains("evernote") || bundleId.contains("onenote")
- {
- return "Clean up this transcribed text for note-taking app \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix grammar and organize into clear, readable notes without adding information."
- }
-
- // Browsers (various web apps). Include: Safari, Chrome, Firefox, Edge, Arc, Brave, Dia, Comet
- else if bundleId.contains("safari") || bundleId.contains("chrome") || bundleId.contains("firefox") ||
- bundleId.contains("edge") || bundleId.contains("arc") || bundleId.contains("brave") ||
- bundleId.contains("dia") || bundleId.contains("comet") ||
- appName.lowercased().contains("safari") || appName.lowercased().contains("chrome") ||
- appName.lowercased().contains("arc") || appName.lowercased().contains("brave") ||
- appName.lowercased().contains("dia") || appName.lowercased().contains("comet")
- {
- // Infer common web apps from window title for better context
- if let inferred = inferWebContext(from: windowTitle, appName: appName) {
- return inferred
- }
- return "Clean up this transcribed text for web browser \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix grammar and basic formatting while preserving meaning."
- }
-
- // Terminal and command line tools
- else if bundleId.contains("terminal") || bundleId.contains("iterm") || bundleId.contains("console") ||
- appName.lowercased().contains("terminal")
- {
- return "Clean up this transcribed text for terminal \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix command syntax, file paths, and technical terms without adding options or commands."
- }
-
- // Social media and creative apps
- else if bundleId.contains("twitter") || bundleId.contains("facebook") || bundleId.contains("instagram") ||
- bundleId.contains("tiktok") || bundleId.contains("linkedin")
- {
- return "Clean up this transcribed text for social media app \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix basic grammar while keeping the natural, engaging tone."
- }
-
- // Default fallback
- else
- {
- return "Clean up this transcribed text for \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix grammar, punctuation, and formatting while preserving meaning and tone."
- }
- }
- */
+ private func getContextualPrompt(for appInfo: (name: String, bundleId: String, windowTitle: String)) -> String {
+ let appName = appInfo.name
+ let bundleId = appInfo.bundleId.lowercased()
+ let windowTitle = appInfo.windowTitle.lowercased()
+
+ // Code editors and IDEs
+ if bundleId.contains("xcode") || bundleId.contains("vscode") || bundleId.contains("sublime") ||
+ bundleId.contains("atom") || bundleId.contains("jetbrains") || bundleId.contains("cursor") ||
+ bundleId.contains("vim") || bundleId.contains("emacs") || appName.lowercased().contains("code")
+ {
+ return "Clean up this transcribed text for code editor \(appName). Make the smallest necessary mechanical edits; do not add or invent content or answer questions. Remove fillers and false starts. Correct programming terms and obvious transcription errors. Preserve meaning and tone."
+ }
+
+ // Email applications
+ else if bundleId.contains("mail") || bundleId.contains("outlook") || bundleId.contains("thunderbird") ||
+ bundleId.contains("airmail") || bundleId.contains("spark")
+ {
+ return "Clean up this transcribed text for email app \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix grammar, punctuation, and capitalization while preserving meaning and tone."
+ }
+
+ // Messaging and chat applications
+ else if bundleId.contains("messages") || bundleId.contains("slack") || bundleId.contains("discord") ||
+ bundleId.contains("telegram") || bundleId.contains("whatsapp") || bundleId.contains("signal") ||
+ bundleId.contains("teams") || bundleId.contains("zoom")
+ {
+ return "Clean up this transcribed text for messaging app \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix basic grammar and clarity while keeping the casual tone."
+ }
+
+ // Document editors and word processors
+ else if bundleId.contains("pages") || bundleId.contains("word") || bundleId.contains("docs") ||
+ bundleId.contains("writer") || bundleId.contains("notion") || bundleId.contains("bear") ||
+ bundleId.contains("ulysses") || bundleId.contains("scrivener")
+ {
+ return "Clean up this transcribed text for document editor \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix grammar, punctuation, and structure while preserving meaning."
+ }
+
+ // Note-taking applications
+ else if bundleId.contains("notes") || bundleId.contains("obsidian") || bundleId.contains("roam") ||
+ bundleId.contains("logseq") || bundleId.contains("evernote") || bundleId.contains("onenote")
+ {
+ return "Clean up this transcribed text for note-taking app \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix grammar and organize into clear, readable notes without adding information."
+ }
+
+ // Browsers (various web apps). Include: Safari, Chrome, Firefox, Edge, Arc, Brave, Dia, Comet
+ else if bundleId.contains("safari") || bundleId.contains("chrome") || bundleId.contains("firefox") ||
+ bundleId.contains("edge") || bundleId.contains("arc") || bundleId.contains("brave") ||
+ bundleId.contains("dia") || bundleId.contains("comet") ||
+ appName.lowercased().contains("safari") || appName.lowercased().contains("chrome") ||
+ appName.lowercased().contains("arc") || appName.lowercased().contains("brave") ||
+ appName.lowercased().contains("dia") || appName.lowercased().contains("comet")
+ {
+ // Infer common web apps from window title for better context
+ if let inferred = inferWebContext(from: windowTitle, appName: appName) {
+ return inferred
+ }
+ return "Clean up this transcribed text for web browser \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix grammar and basic formatting while preserving meaning."
+ }
+
+ // Terminal and command line tools
+ else if bundleId.contains("terminal") || bundleId.contains("iterm") || bundleId.contains("console") ||
+ appName.lowercased().contains("terminal")
+ {
+ return "Clean up this transcribed text for terminal \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix command syntax, file paths, and technical terms without adding options or commands."
+ }
+
+ // Social media and creative apps
+ else if bundleId.contains("twitter") || bundleId.contains("facebook") || bundleId.contains("instagram") ||
+ bundleId.contains("tiktok") || bundleId.contains("linkedin")
+ {
+ return "Clean up this transcribed text for social media app \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix basic grammar while keeping the natural, engaging tone."
+ }
+
+ // Default fallback
+ else
+ {
+ return "Clean up this transcribed text for \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix grammar, punctuation, and formatting while preserving meaning and tone."
+ }
+ }
+ */
/*
- /// Infer web-app specific prompt from a browser window title
- private func inferWebContext(from windowTitle: String, appName: String) -> String? {
- let title = windowTitle
- // Email (Gmail, Outlook Web)
- if title.contains("gmail") || title.contains("inbox") || title.contains("outlook") {
- return "Clean up this transcribed text for email app \(appName) (web). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix grammar, punctuation, and capitalization while preserving meaning."
- }
- // Messaging (Slack, Discord, Teams, Telegram, WhatsApp)
- if title.contains("slack") || title.contains("discord") || title.contains("teams") || title.contains("telegram") || title.contains("whatsapp") {
- return "Clean up this transcribed text for messaging app \(appName) (web). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix basic grammar and clarity while keeping the casual tone."
- }
- // Documents (Google Docs/Sheets, Notion, Confluence)
- if title.contains("google docs") || title.contains("docs") || title.contains("notion") || title.contains("confluence") || title.contains("google sheets") || title.contains("sheet") {
- return "Clean up this transcribed text for a document editor in \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Improve grammar, structure, and readability without adding information."
- }
- // Code (GitHub, Stack Overflow, online IDEs)
- if title.contains("github") || title.contains("stack overflow") || title.contains("stackexchange") || title.contains("replit") || title.contains("codesandbox") {
- return "Clean up this transcribed text for code-related context in \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Correct programming terms and obvious errors without adding explanations."
- }
- // Project/issue tracking (Jira, Linear, Asana)
- if title.contains("jira") || title.contains("linear") || title.contains("asana") || title.contains("clickup") {
- return "Clean up this transcribed text for project management context in \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Keep the text concise and clear without adding commentary."
- }
- return nil
- }
- */
+ /// Infer web-app specific prompt from a browser window title
+ private func inferWebContext(from windowTitle: String, appName: String) -> String? {
+ let title = windowTitle
+ // Email (Gmail, Outlook Web)
+ if title.contains("gmail") || title.contains("inbox") || title.contains("outlook") {
+ return "Clean up this transcribed text for email app \(appName) (web). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix grammar, punctuation, and capitalization while preserving meaning."
+ }
+ // Messaging (Slack, Discord, Teams, Telegram, WhatsApp)
+ if title.contains("slack") || title.contains("discord") || title.contains("teams") || title.contains("telegram") || title.contains("whatsapp") {
+ return "Clean up this transcribed text for messaging app \(appName) (web). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Fix basic grammar and clarity while keeping the casual tone."
+ }
+ // Documents (Google Docs/Sheets, Notion, Confluence)
+ if title.contains("google docs") || title.contains("docs") || title.contains("notion") || title.contains("confluence") || title.contains("google sheets") || title.contains("sheet") {
+ return "Clean up this transcribed text for a document editor in \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Improve grammar, structure, and readability without adding information."
+ }
+ // Code (GitHub, Stack Overflow, online IDEs)
+ if title.contains("github") || title.contains("stack overflow") || title.contains("stackexchange") || title.contains("replit") || title.contains("codesandbox") {
+ return "Clean up this transcribed text for code-related context in \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Correct programming terms and obvious errors without adding explanations."
+ }
+ // Project/issue tracking (Jira, Linear, Asana)
+ if title.contains("jira") || title.contains("linear") || title.contains("asana") || title.contains("clickup") {
+ return "Clean up this transcribed text for project management context in \(appName). Make minimal edits only; do not add or invent content or answer questions. Remove fillers and false starts. Keep the text concise and clear without adding commentary."
+ }
+ return nil
+ }
+ */
/// Build a general system prompt with voice editing commands support
private func buildSystemPrompt(appInfo: (name: String, bundleId: String, windowTitle: String)) -> String {
@@ -1098,7 +1150,7 @@ struct ContentView: View {
CRITICAL: You are a TEXT CLEANER, NOT an assistant. You ONLY fix typos and grammar. You NEVER answer, respond, or add content.
YOUR ONLY JOB: Clean the transcribed text. Return ONLY the cleaned version.
-
+
RULES:
- Fix grammar, punctuation, capitalization
- Remove filler words (uh, um, like, you know)
@@ -1130,19 +1182,20 @@ struct ContentView: View {
How are you?"
"""
}
-
+
// MARK: - Local Endpoint Detection
+
private func isLocalEndpoint(_ urlString: String) -> Bool {
guard let url = URL(string: urlString),
let host = url.host else { return false }
-
+
let hostLower = host.lowercased()
-
+
// Check for localhost variations
if hostLower == "localhost" || hostLower == "127.0.0.1" {
return true
}
-
+
// Check for private IP ranges
// 127.x.x.x
if hostLower.hasPrefix("127.") {
@@ -1161,15 +1214,17 @@ struct ContentView: View {
let components = hostLower.split(separator: ".")
if components.count >= 2,
let secondOctet = Int(components[1]),
- secondOctet >= 16 && secondOctet <= 31 {
+ secondOctet >= 16 && secondOctet <= 31
+ {
return true
}
}
-
+
return false
}
// MARK: - Modular AI Processing
+
private func processTextWithAI(_ inputText: String) async -> String {
// CRITICAL FIX: Read current settings from SettingsStore, not stale @State copies
// This ensures AI provider/model changes in AISettingsView take effect immediately
@@ -1177,12 +1232,12 @@ struct ContentView: View {
let storedProviderAPIKeys = SettingsStore.shared.providerAPIKeys
let storedSelectedModelByProvider = SettingsStore.shared.selectedModelByProvider
let storedSavedProviders = SettingsStore.shared.savedProviders
-
+
// Derive currentProvider and openAIBaseURL from the current settings
let derivedCurrentProvider: String
let derivedBaseURL: String
let derivedSelectedModel: String
-
+
// Get provider info
if let saved = storedSavedProviders.first(where: { $0.id == currentSelectedProviderID }) {
derivedCurrentProvider = "custom:\(saved.id)"
@@ -1201,9 +1256,13 @@ struct ContentView: View {
derivedBaseURL = "https://api.openai.com/v1"
derivedSelectedModel = storedSelectedModelByProvider[currentSelectedProviderID] ?? ""
}
-
- DebugLogger.shared.debug("processTextWithAI using provider=\(derivedCurrentProvider), model=\(derivedSelectedModel)", source: "ContentView")
-
+
+ DebugLogger.shared
+ .debug(
+ "processTextWithAI using provider=\(derivedCurrentProvider), model=\(derivedSelectedModel)",
+ source: "ContentView"
+ )
+
// Route to Apple Intelligence if selected
if currentSelectedProviderID == "apple-intelligence" {
#if canImport(FoundationModels)
@@ -1217,73 +1276,86 @@ struct ContentView: View {
#endif
return inputText // Fallback if not available
}
-
- let endpoint = derivedBaseURL.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty ? "https://api.openai.com/v1" : derivedBaseURL.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
-
+
+ let endpoint = derivedBaseURL.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
+ .isEmpty ? "https://api.openai.com/v1" : derivedBaseURL
+ .trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
+
// Build the full URL - only append /chat/completions if not already present
let fullEndpoint: String
- if endpoint.contains("/chat/completions") ||
- endpoint.contains("/api/chat") ||
- endpoint.contains("/api/generate") {
+ if endpoint.contains("/chat/completions") ||
+ endpoint.contains("/api/chat") ||
+ endpoint.contains("/api/generate")
+ {
// URL already has a complete path, use as-is
fullEndpoint = endpoint
} else {
// Append /chat/completions for OpenAI-compatible endpoints
fullEndpoint = endpoint + "/chat/completions"
}
-
+
guard let url = URL(string: fullEndpoint) else {
return "Error: Invalid Base URL"
}
-
+
let isLocal = isLocalEndpoint(endpoint)
let apiKey = storedProviderAPIKeys[derivedCurrentProvider] ?? ""
-
+
// Skip API key validation for local endpoints
if !isLocal {
guard !apiKey.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty else {
return "Error: API Key not set for \(derivedCurrentProvider)"
}
}
-
// Get app context captured at start of recording if available
let appInfo = recordingAppInfo ?? getCurrentAppInfo()
let systemPrompt = buildSystemPrompt(appInfo: appInfo)
- DebugLogger.shared.debug("Using app context for AI: app=\(appInfo.name), bundleId=\(appInfo.bundleId), title=\(appInfo.windowTitle)", source: "ContentView")
-
+ DebugLogger.shared
+ .debug(
+ "Using app context for AI: app=\(appInfo.name), bundleId=\(appInfo.bundleId), title=\(appInfo.windowTitle)",
+ source: "ContentView"
+ )
+
// Get reasoning config for this model (uses per-model settings or auto-detection)
let providerKey = self.providerKey(for: currentSelectedProviderID)
- let reasoningConfig = SettingsStore.shared.getReasoningConfig(forModel: derivedSelectedModel, provider: providerKey)
-
+ let reasoningConfig = SettingsStore.shared.getReasoningConfig(
+ forModel: derivedSelectedModel,
+ provider: providerKey
+ )
+
if let config = reasoningConfig {
- DebugLogger.shared.debug("Model '\(derivedSelectedModel)' reasoning config: \(config.parameterName)=\(config.parameterValue), enabled=\(config.isEnabled)", source: "ContentView")
+ DebugLogger.shared
+ .debug(
+ "Model '\(derivedSelectedModel)' reasoning config: \(config.parameterName)=\(config.parameterValue), enabled=\(config.isEnabled)",
+ source: "ContentView"
+ )
} else {
DebugLogger.shared.debug("Model '\(derivedSelectedModel)' has no reasoning config", source: "ContentView")
}
-
+
// Get streaming setting
let enableStreaming = SettingsStore.shared.enableAIStreaming
-
+
// Check if this is a reasoning model that doesn't support temperature parameter
let modelLower = derivedSelectedModel.lowercased()
let isReasoningModel = modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3") || modelLower.hasPrefix("gpt-5")
-
+
// Build request body dynamically to support different reasoning parameters
var requestDict: [String: Any] = [
"model": derivedSelectedModel,
"messages": [
["role": "system", "content": systemPrompt],
- ["role": "user", "content": inputText]
- ]
+ ["role": "user", "content": inputText],
+ ],
]
-
+
// Only add temperature for non-reasoning models
// OpenAI reasoning models (o1, o3, gpt-5) don't support custom temperature
if !isReasoningModel {
requestDict["temperature"] = 0.2
}
-
+
// Add reasoning parameter if configured for this model
if let config = reasoningConfig, config.isEnabled {
if config.parameterName == "enable_thinking" {
@@ -1293,9 +1365,12 @@ struct ContentView: View {
// OpenAI/Groq use string values
requestDict[config.parameterName] = config.parameterValue
}
- DebugLogger.shared.debug("Added reasoning param: \(config.parameterName)=\(config.parameterValue)", source: "ContentView")
+ DebugLogger.shared.debug(
+ "Added reasoning param: \(config.parameterName)=\(config.parameterValue)",
+ source: "ContentView"
+ )
}
-
+
// Add streaming if enabled
if enableStreaming {
requestDict["stream"] = true
@@ -1304,7 +1379,7 @@ struct ContentView: View {
guard let jsonData = try? JSONSerialization.data(withJSONObject: requestDict, options: []) else {
return "Error: Failed to encode request"
}
-
+
// Debug: Log request body
if let bodyStr = String(data: jsonData, encoding: .utf8) {
DebugLogger.shared.debug("AI Request body: \(bodyStr)", source: "ContentView")
@@ -1313,12 +1388,12 @@ struct ContentView: View {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
-
+
// Only add Authorization header for non-local endpoints
if !isLocal {
request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
}
-
+
request.httpBody = jsonData
do {
@@ -1330,7 +1405,7 @@ struct ContentView: View {
// Non-streaming mode - single JSON response
DebugLogger.shared.info("Using NON-STREAMING mode for AI request", source: "ContentView")
let (data, response) = try await URLSession.shared.data(for: request)
-
+
if let http = response as? HTTPURLResponse, http.statusCode >= 400 {
let errText = String(data: data, encoding: .utf8) ?? "Unknown error"
return "Error: HTTP \(http.statusCode): \(errText)"
@@ -1343,13 +1418,17 @@ struct ContentView: View {
return "Error: \(error.localizedDescription)"
}
}
-
+
// MARK: - Streaming Response Handler
+
private func processStreamingResponse(request: URLRequest) async throws -> String {
- DebugLogger.shared.debug("Starting streaming request to: \(request.url?.absoluteString ?? "unknown")", source: "Streaming")
-
+ DebugLogger.shared.debug(
+ "Starting streaming request to: \(request.url?.absoluteString ?? "unknown")",
+ source: "Streaming"
+ )
+
let (bytes, response) = try await URLSession.shared.bytes(for: request)
-
+
if let http = response as? HTTPURLResponse {
DebugLogger.shared.debug("Streaming response status: \(http.statusCode)", source: "Streaming")
if http.statusCode >= 400 {
@@ -1362,34 +1441,35 @@ struct ContentView: View {
return "Error: HTTP \(http.statusCode): \(errText)"
}
}
-
+
var fullContent = ""
-
+
// Use efficient line-based iteration instead of byte-by-byte
for try await rawLine in bytes.lines {
let line = rawLine.trimmingCharacters(in: .whitespaces)
-
+
guard line.hasPrefix("data:") else { continue }
-
+
// Handle both "data: " and "data:" formats
var jsonString = String(line.dropFirst(5))
if jsonString.hasPrefix(" ") {
jsonString = String(jsonString.dropFirst(1))
}
-
+
// Skip [DONE] marker
if jsonString.trimmingCharacters(in: .whitespaces) == "[DONE]" {
DebugLogger.shared.debug("Received [DONE] marker", source: "Streaming")
continue
}
-
+
// Parse the JSON chunk
guard let jsonData = jsonString.data(using: .utf8) else { continue }
-
+
do {
let chunk = try JSONDecoder().decode(StreamingChunk.self, from: jsonData)
if let delta = chunk.choices.first?.delta,
- let content = delta.content {
+ let content = delta.content
+ {
fullContent += content
}
} catch {
@@ -1398,17 +1478,19 @@ struct ContentView: View {
let choices = json["choices"] as? [[String: Any]],
let firstChoice = choices.first,
let delta = firstChoice["delta"] as? [String: Any],
- let content = delta["content"] as? String {
+ let content = delta["content"] as? String
+ {
fullContent += content
}
}
}
-
+
DebugLogger.shared.debug("Streaming complete. Content length: \(fullContent.count)", source: "Streaming")
return fullContent.isEmpty ? "<no content>" : fullContent
}
-
+
// MARK: - Stop and Process Transcription
+
private func stopAndProcessTranscription() async {
DebugLogger.shared.debug("stopAndProcessTranscription called", source: "ContentView")
@@ -1440,7 +1522,7 @@ struct ContentView: View {
await processRewriteWithVoiceInstruction(transcribedText)
return
}
-
+
// If this was a command recording, process the command
if wasCommandMode {
DebugLogger.shared.info("Processing command: \(transcribedText)", source: "ContentView")
@@ -1463,17 +1545,18 @@ struct ContentView: View {
}
let trimmedBaseURL = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
let isLocal = isLocalEndpoint(trimmedBaseURL)
- let apiKey = (SettingsStore.shared.getAPIKey(for: currentProviderID) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ let apiKey = (SettingsStore.shared.getAPIKey(for: currentProviderID) ?? "")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
let shouldUseAI = SettingsStore.shared.enableAIProcessing && (isLocal || !apiKey.isEmpty)
-
+
if shouldUseAI {
DebugLogger.shared.debug("Routing transcription through AI post-processing", source: "ContentView")
-
+
// Show processing animation in notch
menuBarManager.setProcessing(true)
-
+
finalText = await processTextWithAI(transcribedText)
-
+
// Hide processing animation
menuBarManager.setProcessing(false)
} else {
@@ -1481,7 +1564,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()
TranscriptionHistoryStore.shared.addEntry(
@@ -1500,100 +1583,115 @@ struct ContentView: View {
let frontmostApp = NSWorkspace.shared.frontmostApplication
let frontmostName = frontmostApp?.localizedName ?? "Unknown"
let isFluidFrontmost = frontmostApp?.bundleIdentifier?.contains("fluid") == true
- let shouldTypeExternally = !isFluidFrontmost || isTranscriptionFocused == false
+ let shouldTypeExternally = !isFluidFrontmost || self.isTranscriptionFocused == false
- DebugLogger.shared.debug(
- "Typing decision → frontmost: \(frontmostName), fluidFrontmost: \(isFluidFrontmost), editorFocused: \(isTranscriptionFocused), willTypeExternally: \(shouldTypeExternally)",
- source: "ContentView"
- )
+ DebugLogger.shared
+ .debug(
+ "Typing decision → frontmost: \(frontmostName), fluidFrontmost: \(isFluidFrontmost), editorFocused: \(self.isTranscriptionFocused), willTypeExternally: \(shouldTypeExternally)",
+ source: "ContentView"
+ )
if shouldTypeExternally {
- asr.typeTextToActiveField(finalText)
+ self.asr.typeTextToActiveField(finalText)
}
}
}
-
+
// MARK: - Rewrite Mode Voice Processing
+
private func processRewriteWithVoiceInstruction(_ instruction: String) async {
let hasOriginalText = !rewriteModeService.originalText.isEmpty
- DebugLogger.shared.info("Processing \(hasOriginalText ? "rewrite" : "write/improve") - instruction: '\(instruction)', originalText length: \(rewriteModeService.originalText.count)", source: "ContentView")
-
+ DebugLogger.shared
+ .info(
+ "Processing \(hasOriginalText ? "rewrite" : "write/improve") - instruction: '\(instruction)', originalText length: \(rewriteModeService.originalText.count)",
+ source: "ContentView"
+ )
+
// Show processing animation
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)
-
+
// Hide processing animation
menuBarManager.setProcessing(false)
-
+
// If rewrite was successful, type the result
if !rewriteModeService.rewrittenText.isEmpty {
- DebugLogger.shared.info("Rewrite successful, typing result (chars: \(rewriteModeService.rewrittenText.count))", source: "ContentView")
-
+ DebugLogger.shared
+ .info(
+ "Rewrite successful, typing result (chars: \(rewriteModeService.rewrittenText.count))",
+ source: "ContentView"
+ )
+
// Copy to clipboard as backup
if SettingsStore.shared.copyTranscriptionToClipboard {
ClipboardService.copyToClipboard(rewriteModeService.rewrittenText)
}
-
+
// Type the rewritten text
asr.typeTextToActiveField(rewriteModeService.rewrittenText)
-
+
// Clear the rewrite service state for next use
rewriteModeService.clearState()
} else {
DebugLogger.shared.error("Rewrite failed - no result", source: "ContentView")
}
}
-
+
// MARK: - Command Mode Voice Processing
+
private func processCommandWithVoice(_ command: String) async {
DebugLogger.shared.info("Processing voice command: '\(command)'", source: "ContentView")
-
+
// Show processing animation
menuBarManager.setProcessing(true)
-
+
// Process the command through CommandModeService
// This stores the conversation history and executes any terminal commands
await commandModeService.processUserCommand(command)
-
+
// Hide processing animation
menuBarManager.setProcessing(false)
-
+
DebugLogger.shared.info("Command processed, conversation stored in Command Mode", source: "ContentView")
}
// Capture app context at start to avoid mismatches if the user switches apps mid-session
private func startRecording() {
// Ensure normal dictation mode is set (command/rewrite modes set their own)
- if !isRecordingForCommand && !isRecordingForRewrite {
+ if !isRecordingForCommand, !isRecordingForRewrite {
menuBarManager.setOverlayMode(.dictation)
}
-
+
let info = getCurrentAppInfo()
recordingAppInfo = info
- DebugLogger.shared.debug("Captured recording app context: app=\(info.name), bundleId=\(info.bundleId), title=\(info.windowTitle)", source: "ContentView")
+ DebugLogger.shared
+ .debug(
+ "Captured recording app context: app=\(info.name), bundleId=\(info.bundleId), title=\(info.windowTitle)",
+ source: "ContentView"
+ )
asr.start()
-
+
// Pre-load model in background while recording (avoids 10s freeze on stop)
Task {
do {
- try await asr.ensureAsrReady()
+ try await self.asr.ensureAsrReady()
DebugLogger.shared.debug("Model pre-loaded during recording", source: "ContentView")
} catch {
DebugLogger.shared.error("Failed to pre-load model: \(error)", source: "ContentView")
}
}
}
-
+
// MARK: - ASR Model Management
-
+
/// Manual download trigger - downloads models when user clicks button
private func downloadModels() async {
DebugLogger.shared.debug("User initiated model download", source: "ContentView")
-
+
do {
try await asr.ensureAsrReady()
DebugLogger.shared.info("Model download completed successfully", source: "ContentView")
@@ -1601,11 +1699,11 @@ struct ContentView: View {
DebugLogger.shared.error("Failed to download models: \(error)", source: "ContentView")
}
}
-
+
/// Delete models from disk
private func deleteModels() async {
DebugLogger.shared.debug("User initiated model deletion", source: "ContentView")
-
+
do {
try await asr.clearModelCache()
DebugLogger.shared.info("Models deleted successfully", source: "ContentView")
@@ -1613,35 +1711,37 @@ struct ContentView: View {
DebugLogger.shared.error("Failed to delete models: \(error)", source: "ContentView")
}
}
-
+
// MARK: - ASR Model Preloading
+
private func preloadASRModel() async {
// DEPRECATED: No longer auto-loads on startup - models downloaded manually
DebugLogger.shared.debug("Skipping auto-preload - models downloaded manually via UI", source: "ContentView")
}
-
+
// MARK: - Model Management
+
private func addNewModel() {
guard !newModelName.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty else { return }
-
+
let modelName = newModelName.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let key = providerKey(for: selectedProviderID)
-
+
// Get current list or start fresh if empty
var list = availableModelsByProvider[key] ?? availableModels
if list.isEmpty {
list = []
}
-
+
// Add the new model if not already in list
if !list.contains(modelName) {
list.append(modelName)
}
-
+
// Update state
availableModelsByProvider[key] = list
SettingsStore.shared.availableModelsByProvider = availableModelsByProvider
-
+
// Update saved provider if exists
if let providerIndex = savedProviders.firstIndex(where: { $0.id == selectedProviderID }) {
let updatedProvider = SettingsStore.SavedProvider(
@@ -1653,27 +1753,27 @@ struct ContentView: View {
savedProviders[providerIndex] = updatedProvider
saveSavedProviders()
}
-
+
// Update UI state
availableModels = list
selectedModel = modelName
selectedModelByProvider[key] = modelName
SettingsStore.shared.selectedModelByProvider = selectedModelByProvider
-
+
// Close the add model UI
showingAddModel = false
newModelName = ""
}
-
// MARK: - OpenAI-compatible call for playground
+
private func callOpenAIChat() async {
guard !isCallingAI else { return }
- await MainActor.run { isCallingAI = true }
+ await MainActor.run { self.isCallingAI = true }
defer { Task { await MainActor.run { isCallingAI = false } } }
-
+
let result = await processTextWithAI(aiInputText)
- await MainActor.run { aiOutputText = result }
+ await MainActor.run { self.aiOutputText = result }
}
private func getModelStatusText() -> String {
@@ -1689,7 +1789,7 @@ struct ContentView: View {
return "Model will download when needed."
}
}
-
+
private func labelFor(status: AVAuthorizationStatus) -> String {
switch status {
case .authorized: return "Microphone: Authorized"
@@ -1699,16 +1799,16 @@ struct ContentView: View {
@unknown default: return "Microphone: Unknown"
}
}
-
+
private func checkAccessibilityPermissions() -> Bool {
return AXIsProcessTrusted()
}
-
+
private func openAccessibilitySettings() {
let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
- AXIsProcessTrustedWithOptions(options)
- didOpenAccessibilityPane = true
- UserDefaults.standard.set(true, forKey: accessibilityRestartFlagKey)
+ AXIsProcessTrustedWithOptions(options)
+ didOpenAccessibilityPane = true
+ UserDefaults.standard.set(true, forKey: accessibilityRestartFlagKey)
}
private func restartApp() {
@@ -1724,29 +1824,32 @@ struct ContentView: View {
NSApp.terminate(nil)
}
}
-
+
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 }
-
+
// Cancel any existing polling task
accessibilityPollingTask?.cancel()
-
+
// Start background polling
accessibilityPollingTask = Task {
while !Task.isCancelled {
try? await Task.sleep(nanoseconds: 2_000_000_000) // Poll every 2 seconds
-
+
// Check if permission was granted
let nowTrusted = AXIsProcessTrusted()
- if nowTrusted && !accessibilityEnabled {
+ if nowTrusted && !self.accessibilityEnabled {
await MainActor.run {
- DebugLogger.shared.info("Accessibility permission granted! Auto-restarting app...", source: "ContentView")
-
+ DebugLogger.shared.info(
+ "Accessibility permission granted! Auto-restarting app...",
+ source: "ContentView"
+ )
+
// Mark that we've auto-restarted to prevent loops
- UserDefaults.standard.set(true, forKey: hasAutoRestartedForAccessibilityKey)
-
+ UserDefaults.standard.set(true, forKey: self.hasAutoRestartedForAccessibilityKey)
+
// Give user brief moment to see any UI feedback
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.restartApp()
@@ -1766,11 +1869,10 @@ struct ContentView: View {
private func openApplicationsFolder() {
NSWorkspace.shared.open(URL(fileURLWithPath: "/Applications"))
}
-
private func initializeHotkeyManagerIfNeeded() {
guard hotkeyManager == nil else { return }
-
+
hotkeyManager = GlobalHotkeyManager(
asrService: asr,
shortcut: hotkeyShortcut,
@@ -1782,29 +1884,45 @@ struct ContentView: View {
self.startRecording()
},
stopAndProcessCallback: {
- await stopAndProcessTranscription()
+ await self.stopAndProcessTranscription()
},
commandModeCallback: {
- DebugLogger.shared.info("Command mode triggered", source: "ContentView")
-
- // Set flag so stopAndProcessTranscription knows to process as command
+ DebugLogger.shared.info(
+ "Command mode triggered",
+ source: "ContentView"
+ )
+
+ // Set flag so stopAndProcessTranscription knows to process as
+ // command
self.isRecordingForCommand = true
-
+
// Set overlay mode to command
self.menuBarManager.setOverlayMode(.command)
-
+
// Start recording immediately for the command
- DebugLogger.shared.info("Starting voice recording for command", source: "ContentView")
+ DebugLogger.shared.info(
+ "Starting voice recording for command",
+ source: "ContentView"
+ )
self.asr.start()
},
rewriteModeCallback: {
// Try to capture text first while still in the other app
let captured = self.rewriteModeService.captureSelectedText()
- DebugLogger.shared.info("Rewrite mode triggered, text captured: \(captured)", source: "ContentView")
-
+ DebugLogger.shared
+ .info(
+ "Rewrite mode triggered, text captured: \(captured)",
+ source: "ContentView"
+ )
+
if !captured {
- // No text selected - start in "write mode" where user speaks what to write
- DebugLogger.shared.info("No text selected - starting in write/improve mode", source: "ContentView")
+ // No text selected - start in "write mode" where user speaks
+ // what to write
+ DebugLogger.shared
+ .info(
+ "No text selected - starting in write/improve mode",
+ source: "ContentView"
+ )
self.rewriteModeService.startWithoutSelection()
// Set overlay mode to write (different visual)
self.menuBarManager.setOverlayMode(.write)
@@ -1812,32 +1930,38 @@ struct ContentView: View {
// Text was selected - rewrite mode
self.menuBarManager.setOverlayMode(.rewrite)
}
-
- // Set flag so stopAndProcessTranscription knows to process as rewrite
+
+ // Set flag so stopAndProcessTranscription knows to process as
+ // rewrite
self.isRecordingForRewrite = true
-
- // Start recording immediately for the rewrite instruction (or text to improve)
- DebugLogger.shared.info("Starting voice recording for rewrite/write mode", source: "ContentView")
+
+ // Start recording immediately for the rewrite instruction (or text
+ // to improve)
+ DebugLogger.shared
+ .info(
+ "Starting voice recording for rewrite/write mode",
+ source: "ContentView"
+ )
self.asr.start()
}
)
-
+
hotkeyManagerInitialized = hotkeyManager?.validateEventTapHealth() ?? false
-
+
hotkeyManager?.enablePressAndHoldMode(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 {
var handled = false
-
+
// Close expanded command notch if visible (highest priority)
if NotchOverlayManager.shared.isCommandOutputExpanded {
DebugLogger.shared.debug("Cancel callback: closing expanded command notch", source: "ContentView")
NotchOverlayManager.shared.hideExpandedCommandOutput()
handled = true
}
-
+
// Reset recording mode flags
if self.isRecordingForCommand {
self.isRecordingForCommand = false
@@ -1849,7 +1973,7 @@ struct ContentView: View {
self.menuBarManager.setOverlayMode(.dictation)
handled = true
}
-
+
// Close mode views if open
if self.selectedSidebarItem == .commandMode || self.selectedSidebarItem == .rewriteMode {
DebugLogger.shared.debug("Cancel callback: closing mode view", source: "ContentView")
@@ -1858,28 +1982,28 @@ struct ContentView: View {
}
handled = true
}
-
+
return handled
}
-
+
// Monitor initialization status
Task {
// Give some time for initialization
try? await Task.sleep(nanoseconds: 3_000_000_000) // 3 seconds
-
+
await MainActor.run {
self.hotkeyManagerInitialized = self.hotkeyManager?.validateEventTapHealth() ?? false
if UserDefaults.standard.bool(forKey: "enableDebugLogs") {
print("[ContentView] Initial hotkey manager health check: \(self.hotkeyManagerInitialized)")
}
-
+
// If still not initialized and accessibility is enabled, try reinitializing
if !self.hotkeyManagerInitialized && self.accessibilityEnabled {
self.hotkeyManagerInitialized = self.hotkeyManager?.validateEventTapHealth() ?? false
if UserDefaults.standard.bool(forKey: "enableDebugLogs") {
print("[ContentView] Initial hotkey manager health check: \(self.hotkeyManagerInitialized)")
}
-
+
// If still not initialized and accessibility is enabled, try reinitializing
if !self.hotkeyManagerInitialized && self.accessibilityEnabled {
if UserDefaults.standard.bool(forKey: "enableDebugLogs") {
@@ -1891,33 +2015,33 @@ struct ContentView: View {
}
}
}
-
+
// MARK: - Model Management Helpers
-
+
private func isCustomModel(_ model: String) -> Bool {
// Non-removable defaults are the provider's default models
return !defaultModels(for: 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)
-
+
// Check for custom config first
if SettingsStore.shared.hasCustomReasoningConfig(forModel: 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()
return modelLower.hasPrefix("gpt-5") || modelLower.contains("gpt-5.") ||
- modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3") ||
- modelLower.contains("gpt-oss") || modelLower.hasPrefix("openai/") ||
- (modelLower.contains("deepseek") && modelLower.contains("reasoner"))
+ modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3") ||
+ modelLower.contains("gpt-oss") || modelLower.hasPrefix("openai/") ||
+ (modelLower.contains("deepseek") && modelLower.contains("reasoner"))
}
-
+
private func removeModel(_ model: String) {
// Don't remove if it's currently selected
if selectedModel == model {
@@ -1926,15 +2050,15 @@ struct ContentView: View {
selectedModel = firstOther
}
}
-
+
// Remove from current provider's model list
availableModels.removeAll { $0 == model }
-
+
// Update the stored models for this provider
let key = providerKey(for: selectedProviderID)
availableModelsByProvider[key] = availableModels
SettingsStore.shared.availableModelsByProvider = 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(
@@ -1946,12 +2070,12 @@ struct ContentView: View {
savedProviders[providerIndex] = updatedProvider
saveSavedProviders()
}
-
+
// Update selected model mapping for this provider
selectedModelByProvider[key] = selectedModel
SettingsStore.shared.selectedModelByProvider = selectedModelByProvider
}
-
+
// Deprecated: hotkey persistence is handled via SettingsStore
}
@@ -1960,6 +2084,7 @@ struct ContentView: View {
// AudioDevice and AudioHardwareObserver moved to Services/AudioDeviceService.swift
// MARK: - Card Animation Modifier
+
struct CardAppearAnimation: ViewModifier {
let delay: Double
@Binding var appear: Bool
@@ -1968,7 +2093,9 @@ struct CardAppearAnimation: ViewModifier {
content
.scaleEffect(appear ? 1.0 : 0.96)
.opacity(appear ? 1.0 : 0)
- .animation(.spring(response: 0.8, dampingFraction: 0.75, blendDuration: 0.2).delay(delay), value: appear)
+ .animation(
+ .spring(response: 0.8, dampingFraction: 0.75, blendDuration: 0.2).delay(delay),
+ value: appear
+ )
}
}
-
diff --git a/Sources/Fluid/CustomAnimations.swift b/Sources/Fluid/CustomAnimations.swift
index 15eaf431..161ac28c 100644
--- a/Sources/Fluid/CustomAnimations.swift
+++ b/Sources/Fluid/CustomAnimations.swift
@@ -1,5 +1,5 @@
-import SwiftUI
import Combine
+import SwiftUI
// MARK: - Custom Animation Configurations
@@ -12,7 +12,11 @@ struct PulseAnimationConfig: AudioVisualizationConfig {
struct WaveAnimationConfig: AudioVisualizationConfig {
let noiseThreshold: CGFloat = 0.2
let maxAnimationScale: CGFloat = 4.0
- let animationSpring: Animation = .spring(response: 0.3, dampingFraction: 0.6, blendDuration: 0) // Optimized for 60 FPS
+ let animationSpring: Animation = .spring(
+ response: 0.3,
+ dampingFraction: 0.6,
+ blendDuration: 0
+ ) // Optimized for 60 FPS
}
// MARK: - Custom Animation Views
@@ -21,12 +25,12 @@ struct PulseAudioVisualizationView: View {
@StateObject private var data: AudioVisualizationData
let config: AudioVisualizationConfig
@State private var animationId = UUID()
-
+
init(audioLevelPublisher: AnyPublisher<CGFloat, Never>, config: AudioVisualizationConfig = PulseAnimationConfig()) {
- self._data = StateObject(wrappedValue: AudioVisualizationData(audioLevelPublisher: audioLevelPublisher))
+ _data = StateObject(wrappedValue: AudioVisualizationData(audioLevelPublisher: audioLevelPublisher))
self.config = config
}
-
+
var body: some View {
ZStack {
// Multiple pulsing rings
@@ -35,17 +39,16 @@ struct PulseAudioVisualizationView: View {
.stroke(Color.green.opacity(0.6 - Double(index) * 0.2), lineWidth: 2)
.frame(width: 40 + CGFloat(index) * 20, height: 40 + CGFloat(index) * 20)
.scaleEffect(
- data.audioLevel > config.noiseThreshold ?
- 1.0 + (data.audioLevel - config.noiseThreshold) * config.maxAnimationScale : 1.0,
+ self.data.audioLevel > self.config.noiseThreshold ?
+ 1.0 + (self.data.audioLevel - self.config.noiseThreshold) * self.config
+ .maxAnimationScale : 1.0,
anchor: .center
)
- .opacity(
- data.audioLevel > config.noiseThreshold ?
- 1.0 - (data.audioLevel - config.noiseThreshold) : 0.3
- )
- .animation(config.animationSpring.delay(Double(index) * 0.1), value: animationId)
+ .opacity(self.data.audioLevel > self.config.noiseThreshold ?
+ 1.0 - (self.data.audioLevel - self.config.noiseThreshold) : 0.3)
+ .animation(self.config.animationSpring.delay(Double(index) * 0.1), value: self.animationId)
}
-
+
// Center dot
Circle()
.fill(Color.green)
@@ -54,8 +57,8 @@ struct PulseAudioVisualizationView: View {
.frame(width: 100, height: 100)
.onChange(of: data.audioLevel) { _, newLevel in
// Only trigger animation update for significant changes to prevent cycles
- if abs(newLevel - (data.audioLevel)) > 0.1 {
- animationId = UUID()
+ if abs(newLevel - (self.data.audioLevel)) > 0.1 {
+ self.animationId = UUID()
}
}
}
@@ -65,12 +68,12 @@ struct WaveAudioVisualizationView: View {
@StateObject private var data: AudioVisualizationData
let config: AudioVisualizationConfig
@State private var animationId = UUID()
-
+
init(audioLevelPublisher: AnyPublisher<CGFloat, Never>, config: AudioVisualizationConfig = WaveAnimationConfig()) {
- self._data = StateObject(wrappedValue: AudioVisualizationData(audioLevelPublisher: audioLevelPublisher))
+ _data = StateObject(wrappedValue: AudioVisualizationData(audioLevelPublisher: audioLevelPublisher))
self.config = config
}
-
+
var body: some View {
HStack(spacing: 4) {
ForEach(0..<8, id: \.self) { index in
@@ -78,64 +81,66 @@ struct WaveAudioVisualizationView: View {
.fill(Color.purple)
.frame(width: 4, height: 20)
.scaleEffect(
- y: data.audioLevel > config.noiseThreshold ?
- 1.0 + (data.audioLevel - config.noiseThreshold) * config.maxAnimationScale * (1.0 - Double(index) * 0.1) : 0.2,
+ y: self.data.audioLevel > self.config.noiseThreshold ?
+ 1.0 + (self.data.audioLevel - self.config.noiseThreshold) * self.config
+ .maxAnimationScale * (1.0 - Double(index) * 0.1) : 0.2,
anchor: .bottom
)
- .animation(config.animationSpring.delay(Double(index) * 0.05), value: animationId)
+ .animation(self.config.animationSpring.delay(Double(index) * 0.05), value: self.animationId)
}
}
.frame(width: 60, height: 40)
.onChange(of: data.audioLevel) { _, newLevel in
// Only trigger animation update for significant changes to prevent cycles
- if abs(newLevel - (data.audioLevel)) > 0.1 {
- animationId = UUID()
+ if abs(newLevel - (self.data.audioLevel)) > 0.1 {
+ self.animationId = UUID()
}
}
}
}
// MARK: - Usage Examples
+
/*
-// Example 1: Using Pulse Animation
-struct PulseListeningOverlayView: View {
- let audioLevelPublisher: AnyPublisher<CGFloat, Never>
-
- var body: some View {
- PulseAudioVisualizationView(
- audioLevelPublisher: audioLevelPublisher,
- config: PulseAnimationConfig()
- )
- }
-}
+ // Example 1: Using Pulse Animation
+ struct PulseListeningOverlayView: View {
+ let audioLevelPublisher: AnyPublisher<CGFloat, Never>
-// Example 2: Using Wave Animation
-struct WaveListeningOverlayView: View {
- let audioLevelPublisher: AnyPublisher<CGFloat, Never>
-
- var body: some View {
- WaveAudioVisualizationView(
- audioLevelPublisher: audioLevelPublisher,
- config: WaveAnimationConfig()
- )
- }
-}
+ var body: some View {
+ PulseAudioVisualizationView(
+ audioLevelPublisher: audioLevelPublisher,
+ config: PulseAnimationConfig()
+ )
+ }
+ }
-// Example 3: Custom Configuration
-struct CustomConfigAnimationConfig: AudioVisualizationConfig {
- let noiseThreshold: CGFloat = 0.1 // Very sensitive
- let maxAnimationScale: CGFloat = 5.0 // Very dramatic
- let animationSpring: Animation = .interpolatingSpring(stiffness: 300, damping: 30)
-}
+ // Example 2: Using Wave Animation
+ struct WaveListeningOverlayView: View {
+ let audioLevelPublisher: AnyPublisher<CGFloat, Never>
-struct CustomListeningOverlayView: View {
- let audioLevelPublisher: AnyPublisher<CGFloat, Never>
-
- var body: some View {
- DefaultAudioVisualizationView(
- audioLevelPublisher: audioLevelPublisher,
- config: CustomConfigAnimationConfig()
- )
- }
-}
-*/
\ No newline at end of file
+ var body: some View {
+ WaveAudioVisualizationView(
+ audioLevelPublisher: audioLevelPublisher,
+ config: WaveAnimationConfig()
+ )
+ }
+ }
+
+ // Example 3: Custom Configuration
+ struct CustomConfigAnimationConfig: AudioVisualizationConfig {
+ let noiseThreshold: CGFloat = 0.1 // Very sensitive
+ let maxAnimationScale: CGFloat = 5.0 // Very dramatic
+ let animationSpring: Animation = .interpolatingSpring(stiffness: 300, damping: 30)
+ }
+
+ struct CustomListeningOverlayView: View {
+ let audioLevelPublisher: AnyPublisher<CGFloat, Never>
+
+ var body: some View {
+ DefaultAudioVisualizationView(
+ audioLevelPublisher: audioLevelPublisher,
+ config: CustomConfigAnimationConfig()
+ )
+ }
+ }
+ */
diff --git a/Sources/Fluid/Models/HotkeyShortcut.swift b/Sources/Fluid/Models/HotkeyShortcut.swift
index d6018346..77c73c5f 100644
--- a/Sources/Fluid/Models/HotkeyShortcut.swift
+++ b/Sources/Fluid/Models/HotkeyShortcut.swift
@@ -1,41 +1,33 @@
-import Foundation
import AppKit
+import Foundation
-struct HotkeyShortcut: Codable, Equatable
-{
+struct HotkeyShortcut: Codable, Equatable {
var keyCode: UInt16
var modifierFlags: NSEvent.ModifierFlags
enum CodingKeys: String, CodingKey { case keyCode, modifierFlagsRawValue }
- var displayString: String
- {
+ 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 let key = Self.keyCodeToString(keyCode)
- {
+ if let key = Self.keyCodeToString(keyCode) {
parts.append(key)
- }
- else
- {
+ } else {
parts.append(String(Character(UnicodeScalar(keyCode) ?? "?")))
}
- if modifierFlags.isEmpty
- {
+ if modifierFlags.isEmpty {
return parts.last ?? "Unknown"
}
return parts.joined(separator: " + ")
}
- static func keyCodeToString(_ keyCode: UInt16) -> String?
- {
- switch keyCode
- {
+ static func keyCodeToString(_ keyCode: UInt16) -> String? {
+ switch keyCode {
case 36: return "Return"
case 48: return "Tab"
case 49: return "Space"
@@ -106,22 +98,17 @@ struct HotkeyShortcut: Codable, Equatable
}
}
-extension HotkeyShortcut
-{
- init(from decoder: Decoder) throws
- {
+extension HotkeyShortcut {
+ init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
- self.keyCode = try c.decode(UInt16.self, forKey: .keyCode)
+ keyCode = try c.decode(UInt16.self, forKey: .keyCode)
let raw = try c.decode(UInt.self, forKey: .modifierFlagsRawValue)
- self.modifierFlags = NSEvent.ModifierFlags(rawValue: raw)
+ modifierFlags = NSEvent.ModifierFlags(rawValue: raw)
}
- func encode(to encoder: Encoder) throws
- {
+ 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)
}
}
-
-
diff --git a/Sources/Fluid/Networking/AIProvider.swift b/Sources/Fluid/Networking/AIProvider.swift
index eea97471..fa7804fe 100644
--- a/Sources/Fluid/Networking/AIProvider.swift
+++ b/Sources/Fluid/Networking/AIProvider.swift
@@ -1,40 +1,46 @@
import Foundation
-protocol AIProvider
-{
- func process(systemPrompt: String, userText: String, model: String, apiKey: String, baseURL: String, stream: Bool) async -> String
+protocol AIProvider {
+ func process(
+ systemPrompt: String,
+ userText: String,
+ model: String,
+ apiKey: String,
+ baseURL: String,
+ stream: Bool
+ ) async -> String
}
-final class OpenAICompatibleProvider: AIProvider
-{
+final class OpenAICompatibleProvider: AIProvider {
struct ChatMessage: Codable { let role: String; let content: String }
- struct ChatRequest: Codable {
+ struct ChatRequest: Codable {
let model: String
let messages: [ChatMessage]
let temperature: Double?
let reasoning_effort: String?
let stream: Bool?
-
+
enum CodingKeys: String, CodingKey {
case model, messages, temperature, reasoning_effort, stream
}
}
+
struct ChatChoiceMessage: Codable { let role: String; let content: String }
struct ChatChoice: Codable { let index: Int?; let message: ChatChoiceMessage }
struct ChatResponse: Codable { let choices: [ChatChoice] }
-
+
// Helper function to detect if the endpoint is local
private func isLocalEndpoint(_ urlString: String) -> Bool {
guard let url = URL(string: urlString),
let host = url.host else { return false }
-
+
let hostLower = host.lowercased()
-
+
// Check for localhost variations
if hostLower == "localhost" || hostLower == "127.0.0.1" {
return true
}
-
+
// Check for private IP ranges
// 127.x.x.x
if hostLower.hasPrefix("127.") {
@@ -53,14 +59,15 @@ final class OpenAICompatibleProvider: AIProvider
let components = hostLower.split(separator: ".")
if components.count >= 2,
let secondOctet = Int(components[1]),
- secondOctet >= 16 && secondOctet <= 31 {
+ secondOctet >= 16 && secondOctet <= 31
+ {
return true
}
}
-
+
return false
}
-
+
// Helper function to detect if model is a gpt-oss model (Groq reasoning models)
private func isGptOssModel(_ modelName: String) -> Bool {
let modelLower = modelName.lowercased()
@@ -68,29 +75,37 @@ final class OpenAICompatibleProvider: AIProvider
return modelLower.contains("gpt-oss") || modelLower.hasPrefix("openai/")
}
- func process(systemPrompt: String, userText: String, model: String, apiKey: String, baseURL: String, stream: Bool = false) async -> String
- {
- let endpoint = baseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? "https://api.openai.com/v1" : baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
-
+ func process(
+ systemPrompt: String,
+ userText: String,
+ model: String,
+ apiKey: String,
+ baseURL: String,
+ stream: Bool = false
+ ) async -> String {
+ let endpoint = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
+ .isEmpty ? "https://api.openai.com/v1" : baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
+
// Build the full URL - only append /chat/completions if not already present
let fullEndpoint: String
- if endpoint.contains("/chat/completions") ||
- endpoint.contains("/api/chat") ||
- endpoint.contains("/api/generate") {
+ if endpoint.contains("/chat/completions") ||
+ endpoint.contains("/api/chat") ||
+ endpoint.contains("/api/generate")
+ {
// URL already has a complete path, use as-is
fullEndpoint = endpoint
} else {
// Append /chat/completions for OpenAI-compatible endpoints
fullEndpoint = endpoint + "/chat/completions"
}
-
+
guard let url = URL(string: fullEndpoint) else { return "Error: Invalid Base URL" }
-
+
let isLocal = isLocalEndpoint(endpoint)
-
+
// Check if model is gpt-oss and add reasoning_effort parameter
let shouldAddReasoningEffort = isGptOssModel(model)
-
+
// Check if this is a reasoning model that doesn't support temperature parameter
let modelLower = model.lowercased()
let isReasoningModel = modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3") || modelLower.hasPrefix("gpt-5")
@@ -99,9 +114,9 @@ final class OpenAICompatibleProvider: AIProvider
model: model,
messages: [
ChatMessage(role: "system", content: systemPrompt),
- ChatMessage(role: "user", content: userText)
+ ChatMessage(role: "user", content: userText),
],
- temperature: isReasoningModel ? nil : 0.2, // Don't send temperature for reasoning models
+ temperature: isReasoningModel ? nil : 0.2, // Don't send temperature for reasoning models
reasoning_effort: shouldAddReasoningEffort ? "low" : nil,
stream: stream ? true : nil
)
@@ -111,36 +126,32 @@ final class OpenAICompatibleProvider: AIProvider
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
-
+
// Only add Authorization header for non-local endpoints
if !isLocal {
request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
}
-
+
request.httpBody = jsonData
- do
- {
+ do {
let (data, response) = try await URLSession.shared.data(for: request)
-
+
#if DEBUG
DebugLogger.shared.debug("AI Request to: \(request.url?.absoluteString ?? "unknown")", source: "AIProvider")
if let http = response as? HTTPURLResponse {
DebugLogger.shared.debug("HTTP Status: \(http.statusCode)", source: "AIProvider")
}
#endif
-
- if let http = response as? HTTPURLResponse, http.statusCode >= 400
- {
+
+ if let http = response as? HTTPURLResponse, http.statusCode >= 400 {
let errText = String(data: data, encoding: .utf8) ?? "Unknown error"
DebugLogger.shared.error("AI API error HTTP \(http.statusCode): \(errText)", source: "AIProvider")
return "Error: HTTP \(http.statusCode): \(errText)"
}
let decoded = try JSONDecoder().decode(ChatResponse.self, from: data)
return decoded.choices.first?.message.content ?? "<no content>"
- }
- catch
- {
+ } catch {
DebugLogger.shared.error("AI API request failed: \(error.localizedDescription)", source: "AIProvider")
#if DEBUG
if let decodingError = error as? DecodingError {
@@ -151,4 +162,3 @@ final class OpenAICompatibleProvider: AIProvider
}
}
}
-
diff --git a/Sources/Fluid/Networking/AppleIntelligenceProvider.swift b/Sources/Fluid/Networking/AppleIntelligenceProvider.swift
index 0bf2190c..c748dcec 100644
--- a/Sources/Fluid/Networking/AppleIntelligenceProvider.swift
+++ b/Sources/Fluid/Networking/AppleIntelligenceProvider.swift
@@ -1,10 +1,3 @@
-//
-// AppleIntelligenceProvider.swift
-// FluidVoice
-//
-// On-device AI processing using Apple's FoundationModels framework (macOS 26+)
-//
-
import Foundation
#if canImport(FoundationModels)
@@ -13,7 +6,7 @@ import FoundationModels
// MARK: - Apple Intelligence Availability Service
-struct AppleIntelligenceService {
+enum AppleIntelligenceService {
/// Whether the current OS supports FoundationModels (compile-time + runtime check)
static var isSupported: Bool {
if #available(macOS 26.0, *) {
@@ -21,7 +14,7 @@ struct AppleIntelligenceService {
}
return false
}
-
+
/// Whether Apple Intelligence is available and enabled on this device
static var isAvailable: Bool {
guard isSupported else { return false }
@@ -32,7 +25,7 @@ struct AppleIntelligenceService {
#endif
return false
}
-
+
/// Human-readable reason why Apple Intelligence is unavailable
static var unavailabilityReason: String? {
if !isSupported {
@@ -50,51 +43,53 @@ struct AppleIntelligenceService {
#if canImport(FoundationModels)
@available(macOS 26.0, *)
final class AppleIntelligenceProvider {
-
/// Process text with a system prompt (for transcription cleanup)
func process(systemPrompt: String, userText: String) async -> String {
do {
let session = LanguageModelSession()
-
+
let fullPrompt = """
\(systemPrompt)
-
+
\(userText)
"""
-
+
let response = try await session.respond(to: fullPrompt)
return response.content
} catch {
- DebugLogger.shared.error("Apple Intelligence error: \(error.localizedDescription)", source: "AppleIntelligenceProvider")
+ DebugLogger.shared.error(
+ "Apple Intelligence error: \(error.localizedDescription)",
+ source: "AppleIntelligenceProvider"
+ )
return "Error: \(error.localizedDescription)"
}
}
-
+
/// Process rewrite/write requests with conversation history
func processRewrite(messages: [(role: String, content: String)], isWriteMode: Bool) async throws -> String {
let session = LanguageModelSession()
-
+
// Build the conversation as a single prompt since FoundationModels
// doesn't have the same multi-turn API as OpenAI
var fullPrompt = ""
-
+
// Add system context
if isWriteMode {
fullPrompt += """
You are a helpful writing assistant. The user will ask you to write or generate text for them.
Respond directly with the requested content. Be concise and helpful.
Output ONLY what they asked for - no explanations or preamble.
-
+
"""
} else {
fullPrompt += """
You are a writing assistant that rewrites text according to user instructions.
Follow the user's specific instructions for how to rewrite.
Output ONLY the rewritten text. No explanations, no quotes, no preamble.
-
+
"""
}
-
+
// Add conversation history
for message in messages {
if message.role == "user" {
@@ -103,14 +98,11 @@ final class AppleIntelligenceProvider {
fullPrompt += "Assistant: \(message.content)\n\n"
}
}
-
+
fullPrompt += "Assistant:"
-
+
let response = try await session.respond(to: fullPrompt)
return response.content
}
}
#endif
-
-
-
diff --git a/Sources/Fluid/Networking/FunctionCallingProvider.swift b/Sources/Fluid/Networking/FunctionCallingProvider.swift
index ca348a27..2b9057cb 100644
--- a/Sources/Fluid/Networking/FunctionCallingProvider.swift
+++ b/Sources/Fluid/Networking/FunctionCallingProvider.swift
@@ -2,26 +2,31 @@ import Foundation
/// Extends OpenAI-compatible API to support function calling with MCP tools
final class FunctionCallingProvider {
-
struct FunctionCall: Codable {
let name: String
- let arguments: String // JSON string
+ let arguments: String // JSON string
}
-
+
struct ToolCall: Codable {
let id: String
let type: String
let function: FunctionCall
}
-
+
struct ChatMessage: Codable {
let role: String
let content: String?
let tool_calls: [ToolCall]?
let tool_call_id: String?
let name: String?
-
- init(role: String, content: String?, tool_calls: [ToolCall]? = nil, tool_call_id: String? = nil, name: String? = nil) {
+
+ init(
+ role: String,
+ content: String?,
+ tool_calls: [ToolCall]? = nil,
+ tool_call_id: String? = nil,
+ name: String? = nil
+ ) {
self.role = role
self.content = content
self.tool_calls = tool_calls
@@ -29,25 +34,25 @@ final class FunctionCallingProvider {
self.name = name
}
}
-
+
struct ChatRequest: Encodable {
let model: String
let messages: [ChatMessage]
let temperature: Double?
let tools: [[String: Any]]?
let tool_choice: String?
-
+
enum CodingKeys: String, CodingKey {
case model, messages, temperature, tools, tool_choice
}
-
+
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(model, forKey: .model)
try container.encode(messages, forKey: .messages)
try container.encodeIfPresent(temperature, forKey: .temperature)
try container.encodeIfPresent(tool_choice, forKey: .tool_choice)
-
+
if let tools = tools {
let toolsData = try JSONSerialization.data(withJSONObject: tools)
let toolsArray = try JSONDecoder().decode([AnyCodable].self, from: toolsData)
@@ -55,25 +60,25 @@ final class FunctionCallingProvider {
}
}
}
-
+
struct ChatChoice: Codable {
let index: Int?
let message: ChatMessage
let finish_reason: String?
}
-
+
struct ChatResponse: Codable {
let choices: [ChatChoice]
}
-
+
// Helper for encoding/decoding Any
struct AnyCodable: Codable {
let value: Any
-
+
init(_ value: Any) {
self.value = value
}
-
+
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let dict = try? container.decode([String: AnyCodable].self) {
@@ -92,7 +97,7 @@ final class FunctionCallingProvider {
value = NSNull()
}
}
-
+
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
if let dict = value as? [String: Any] {
@@ -112,45 +117,47 @@ final class FunctionCallingProvider {
}
}
}
-
+
/// Result of LLM processing - either a text response or tool calls
enum LLMResult {
case textResponse(String)
case toolCalls([(name: String, arguments: [String: Any], callId: String)])
case error(String)
}
-
+
// Helper function to detect if the endpoint is local
private func isLocalEndpoint(_ urlString: String) -> Bool {
guard let url = URL(string: urlString),
let host = url.host else { return false }
-
+
let hostLower = host.lowercased()
-
+
// Check for localhost variations
if hostLower == "localhost" || hostLower == "127.0.0.1" {
return true
}
-
+
// Check for private IP ranges
- if hostLower.hasPrefix("127.") || hostLower.hasPrefix("10.") ||
- hostLower.hasPrefix("192.168.") {
+ if hostLower.hasPrefix("127.") || hostLower.hasPrefix("10.") ||
+ hostLower.hasPrefix("192.168.")
+ {
return true
}
-
+
// 172.16.x.x - 172.31.x.x
if hostLower.hasPrefix("172.") {
let components = hostLower.split(separator: ".")
if components.count >= 2,
let secondOctet = Int(components[1]),
- secondOctet >= 16 && secondOctet <= 31 {
+ secondOctet >= 16 && secondOctet <= 31
+ {
return true
}
}
-
+
return false
}
-
+
/// Process user input with LLM and MCP tools
func processWithTools(
userText: String,
@@ -160,99 +167,114 @@ final class FunctionCallingProvider {
apiKey: String,
baseURL: String
) async -> LLMResult {
- let endpoint = baseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?
+ let endpoint = baseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?
"https://api.openai.com/v1" : baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
-
+
// Build the full URL
let fullEndpoint: String
- if endpoint.contains("/chat/completions") ||
- endpoint.contains("/api/chat") ||
- endpoint.contains("/api/generate") {
+ if endpoint.contains("/chat/completions") ||
+ endpoint.contains("/api/chat") ||
+ endpoint.contains("/api/generate")
+ {
fullEndpoint = endpoint
} else {
fullEndpoint = endpoint + "/chat/completions"
}
-
+
guard let url = URL(string: fullEndpoint) else {
return .error("Invalid Base URL")
}
-
+
let isLocal = isLocalEndpoint(endpoint)
-
+
// Build messages array
var messages = conversationHistory
messages.append(ChatMessage(role: "user", content: userText))
-
+
// Check if this is a reasoning model that doesn't support temperature parameter
let modelLower = model.lowercased()
let isReasoningModel = modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3") || modelLower.hasPrefix("gpt-5")
-
+
let body = ChatRequest(
model: model,
messages: messages,
- temperature: isReasoningModel ? nil : 0.2, // Don't send temperature for reasoning models
+ temperature: isReasoningModel ? nil : 0.2, // Don't send temperature for reasoning models
tools: tools.isEmpty ? nil : tools,
tool_choice: tools.isEmpty ? nil : "auto"
)
-
- DebugLogger.shared.info("📤 Sending to LLM: \(tools.count) tools, model: \(model)", source: "FunctionCallingProvider")
+
+ DebugLogger.shared.info(
+ "📤 Sending to LLM: \(tools.count) tools, model: \(model)",
+ source: "FunctionCallingProvider"
+ )
if !tools.isEmpty {
- DebugLogger.shared.info("Tools in request: \(tools.map { ($0["function"] as? [String: Any])?["name"] as? String ?? "?" }.joined(separator: ", "))", source: "FunctionCallingProvider")
+ DebugLogger.shared
+ .info(
+ "Tools in request: \(tools.map { ($0["function"] as? [String: Any])?["name"] as? String ?? "?" }.joined(separator: ", "))",
+ source: "FunctionCallingProvider"
+ )
}
-
+
guard let jsonData = try? JSONEncoder().encode(body) else {
DebugLogger.shared.error("Failed to encode request", source: "FunctionCallingProvider")
return .error("Failed to encode request")
}
-
+
// Debug: Log request payload
if let requestString = String(data: jsonData, encoding: .utf8) {
DebugLogger.shared.debug("Request JSON: \(requestString)", source: "FunctionCallingProvider")
}
-
+
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
-
+
// Only add Authorization header for non-local endpoints
if !isLocal {
request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
}
-
+
request.httpBody = jsonData
-
+
do {
let (data, response) = try await URLSession.shared.data(for: request)
-
+
// Log response
if let responseString = String(data: data, encoding: .utf8) {
DebugLogger.shared.debug("📥 LLM Response: \(responseString)", source: "FunctionCallingProvider")
}
-
+
if let http = response as? HTTPURLResponse, http.statusCode >= 400 {
let errText = String(data: data, encoding: .utf8) ?? "Unknown error"
DebugLogger.shared.error("HTTP \(http.statusCode): \(errText)", source: "FunctionCallingProvider")
return .error("HTTP \(http.statusCode): \(errText)")
}
-
+
let decoded = try JSONDecoder().decode(ChatResponse.self, from: data)
guard let choice = decoded.choices.first else {
DebugLogger.shared.error("No choices in LLM response", source: "FunctionCallingProvider")
return .error("No response from LLM")
}
-
+
let message = choice.message
-
+
// Check if LLM wants to call tools
if let toolCalls = message.tool_calls, !toolCalls.isEmpty {
- DebugLogger.shared.info("🎯 LLM decided to call \(toolCalls.count) tools", source: "FunctionCallingProvider")
+ DebugLogger.shared.info(
+ "🎯 LLM decided to call \(toolCalls.count) tools",
+ source: "FunctionCallingProvider"
+ )
var parsedCalls: [(name: String, arguments: [String: Any], callId: String)] = []
-
+
for toolCall in toolCalls {
- DebugLogger.shared.info(" → \(toolCall.function.name)(\(toolCall.function.arguments))", source: "FunctionCallingProvider")
+ DebugLogger.shared.info(
+ " → \(toolCall.function.name)(\(toolCall.function.arguments))",
+ source: "FunctionCallingProvider"
+ )
// Parse arguments JSON string
if let argsData = toolCall.function.arguments.data(using: .utf8),
- let argsDict = try? JSONSerialization.jsonObject(with: argsData) as? [String: Any] {
+ let argsDict = try? JSONSerialization.jsonObject(with: argsData) as? [String: Any]
+ {
parsedCalls.append((
name: toolCall.function.name,
arguments: argsDict,
@@ -260,20 +282,26 @@ final class FunctionCallingProvider {
))
}
}
-
+
return .toolCalls(parsedCalls)
}
-
+
// Otherwise, return text response
- DebugLogger.shared.info("💭 LLM responded with text only (finish_reason: \(choice.finish_reason ?? "none"))", source: "FunctionCallingProvider")
+ DebugLogger.shared.info(
+ "💭 LLM responded with text only (finish_reason: \(choice.finish_reason ?? "none"))",
+ source: "FunctionCallingProvider"
+ )
return .textResponse(message.content ?? "<no content>")
-
+
} catch {
- DebugLogger.shared.error("❌ Function calling failed: \(error.localizedDescription)", source: "FunctionCallingProvider")
+ DebugLogger.shared.error(
+ "❌ Function calling failed: \(error.localizedDescription)",
+ source: "FunctionCallingProvider"
+ )
return .error(error.localizedDescription)
}
}
-
+
/// Continue conversation after tool execution
func continueWithToolResults(
conversationHistory: [ChatMessage],
@@ -282,73 +310,81 @@ final class FunctionCallingProvider {
apiKey: String,
baseURL: String
) async -> LLMResult {
- let endpoint = baseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?
+ let endpoint = baseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?
"https://api.openai.com/v1" : baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
-
+
let fullEndpoint: String
- if endpoint.contains("/chat/completions") ||
- endpoint.contains("/api/chat") ||
- endpoint.contains("/api/generate") {
+ if endpoint.contains("/chat/completions") ||
+ endpoint.contains("/api/chat") ||
+ endpoint.contains("/api/generate")
+ {
fullEndpoint = endpoint
} else {
fullEndpoint = endpoint + "/chat/completions"
}
-
+
guard let url = URL(string: fullEndpoint) else {
return .error("Invalid Base URL")
}
-
+
let isLocal = isLocalEndpoint(endpoint)
-
+
// Use conversation history as-is (tool messages should already be added by caller)
let messages = conversationHistory
-
+
// Check if this is a reasoning model that doesn't support temperature parameter
let modelLower = model.lowercased()
let isReasoningModel = modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3") || modelLower.hasPrefix("gpt-5")
-
+
// Don't pass tools or tool_choice in the final response request
// Some providers (like OpenAI) reject tool_choice when tools is nil
let body = ChatRequest(
model: model,
messages: messages,
- temperature: isReasoningModel ? nil : 0.2, // Don't send temperature for reasoning models
+ temperature: isReasoningModel ? nil : 0.2, // Don't send temperature for reasoning models
tools: nil,
tool_choice: nil
)
-
+
guard let jsonData = try? JSONEncoder().encode(body) else {
return .error("Failed to encode request")
}
-
+
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
-
+
if !isLocal {
request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
}
-
+
request.httpBody = jsonData
-
+
do {
let (data, response) = try await URLSession.shared.data(for: request)
-
+
if let http = response as? HTTPURLResponse, http.statusCode >= 400 {
let errText = String(data: data, encoding: .utf8) ?? "Unknown error"
- DebugLogger.shared.error("HTTP \(http.statusCode) in continueWithToolResults: \(errText)", source: "FunctionCallingProvider")
+ DebugLogger.shared.error(
+ "HTTP \(http.statusCode) in continueWithToolResults: \(errText)",
+ source: "FunctionCallingProvider"
+ )
return .error("HTTP \(http.statusCode): \(errText)")
}
-
+
let decoded = try JSONDecoder().decode(ChatResponse.self, from: data)
guard let choice = decoded.choices.first else {
return .error("No response from LLM")
}
-
- // If the model tries to call tools again despite tool_choice being "none",
+
+ // If the model tries to call tools again despite tool_choice being "none",
// just extract the text content or return a generic message
if let toolCalls = choice.message.tool_calls, !toolCalls.isEmpty {
- DebugLogger.shared.warning("Model tried to call tools in final response (tool_choice was 'none'). Ignoring tool calls.", source: "FunctionCallingProvider")
+ DebugLogger.shared
+ .warning(
+ "Model tried to call tools in final response (tool_choice was 'none'). Ignoring tool calls.",
+ source: "FunctionCallingProvider"
+ )
// Try to extract any text content if available
if let content = choice.message.content, !content.isEmpty {
return .textResponse(content)
@@ -356,13 +392,15 @@ final class FunctionCallingProvider {
// Otherwise, return a generic success message
return .textResponse("Task completed successfully.")
}
-
+
return .textResponse(choice.message.content ?? "<no content>")
-
+
} catch {
- DebugLogger.shared.error("Error in continueWithToolResults: \(error.localizedDescription)", source: "FunctionCallingProvider")
+ DebugLogger.shared.error(
+ "Error in continueWithToolResults: \(error.localizedDescription)",
+ source: "FunctionCallingProvider"
+ )
return .error(error.localizedDescription)
}
}
}
-
diff --git a/Sources/Fluid/Networking/ModelDownloader.swift b/Sources/Fluid/Networking/ModelDownloader.swift
index a454c9c3..f575ccd8 100644
--- a/Sources/Fluid/Networking/ModelDownloader.swift
+++ b/Sources/Fluid/Networking/ModelDownloader.swift
@@ -1,5 +1,5 @@
-import Foundation
import CoreML
+import Foundation
#if arch(arm64)
import FluidAudio
#endif
@@ -7,16 +7,13 @@ import FluidAudio
/// A robust downloader for Hugging Face models with progress tracking and error handling.
/// Supports downloading entire model repositories with proper file structure preservation.
/// Can be configured to use different model repositories for flexibility.
-final class HuggingFaceModelDownloader
-{
- struct HFEntry: Decodable
- {
+final class HuggingFaceModelDownloader {
+ struct HFEntry: Decodable {
let type: String
let path: String
}
- struct ModelItem
- {
+ struct ModelItem {
let path: String
let isDirectory: Bool
}
@@ -31,18 +28,17 @@ final class HuggingFaceModelDownloader
private var baseResolveURL: URL
/// Initialize with default model repository settings
- init()
- {
- self.owner = "FluidInference"
- self.repo = "parakeet-tdt-0.6b-v3-coreml"
- self.revision = "main"
- self.baseApiURL = URL(string: "https://huggingface.co/api/models/")!
+ init() {
+ owner = "FluidInference"
+ repo = "parakeet-tdt-0.6b-v3-coreml"
+ revision = "main"
+ baseApiURL = URL(string: "https://huggingface.co/api/models/")!
.appendingPathComponent(owner)
.appendingPathComponent(repo)
.appendingPathComponent("tree")
.appendingPathComponent(revision)
- self.baseResolveURL = URL(string: "https://huggingface.co/")!
+ baseResolveURL = URL(string: "https://huggingface.co/")!
.appendingPathComponent(owner)
.appendingPathComponent(repo)
.appendingPathComponent("resolve")
@@ -54,57 +50,47 @@ final class HuggingFaceModelDownloader
/// - owner: Hugging Face username or organization
/// - repo: Repository name containing the models
/// - revision: Branch or commit hash (default: "main")
- init(owner: String, repo: String, revision: String = "main")
- {
+ init(owner: String, repo: String, revision: String = "main") {
self.owner = owner
self.repo = repo
self.revision = revision
- self.baseApiURL = URL(string: "https://huggingface.co/api/models/")!
+ baseApiURL = URL(string: "https://huggingface.co/api/models/")!
.appendingPathComponent(owner)
.appendingPathComponent(repo)
.appendingPathComponent("tree")
.appendingPathComponent(revision)
- self.baseResolveURL = URL(string: "https://huggingface.co/")!
+ baseResolveURL = URL(string: "https://huggingface.co/")!
.appendingPathComponent(owner)
.appendingPathComponent(repo)
.appendingPathComponent("resolve")
.appendingPathComponent(revision)
}
- func ensureModelsPresent(at targetRoot: URL, onProgress: ((Double, String) -> Void)? = nil) async throws
- {
+ func ensureModelsPresent(at targetRoot: URL, onProgress: ((Double, String) -> Void)? = nil) async throws {
try FileManager.default.createDirectory(at: targetRoot, withIntermediateDirectories: true)
// Build list of files to download (flatten directories via HF API tree)
var pendingFiles: [String] = []
- for item in requiredItems()
- {
- if item.isDirectory
- {
+ for item in requiredItems() {
+ if item.isDirectory {
let files = try await listFilesRecursively(relativePath: item.path)
- for rel in files
- {
+ for rel in files {
let dest = targetRoot.appendingPathComponent(rel)
- if FileManager.default.fileExists(atPath: dest.path) == false
- {
+ if FileManager.default.fileExists(atPath: dest.path) == false {
pendingFiles.append(rel)
}
}
- }
- else
- {
+ } else {
let dest = targetRoot.appendingPathComponent(item.path)
- if FileManager.default.fileExists(atPath: dest.path) == false
- {
+ if FileManager.default.fileExists(atPath: dest.path) == false {
pendingFiles.append(item.path)
}
}
}
// If nothing to download, say so clearly
- if pendingFiles.isEmpty
- {
+ if pendingFiles.isEmpty {
print("[ModelDL] All required model files are already present. Nothing to download.")
onProgress?(1.0, "")
return
@@ -113,8 +99,7 @@ final class HuggingFaceModelDownloader
// Compute total bytes (best-effort) for determinate progress
var sizeByPath: [String: Int64] = [:]
var totalBytes: Int64 = 0
- for rel in pendingFiles
- {
+ for rel in pendingFiles {
let expected = try await headExpectedLength(relativePath: rel)
sizeByPath[rel] = expected
if expected > 0 { totalBytes += expected }
@@ -127,15 +112,12 @@ final class HuggingFaceModelDownloader
let fallbackTotal = pendingFiles.count
var fallbackCompleted = 0
- for (idx, rel) in pendingFiles.enumerated()
- {
- print("[ModelDL] (\(idx+1)/\(pendingFiles.count)) Downloading: \(rel)")
+ 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
- if totalBytes > 0
- {
+ if totalBytes > 0 {
let expected = sizeByPath[rel] ?? 0
- if expected > 0
- {
+ if expected > 0 {
let overallBase = Double(downloadedBytes) / Double(totalBytes)
let combined = min(1.0, overallBase + (perFilePct * Double(expected)) / Double(totalBytes))
onProgress?(combined, rel)
@@ -144,15 +126,15 @@ final class HuggingFaceModelDownloader
}
}
}
- if totalBytes > 0
- {
+ if totalBytes > 0 {
downloadedBytes += (sizeByPath[rel] ?? 0)
let pct = min(1.0, Double(downloadedBytes) / Double(totalBytes))
onProgress?(pct, rel)
- print(String(format: "[ModelDL] Overall progress: %.1f%% (\(Self.formatBytes(downloadedBytes))/\(Self.formatBytes(totalBytes)))", pct * 100.0))
- }
- else if fallbackTotal > 0
- {
+ print(String(
+ format: "[ModelDL] Overall progress: %.1f%% (\(Self.formatBytes(downloadedBytes))/\(Self.formatBytes(totalBytes)))",
+ pct * 100.0
+ ))
+ } else if fallbackTotal > 0 {
fallbackCompleted += 1
onProgress?(Double(fallbackCompleted) / Double(fallbackTotal), rel)
print("[ModelDL] Overall progress: \(fallbackCompleted)/\(fallbackTotal)")
@@ -160,33 +142,36 @@ final class HuggingFaceModelDownloader
}
}
- private func requiredItems() -> [ModelItem]
- {
+ private func requiredItems() -> [ModelItem] {
return [
// Preferred v3 unified model file names used by FluidAudio 0.5+
ModelItem(path: "MelEncoder.mlmodelc", isDirectory: true),
ModelItem(path: "Decoder.mlmodelc", isDirectory: true),
ModelItem(path: "JointDecision.mlmodelc", isDirectory: true),
- ModelItem(path: "parakeet_v3_vocab.json", isDirectory: false)
+ ModelItem(path: "parakeet_v3_vocab.json", isDirectory: false),
]
}
- private func downloadDirectory(relativePath: String, to destination: URL) async throws
- {
+ private func downloadDirectory(relativePath: String, to destination: URL) async throws {
try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true)
// Download entire directory by enumerating all files
let files = try await listFilesRecursively(relativePath: relativePath)
- for rel in files
- {
+ for rel in files {
let dest = destination.deletingLastPathComponent().appendingPathComponent(rel)
- try FileManager.default.createDirectory(at: dest.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(
+ at: dest.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
try await downloadFile(relativePath: rel, to: dest)
}
}
- private func downloadFile(relativePath: String, to destination: URL, perFileProgress: ((Double) -> Void)? = nil) async throws
- {
+ private func downloadFile(
+ relativePath: String,
+ to destination: URL,
+ perFileProgress: ((Double) -> Void)? = nil
+ ) async throws {
let fileURL = baseResolveURL.appendingPathComponent(relativePath)
let delegate = DownloadProgressDelegate(onProgress: perFileProgress)
@@ -195,23 +180,21 @@ final class HuggingFaceModelDownloader
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
delegate.onFinish = { tempUrl, response in
- do
- {
- if let http = response as? HTTPURLResponse, http.statusCode >= 400
- {
+ do {
+ if let http = response as? HTTPURLResponse, http.statusCode >= 400 {
continuation.resume(throwing: NSError(domain: "HF", code: http.statusCode))
return
}
- try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
- if FileManager.default.fileExists(atPath: destination.path)
- {
+ try FileManager.default.createDirectory(
+ at: destination.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
+ if FileManager.default.fileExists(atPath: destination.path) {
try FileManager.default.removeItem(at: destination)
}
try FileManager.default.moveItem(at: tempUrl, to: destination)
continuation.resume()
- }
- catch
- {
+ } catch {
continuation.resume(throwing: error)
}
}
@@ -222,38 +205,42 @@ final class HuggingFaceModelDownloader
}
}
- private final class DownloadProgressDelegate: NSObject, URLSessionDownloadDelegate
- {
+ private final class DownloadProgressDelegate: NSObject, URLSessionDownloadDelegate {
private let onProgress: ((Double) -> Void)?
var onFinish: ((URL, URLResponse) -> Void)?
var onError: ((Error) -> Void)?
- init(onProgress: ((Double) -> Void)?)
- {
+ init(onProgress: ((Double) -> Void)?) {
self.onProgress = onProgress
}
- func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
- {
+ func urlSession(
+ _ session: URLSession,
+ downloadTask: URLSessionDownloadTask,
+ didFinishDownloadingTo location: URL
+ ) {
guard let response = downloadTask.response else { return }
onFinish?(location, response)
}
- func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
- {
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let error = error { onError?(error) }
}
- func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
- {
+ func urlSession(
+ _ session: URLSession,
+ downloadTask: URLSessionDownloadTask,
+ didWriteData bytesWritten: Int64,
+ totalBytesWritten: Int64,
+ totalBytesExpectedToWrite: Int64
+ ) {
guard totalBytesExpectedToWrite > 0 else { return }
let pct = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
onProgress?(pct)
}
}
- private func headExpectedLength(relativePath: String) async throws -> Int64
- {
+ private func headExpectedLength(relativePath: String) async throws -> Int64 {
let fileURL = baseResolveURL.appendingPathComponent(relativePath)
var req = URLRequest(url: fileURL)
req.httpMethod = "HEAD"
@@ -264,16 +251,14 @@ final class HuggingFaceModelDownloader
return http.expectedContentLength
}
- private func listFilesRecursively(relativePath: String) async throws -> [String]
- {
+ private func listFilesRecursively(relativePath: String) async throws -> [String] {
let listingURL = baseApiURL
.appendingPathComponent(relativePath)
var comps = URLComponents(url: listingURL, resolvingAgainstBaseURL: false)!
comps.queryItems = [URLQueryItem(name: "recursive", value: "1")]
let (data, resp) = try await URLSession.shared.data(from: comps.url!)
- if let http = resp as? HTTPURLResponse, http.statusCode >= 400
- {
+ if let http = resp as? HTTPURLResponse, http.statusCode >= 400 {
throw NSError(domain: "HF", code: http.statusCode)
}
@@ -285,8 +270,7 @@ final class HuggingFaceModelDownloader
.map { $0.path }
}
- private static func formatBytes(_ bytes: Int64) -> String
- {
+ private static func formatBytes(_ bytes: Int64) -> String {
let kb: Double = 1024
let mb = kb * 1024
let gb = mb * 1024
@@ -299,11 +283,9 @@ final class HuggingFaceModelDownloader
}
#if arch(arm64)
-extension HuggingFaceModelDownloader
-{
+extension HuggingFaceModelDownloader {
/// Load ASR models directly from disk using unified v3 model names
- func loadLocalAsrModels(from repoDirectory: URL) async throws -> AsrModels
- {
+ func loadLocalAsrModels(from repoDirectory: URL) async throws -> AsrModels {
let config = AsrModels.defaultConfiguration()
let fm = FileManager.default
@@ -321,10 +303,10 @@ extension HuggingFaceModelDownloader
// Check if new structure exists
let hasNewStructure = fm.fileExists(atPath: preprocessorUrl.path) && fm.fileExists(atPath: encoderUrl.path)
-
+
let encoder: MLModel
let preprocessor: MLModel?
-
+
if hasNewStructure {
// Load with new structure (separate Preprocessor and Encoder)
print("[ModelDL] Loading with new model structure (Preprocessor + Encoder)")
@@ -336,14 +318,14 @@ extension HuggingFaceModelDownloader
print("[ModelDL] New structure not found, trying legacy MelEncoder")
print("[ModelDL] MelEncoder path: \(melEncUrl.path)")
print("[ModelDL] MelEncoder exists: \(fm.fileExists(atPath: melEncUrl.path))")
-
+
if fm.fileExists(atPath: melEncUrl.path) {
encoder = try MLModel(contentsOf: melEncUrl, configuration: config)
preprocessor = nil
print("[ModelDL] Using MelEncoder (legacy mode)")
} else {
throw NSError(domain: "ModelDL", code: -1, userInfo: [
- NSLocalizedDescriptionKey: "Neither new model structure (Preprocessor + Encoder) nor legacy structure (MelEncoder) found"
+ NSLocalizedDescriptionKey: "Neither new model structure (Preprocessor + Encoder) nor legacy structure (MelEncoder) found",
])
}
}
@@ -353,9 +335,14 @@ extension HuggingFaceModelDownloader
let joint = try MLModel(contentsOf: jointUrl, configuration: config)
// Load vocabulary (JSON: {"0": "<pad>", ...}) from repo root
- let vocabPath = repoDirectory.deletingLastPathComponent().appendingPathComponent("parakeet-tdt-0.6b-v3-coreml").appendingPathComponent("parakeet_v3_vocab.json")
+ let vocabPath = repoDirectory.deletingLastPathComponent().appendingPathComponent("parakeet-tdt-0.6b-v3-coreml")
+ .appendingPathComponent("parakeet_v3_vocab.json")
guard fm.fileExists(atPath: vocabPath.path) else {
- throw NSError(domain: "ModelDL", code: -2, userInfo: [NSLocalizedDescriptionKey: "Vocabulary file not found at \(vocabPath.path)"])
+ throw NSError(
+ domain: "ModelDL",
+ code: -2,
+ userInfo: [NSLocalizedDescriptionKey: "Vocabulary file not found at \(vocabPath.path)"]
+ )
}
let vocabData = try Data(contentsOf: vocabPath)
let raw = try JSONSerialization.jsonObject(with: vocabData) as? [String: String] ?? [:]
@@ -370,7 +357,7 @@ extension HuggingFaceModelDownloader
// For v2 models without separate preprocessor, use encoder as preprocessor
// For v3 models, use the separate preprocessor
let finalPreprocessor = preprocessor ?? encoder
-
+
return AsrModels(
encoder: encoder,
preprocessor: finalPreprocessor,
diff --git a/Sources/Fluid/Persistence/ChatHistoryStore.swift b/Sources/Fluid/Persistence/ChatHistoryStore.swift
index bc46a090..edf8f86e 100644
--- a/Sources/Fluid/Persistence/ChatHistoryStore.swift
+++ b/Sources/Fluid/Persistence/ChatHistoryStore.swift
@@ -1,12 +1,5 @@
-//
-// ChatHistoryStore.swift
-// Fluid
-//
-// Persistence manager for Command Mode chat history
-//
-
-import Foundation
import Combine
+import Foundation
// MARK: - Chat Message Model (Codable version of CommandModeService.Message)
@@ -17,13 +10,13 @@ struct ChatMessage: Codable, Identifiable, Equatable {
let toolCall: ToolCall?
let stepType: StepType
let timestamp: Date
-
+
enum Role: String, Codable, Equatable {
case user
case assistant
case tool
}
-
+
enum StepType: String, Codable, Equatable {
case normal
case thinking
@@ -33,15 +26,22 @@ struct ChatMessage: Codable, Identifiable, Equatable {
case success
case failure
}
-
+
struct ToolCall: Codable, Equatable {
let id: String
let command: String
let workingDirectory: String?
let purpose: String?
}
-
- init(id: UUID = UUID(), role: Role, content: String, toolCall: ToolCall? = nil, stepType: StepType = .normal, timestamp: Date = Date()) {
+
+ init(
+ id: UUID = UUID(),
+ role: Role,
+ content: String,
+ toolCall: ToolCall? = nil,
+ stepType: StepType = .normal,
+ timestamp: Date = Date()
+ ) {
self.id = id
self.role = role
self.content = content
@@ -59,15 +59,21 @@ struct ChatSession: Codable, Identifiable, Equatable {
let createdAt: Date
var updatedAt: Date
var messages: [ChatMessage]
-
- init(id: String = UUID().uuidString, title: String = "New Chat", createdAt: Date = Date(), updatedAt: Date = Date(), messages: [ChatMessage] = []) {
+
+ init(
+ id: String = UUID().uuidString,
+ title: String = "New Chat",
+ createdAt: Date = Date(),
+ updatedAt: Date = Date(),
+ messages: [ChatMessage] = []
+ ) {
self.id = id
self.title = title
self.createdAt = createdAt
self.updatedAt = updatedAt
self.messages = messages
}
-
+
/// Generate title from first user message (max 50 chars)
mutating func updateTitleFromFirstMessage() {
guard let firstUserMessage = messages.first(where: { $0.role == .user }) else { return }
@@ -78,7 +84,7 @@ struct ChatSession: Codable, Identifiable, Equatable {
title = content.isEmpty ? "New Chat" : content
}
}
-
+
/// Relative time string for display
var relativeTimeString: String {
let formatter = RelativeDateTimeFormatter()
@@ -92,21 +98,21 @@ struct ChatSession: Codable, Identifiable, Equatable {
@MainActor
final class ChatHistoryStore: ObservableObject {
static let shared = ChatHistoryStore()
-
+
private let defaults = UserDefaults.standard
private let maxChats = 30
-
+
private enum Keys {
static let chatSessions = "CommandModeChatSessions"
static let currentChatID = "CommandModeCurrentChatID"
}
-
+
@Published private(set) var sessions: [ChatSession] = []
@Published var currentChatID: String?
-
+
private init() {
loadSessions()
-
+
// Ensure there's always a current chat
if currentChatID == nil || sessions.first(where: { $0.id == currentChatID }) == nil {
if let first = sessions.first {
@@ -120,15 +126,15 @@ final class ChatHistoryStore: ObservableObject {
}
}
}
-
+
// MARK: - Public Methods
-
+
/// Get the current active chat session
var currentSession: ChatSession? {
guard let id = currentChatID else { return nil }
return 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 }
@@ -137,21 +143,21 @@ final class ChatHistoryStore: ObservableObject {
}
return result
}
-
+
/// Create a new chat and set it as current
@discardableResult
func createNewChat() -> ChatSession {
let newChat = ChatSession()
sessions.insert(newChat, at: 0)
currentChatID = newChat.id
-
+
// Trim old chats if over limit
trimOldChats()
saveSessions()
-
+
return newChat
}
-
+
/// Save/update a chat session
func saveChat(_ session: ChatSession) {
if let index = sessions.firstIndex(where: { $0.id == session.id }) {
@@ -163,25 +169,25 @@ final class ChatHistoryStore: ObservableObject {
updated.updatedAt = Date()
sessions.insert(updated, at: 0)
}
-
+
trimOldChats()
saveSessions()
}
-
+
/// Update current chat with messages
func updateCurrentChat(messages: [ChatMessage]) {
guard let id = currentChatID,
let index = sessions.firstIndex(where: { $0.id == id }) else { return }
-
+
var session = sessions[index]
session.messages = messages
session.updatedAt = Date()
session.updateTitleFromFirstMessage()
sessions[index] = session
-
+
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 }
@@ -189,16 +195,16 @@ final class ChatHistoryStore: ObservableObject {
saveCurrentChatID()
return session
}
-
+
/// Switch to a different chat
func switchToChat(id: String) -> ChatSession? {
return loadChat(id: id)
}
-
+
/// Delete a chat by ID
func deleteChat(id: String) {
sessions.removeAll { $0.id == id }
-
+
// If deleted current chat, switch to most recent or create new
if currentChatID == id {
if let first = sessions.sorted(by: { $0.updatedAt > $1.updatedAt }).first {
@@ -209,42 +215,43 @@ final class ChatHistoryStore: ObservableObject {
currentChatID = newChat.id
}
}
-
+
saveSessions()
}
-
+
/// Delete current chat and switch to next
func deleteCurrentChat() {
guard let id = currentChatID else { return }
deleteChat(id: id)
}
-
+
/// Clear current chat (delete messages but keep session)
func clearCurrentChat() {
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()
-
+
saveSessions()
}
-
+
// MARK: - Private Methods
-
+
private func loadSessions() {
guard let data = defaults.data(forKey: Keys.chatSessions),
- let decoded = try? JSONDecoder().decode([ChatSession].self, from: data) else {
+ let decoded = try? JSONDecoder().decode([ChatSession].self, from: data)
+ else {
sessions = []
return
}
sessions = decoded
-
+
// Load current chat ID
currentChatID = defaults.string(forKey: Keys.currentChatID)
}
-
+
private func saveSessions() {
if let encoded = try? JSONEncoder().encode(sessions) {
defaults.set(encoded, forKey: Keys.chatSessions)
@@ -252,11 +259,11 @@ final class ChatHistoryStore: ObservableObject {
saveCurrentChatID()
objectWillChange.send()
}
-
+
private func saveCurrentChatID() {
defaults.set(currentChatID, forKey: Keys.currentChatID)
}
-
+
private func trimOldChats() {
if sessions.count > maxChats {
// Sort by updatedAt and keep most recent
@@ -265,5 +272,3 @@ final class ChatHistoryStore: ObservableObject {
}
}
}
-
-
diff --git a/Sources/Fluid/Persistence/KeychainService.swift b/Sources/Fluid/Persistence/KeychainService.swift
index 5e07eb82..08268217 100644
--- a/Sources/Fluid/Persistence/KeychainService.swift
+++ b/Sources/Fluid/Persistence/KeychainService.swift
@@ -9,7 +9,7 @@ enum KeychainServiceError: Error, LocalizedError {
switch self {
case .invalidData:
return "Failed to convert key data."
- case .unhandled(let status):
+ case let .unhandled(status):
if let message = SecCopyErrorMessageString(status, nil) as String? {
return message
}
@@ -72,7 +72,7 @@ final class KeychainService {
kSecAttrService as String: service,
kSecReturnAttributes as String: true,
kSecReturnData as String: true,
- kSecMatchLimit as String: kSecMatchLimitAll
+ kSecMatchLimit as String: kSecMatchLimitAll,
]
var items: CFTypeRef?
@@ -85,7 +85,8 @@ final class KeychainService {
guard let providerID = attributes[kSecAttrAccount as String] as? String,
providerID != account,
let data = attributes[kSecValueData as String] as? Data,
- let key = String(data: data, encoding: .utf8) else {
+ let key = String(data: data, encoding: .utf8)
+ else {
continue
}
result[providerID] = key
@@ -103,7 +104,7 @@ final class KeychainService {
if let providerIDs {
targets = providerIDs
} else {
- targets = Array((try legacyProviderEntries()).keys)
+ targets = try Array(legacyProviderEntries().keys)
}
for providerID in targets {
@@ -158,8 +159,10 @@ final class KeychainService {
try removeLegacyEntries()
return
case errSecDuplicateItem:
- let updateStatus = SecItemUpdate(aggregatedQuery() as CFDictionary,
- [kSecValueData as String: data] as CFDictionary)
+ let updateStatus = SecItemUpdate(
+ aggregatedQuery() as CFDictionary,
+ [kSecValueData as String: data] as CFDictionary
+ )
guard updateStatus == errSecSuccess else {
throw KeychainServiceError.unhandled(updateStatus)
}
@@ -173,7 +176,7 @@ final class KeychainService {
[
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
- kSecAttrAccount as String: account
+ kSecAttrAccount as String: account,
]
}
@@ -181,8 +184,7 @@ final class KeychainService {
[
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
- kSecAttrAccount as String: providerID
+ kSecAttrAccount as String: providerID,
]
}
}
-
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index 1f6c653d..1efee881 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -1,11 +1,10 @@
-import Foundation
-import ServiceManagement
-import ApplicationServices
import AppKit
+import ApplicationServices
import Combine
+import Foundation
+import ServiceManagement
-final class SettingsStore: ObservableObject
-{
+final class SettingsStore: ObservableObject {
static let shared = SettingsStore()
private let defaults = UserDefaults.standard
private let keychain = KeychainService.shared
@@ -16,10 +15,9 @@ final class SettingsStore: ObservableObject
}
// Keys
- private enum Keys
- {
+ private enum Keys {
static let enableAIProcessing = "EnableAIProcessing"
- static let enableDebugLogs = "EnableDebugLogs"
+ static let enableDebugLogs = "EnableDebugLogs"
static let availableAIModels = "AvailableAIModels"
static let availableModelsByProvider = "AvailableModelsByProvider"
static let selectedAIModel = "SelectedAIModel"
@@ -29,8 +27,8 @@ final class SettingsStore: ObservableObject
static let providerAPIKeyIdentifiers = "ProviderAPIKeyIdentifiers"
static let savedProviders = "SavedProviders"
static let hotkeyShortcutKey = "HotkeyShortcutKey"
- static let preferredInputDeviceUID = "PreferredInputDeviceUID"
- static let preferredOutputDeviceUID = "PreferredOutputDeviceUID"
+ static let preferredInputDeviceUID = "PreferredInputDeviceUID"
+ static let preferredOutputDeviceUID = "PreferredOutputDeviceUID"
static let visualizerNoiseThreshold = "VisualizerNoiseThreshold"
static let launchAtStartup = "LaunchAtStartup"
static let showInDock = "ShowInDock"
@@ -41,7 +39,7 @@ final class SettingsStore: ObservableObject
static let autoUpdateCheckEnabled = "AutoUpdateCheckEnabled"
static let lastUpdateCheckDate = "LastUpdateCheckDate"
static let playgroundUsed = "PlaygroundUsed"
-
+
// Command Mode Keys
static let commandModeSelectedModel = "CommandModeSelectedModel"
static let commandModeSelectedProviderID = "CommandModeSelectedProviderID"
@@ -49,69 +47,83 @@ final class SettingsStore: ObservableObject
static let commandModeConfirmBeforeExecute = "CommandModeConfirmBeforeExecute"
static let commandModeLinkedToGlobal = "CommandModeLinkedToGlobal"
static let commandModeShortcutEnabled = "CommandModeShortcutEnabled"
-
+
// Rewrite Mode Keys
static let rewriteModeHotkeyShortcut = "RewriteModeHotkeyShortcut"
static let rewriteModeSelectedModel = "RewriteModeSelectedModel"
static let rewriteModeSelectedProviderID = "RewriteModeSelectedProviderID"
static let rewriteModeLinkedToGlobal = "RewriteModeLinkedToGlobal"
-
+
// Model Reasoning Config Keys
static let modelReasoningConfigs = "ModelReasoningConfigs"
static let rewriteModeShortcutEnabled = "RewriteModeShortcutEnabled"
-
+
// Stats Keys
static let userTypingWPM = "UserTypingWPM"
// Filler Words
static let fillerWords = "FillerWords"
static let removeFillerWordsEnabled = "RemoveFillerWordsEnabled"
-
+
// Transcription Provider (ASR)
static let selectedTranscriptionProvider = "SelectedTranscriptionProvider"
static let whisperModelSize = "WhisperModelSize"
-
+
// Unified Speech Model (replaces above two)
static let selectedSpeechModel = "SelectedSpeechModel"
}
-
+
// MARK: - Model Reasoning Configuration
-
+
/// Configuration for model-specific reasoning/thinking parameters
struct ModelReasoningConfig: Codable, Equatable {
/// The parameter name to use (e.g., "reasoning_effort", "enable_thinking", "thinking")
var parameterName: String
-
+
/// The value to use for the parameter (e.g., "low", "medium", "high", "none", "true")
var parameterValue: String
-
+
/// Whether this config is enabled (allows disabling without deleting)
var isEnabled: Bool
-
+
init(parameterName: String = "reasoning_effort", parameterValue: String = "low", isEnabled: Bool = true) {
self.parameterName = parameterName
self.parameterValue = parameterValue
self.isEnabled = isEnabled
}
-
+
/// Common presets for different model types
- static let openAIGPT5 = ModelReasoningConfig(parameterName: "reasoning_effort", parameterValue: "low", isEnabled: true)
- static let openAIO1 = ModelReasoningConfig(parameterName: "reasoning_effort", parameterValue: "medium", isEnabled: true)
- static let groqGPTOSS = ModelReasoningConfig(parameterName: "reasoning_effort", parameterValue: "low", isEnabled: true)
- static let deepSeekReasoner = ModelReasoningConfig(parameterName: "enable_thinking", parameterValue: "true", isEnabled: true)
+ static let openAIGPT5 = ModelReasoningConfig(
+ parameterName: "reasoning_effort",
+ parameterValue: "low",
+ isEnabled: true
+ )
+ static let openAIO1 = ModelReasoningConfig(
+ parameterName: "reasoning_effort",
+ parameterValue: "medium",
+ isEnabled: true
+ )
+ static let groqGPTOSS = ModelReasoningConfig(
+ parameterName: "reasoning_effort",
+ parameterValue: "low",
+ isEnabled: true
+ )
+ static let deepSeekReasoner = ModelReasoningConfig(
+ parameterName: "enable_thinking",
+ parameterValue: "true",
+ isEnabled: true
+ )
static let disabled = ModelReasoningConfig(parameterName: "", parameterValue: "", isEnabled: false)
}
- struct SavedProvider: Codable, Identifiable, Hashable
- {
+ struct SavedProvider: Codable, Identifiable, Hashable {
let id: String
let name: String
let baseURL: String
let apiKey: String
let models: [String]
- init(id: String = UUID().uuidString, name: String, baseURL: String, apiKey: String = "", models: [String] = [])
- {
+ init(id: String = UUID().uuidString, name: String, baseURL: String, apiKey: String = "", models: [String] = []) {
self.id = id
self.name = name
self.baseURL = baseURL
@@ -120,8 +132,7 @@ final class SettingsStore: ObservableObject
}
}
- var enableAIProcessing: Bool
- {
+ var enableAIProcessing: Bool {
get { defaults.bool(forKey: Keys.enableAIProcessing) }
set {
objectWillChange.send()
@@ -129,8 +140,7 @@ final class SettingsStore: ObservableObject
}
}
- var availableModels: [String]
- {
+ var availableModels: [String] {
get { (defaults.array(forKey: Keys.availableAIModels) as? [String]) ?? [] }
set {
objectWillChange.send()
@@ -138,8 +148,7 @@ final class SettingsStore: ObservableObject
}
}
- var availableModelsByProvider: [String: [String]]
- {
+ var availableModelsByProvider: [String: [String]] {
get { (defaults.dictionary(forKey: Keys.availableModelsByProvider) as? [String: [String]]) ?? [:] }
set {
objectWillChange.send()
@@ -147,17 +156,15 @@ final class SettingsStore: ObservableObject
}
}
- var enableDebugLogs: Bool
- {
- get { defaults.bool(forKey: Keys.enableDebugLogs) }
- set {
- objectWillChange.send()
- defaults.set(newValue, forKey: Keys.enableDebugLogs)
- }
- }
-
- var selectedModel: String?
- {
+ var enableDebugLogs: Bool {
+ get { defaults.bool(forKey: Keys.enableDebugLogs) }
+ set {
+ objectWillChange.send()
+ defaults.set(newValue, forKey: Keys.enableDebugLogs)
+ }
+ }
+
+ var selectedModel: String? {
get { defaults.string(forKey: Keys.selectedAIModel) }
set {
objectWillChange.send()
@@ -165,8 +172,7 @@ final class SettingsStore: ObservableObject
}
}
- var selectedModelByProvider: [String: String]
- {
+ var selectedModelByProvider: [String: String] {
get { (defaults.dictionary(forKey: Keys.selectedModelByProvider) as? [String: String]) ?? [:] }
set {
objectWillChange.send()
@@ -181,20 +187,19 @@ final class SettingsStore: ObservableObject
persistProviderAPIKeys(newValue)
}
}
-
+
/// Securely retrieve API key for a provider, handling custom prefix logic
func getAPIKey(for providerID: String) -> String? {
let keys = providerAPIKeys
// Try exact match first
if let key = keys[providerID] { return key }
-
+
// Try canonical key format (custom:ID)
let canonical = canonicalProviderKey(for: providerID)
return keys[canonical]
}
- var selectedProviderID: String
- {
+ var selectedProviderID: String {
get { defaults.string(forKey: Keys.selectedProviderID) ?? "openai" }
set {
objectWillChange.send()
@@ -212,11 +217,13 @@ final class SettingsStore: ObservableObject
objectWillChange.send()
let sanitized = newValue.map { provider -> SavedProvider in
if provider.apiKey.isEmpty { return provider }
- return SavedProvider(id: provider.id,
- name: provider.name,
- baseURL: provider.baseURL,
- apiKey: "",
- models: provider.models)
+ return SavedProvider(
+ id: provider.id,
+ name: provider.name,
+ baseURL: provider.baseURL,
+ apiKey: "",
+ models: provider.models
+ )
}
if let encoded = try? JSONEncoder().encode(sanitized) {
defaults.set(encoded, forKey: Keys.savedProviders)
@@ -224,10 +231,8 @@ final class SettingsStore: ObservableObject
}
}
- var hotkeyShortcut: HotkeyShortcut
- {
- get
- {
+ var hotkeyShortcut: HotkeyShortcut {
+ get {
if let data = defaults.data(forKey: Keys.hotkeyShortcutKey),
let shortcut = try? JSONDecoder().decode(HotkeyShortcut.self, from: data)
{
@@ -235,25 +240,20 @@ final class SettingsStore: ObservableObject
}
return HotkeyShortcut(keyCode: 61, modifierFlags: [])
}
- set
- {
+ set {
objectWillChange.send()
- if let data = try? JSONEncoder().encode(newValue)
- {
+ if let data = try? JSONEncoder().encode(newValue) {
defaults.set(data, forKey: Keys.hotkeyShortcutKey)
}
}
}
-
- var pressAndHoldMode: Bool
- {
+ var pressAndHoldMode: Bool {
get { defaults.bool(forKey: Keys.pressAndHoldMode) }
set { defaults.set(newValue, forKey: Keys.pressAndHoldMode) }
}
- var enableStreamingPreview: Bool
- {
+ var enableStreamingPreview: Bool {
get {
let value = defaults.object(forKey: Keys.enableStreamingPreview)
return value as? Bool ?? true // Default to true (enabled)
@@ -261,8 +261,7 @@ final class SettingsStore: ObservableObject
set { defaults.set(newValue, forKey: Keys.enableStreamingPreview) }
}
- var enableAIStreaming: Bool
- {
+ var enableAIStreaming: Bool {
get {
let value = defaults.object(forKey: Keys.enableAIStreaming)
return value as? Bool ?? false // Default to false (disabled)
@@ -273,26 +272,22 @@ final class SettingsStore: ObservableObject
}
}
- var copyTranscriptionToClipboard: Bool
- {
+ var copyTranscriptionToClipboard: Bool {
get { defaults.bool(forKey: Keys.copyTranscriptionToClipboard) }
set { defaults.set(newValue, forKey: Keys.copyTranscriptionToClipboard) }
}
- var preferredInputDeviceUID: String?
- {
- get { defaults.string(forKey: Keys.preferredInputDeviceUID) }
- set { defaults.set(newValue, forKey: Keys.preferredInputDeviceUID) }
- }
-
- var preferredOutputDeviceUID: String?
- {
- get { defaults.string(forKey: Keys.preferredOutputDeviceUID) }
- set { defaults.set(newValue, forKey: Keys.preferredOutputDeviceUID) }
- }
-
- var visualizerNoiseThreshold: Double
- {
+ var preferredInputDeviceUID: String? {
+ get { defaults.string(forKey: Keys.preferredInputDeviceUID) }
+ set { defaults.set(newValue, forKey: Keys.preferredInputDeviceUID) }
+ }
+
+ var preferredOutputDeviceUID: String? {
+ get { defaults.string(forKey: Keys.preferredOutputDeviceUID) }
+ set { defaults.set(newValue, forKey: Keys.preferredOutputDeviceUID) }
+ }
+
+ var visualizerNoiseThreshold: Double {
get {
let value = defaults.double(forKey: Keys.visualizerNoiseThreshold)
return value == 0.0 ? 0.4 : value // Default to 0.4 if not set
@@ -302,8 +297,7 @@ final class SettingsStore: ObservableObject
// MARK: - Preferences Settings
- var launchAtStartup: Bool
- {
+ var launchAtStartup: Bool {
get { defaults.bool(forKey: Keys.launchAtStartup) }
set {
defaults.set(newValue, forKey: Keys.launchAtStartup)
@@ -327,8 +321,7 @@ final class SettingsStore: ObservableObject
#endif
}
- var showInDock: Bool
- {
+ var showInDock: Bool {
get {
let value = defaults.object(forKey: Keys.showInDock)
return value as? Bool ?? true // Default to true if not set
@@ -340,8 +333,7 @@ final class SettingsStore: ObservableObject
}
}
- var autoUpdateCheckEnabled: Bool
- {
+ var autoUpdateCheckEnabled: Bool {
get {
let value = defaults.object(forKey: Keys.autoUpdateCheckEnabled)
return value as? Bool ?? true // Default to enabled
@@ -351,8 +343,7 @@ final class SettingsStore: ObservableObject
}
}
- var lastUpdateCheckDate: Date?
- {
+ var lastUpdateCheckDate: Date? {
get {
return defaults.object(forKey: Keys.lastUpdateCheckDate) as? Date
}
@@ -365,12 +356,12 @@ final class SettingsStore: ObservableObject
func shouldCheckForUpdates() -> Bool {
guard autoUpdateCheckEnabled else { return false }
-
+
guard let lastCheck = lastUpdateCheckDate else {
// Never checked before, should check
return true
}
-
+
// Check if more than 24 hours have passed
let dayInSeconds: TimeInterval = 24 * 60 * 60
return Date().timeIntervalSince(lastCheck) >= dayInSeconds
@@ -384,38 +375,38 @@ final class SettingsStore: ObservableObject
get { defaults.bool(forKey: Keys.playgroundUsed) }
set { defaults.set(newValue, forKey: Keys.playgroundUsed) }
}
-
+
// MARK: - Command Mode Settings
-
- var commandModeSelectedModel: String?
- {
+
+ var commandModeSelectedModel: String? {
get { defaults.string(forKey: Keys.commandModeSelectedModel) }
set {
objectWillChange.send()
defaults.set(newValue, forKey: Keys.commandModeSelectedModel)
}
}
-
- var commandModeSelectedProviderID: String
- {
+
+ var commandModeSelectedProviderID: String {
get { defaults.string(forKey: Keys.commandModeSelectedProviderID) ?? "openai" }
set {
objectWillChange.send()
defaults.set(newValue, forKey: Keys.commandModeSelectedProviderID)
}
}
-
- var commandModeLinkedToGlobal: Bool
- {
- get { defaults.bool(forKey: Keys.commandModeLinkedToGlobal) } // Default to false (let user opt-in, or true if preferred)
+
+ var commandModeLinkedToGlobal: Bool {
+ get {
+ defaults
+ .bool(forKey: Keys.commandModeLinkedToGlobal)
+ } // Default to false (let user opt-in, or true if
+ // preferred)
set {
objectWillChange.send()
defaults.set(newValue, forKey: Keys.commandModeLinkedToGlobal)
}
}
-
- var commandModeShortcutEnabled: Bool
- {
+
+ var commandModeShortcutEnabled: Bool {
get {
let value = defaults.object(forKey: Keys.commandModeShortcutEnabled)
return value as? Bool ?? true
@@ -425,11 +416,9 @@ final class SettingsStore: ObservableObject
defaults.set(newValue, forKey: Keys.commandModeShortcutEnabled)
}
}
-
- var commandModeHotkeyShortcut: HotkeyShortcut
- {
- get
- {
+
+ var commandModeHotkeyShortcut: HotkeyShortcut {
+ get {
if let data = defaults.data(forKey: Keys.commandModeHotkeyShortcut),
let shortcut = try? JSONDecoder().decode(HotkeyShortcut.self, from: data)
{
@@ -438,18 +427,15 @@ final class SettingsStore: ObservableObject
// Default to Right Command key (keyCode: 54, no modifiers for the key itself)
return HotkeyShortcut(keyCode: 54, modifierFlags: [])
}
- set
- {
+ set {
objectWillChange.send()
- if let data = try? JSONEncoder().encode(newValue)
- {
+ if let data = try? JSONEncoder().encode(newValue) {
defaults.set(data, forKey: Keys.commandModeHotkeyShortcut)
}
}
}
-
- var commandModeConfirmBeforeExecute: Bool
- {
+
+ var commandModeConfirmBeforeExecute: Bool {
get {
// Default to true (safer - ask before running commands)
let value = defaults.object(forKey: Keys.commandModeConfirmBeforeExecute)
@@ -460,13 +446,11 @@ final class SettingsStore: ObservableObject
defaults.set(newValue, forKey: Keys.commandModeConfirmBeforeExecute)
}
}
-
+
// MARK: - Rewrite Mode Settings
-
- var rewriteModeHotkeyShortcut: HotkeyShortcut
- {
- get
- {
+
+ var rewriteModeHotkeyShortcut: HotkeyShortcut {
+ get {
if let data = defaults.data(forKey: Keys.rewriteModeHotkeyShortcut),
let shortcut = try? JSONDecoder().decode(HotkeyShortcut.self, from: data)
{
@@ -475,36 +459,31 @@ final class SettingsStore: ObservableObject
// Default to Option+R (keyCode: 15 is R, with Option modifier)
return HotkeyShortcut(keyCode: 15, modifierFlags: [.option])
}
- set
- {
+ set {
objectWillChange.send()
- if let data = try? JSONEncoder().encode(newValue)
- {
+ if let data = try? JSONEncoder().encode(newValue) {
defaults.set(data, forKey: Keys.rewriteModeHotkeyShortcut)
}
}
}
-
- var rewriteModeSelectedModel: String?
- {
+
+ var rewriteModeSelectedModel: String? {
get { defaults.string(forKey: Keys.rewriteModeSelectedModel) }
set {
objectWillChange.send()
defaults.set(newValue, forKey: Keys.rewriteModeSelectedModel)
}
}
-
- var rewriteModeSelectedProviderID: String
- {
+
+ var rewriteModeSelectedProviderID: String {
get { defaults.string(forKey: Keys.rewriteModeSelectedProviderID) ?? "openai" }
set {
objectWillChange.send()
defaults.set(newValue, forKey: Keys.rewriteModeSelectedProviderID)
}
}
-
- var rewriteModeLinkedToGlobal: Bool
- {
+
+ var rewriteModeLinkedToGlobal: Bool {
get {
// Default to true - sync with global settings by default
let value = defaults.object(forKey: Keys.rewriteModeLinkedToGlobal)
@@ -515,16 +494,16 @@ final class SettingsStore: ObservableObject
defaults.set(newValue, forKey: Keys.rewriteModeLinkedToGlobal)
}
}
-
+
// MARK: - Model Reasoning Configuration
-
+
/// Per-model reasoning configuration storage
/// Key format: "provider:model" (e.g., "openai:gpt-5.1", "groq:gpt-oss-120b")
- var modelReasoningConfigs: [String: ModelReasoningConfig]
- {
+ var modelReasoningConfigs: [String: ModelReasoningConfig] {
get {
guard let data = defaults.data(forKey: Keys.modelReasoningConfigs),
- let decoded = try? JSONDecoder().decode([String: ModelReasoningConfig].self, from: data) else {
+ let decoded = try? JSONDecoder().decode([String: ModelReasoningConfig].self, from: data)
+ else {
return [:]
}
return decoded
@@ -536,65 +515,64 @@ final class SettingsStore: ObservableObject
}
}
}
-
+
/// Get reasoning config for a specific model, with smart defaults for known models
func getReasoningConfig(forModel model: String, provider: String) -> ModelReasoningConfig? {
let key = "\(provider):\(model)"
-
+
// First check if user has a custom config
if let customConfig = modelReasoningConfigs[key] {
return customConfig.isEnabled ? customConfig : nil
}
-
+
// Apply smart defaults for known model patterns
let modelLower = model.lowercased()
-
+
// OpenAI gpt-5.x models
if modelLower.hasPrefix("gpt-5") || modelLower.contains("gpt-5.") {
return .openAIGPT5
}
-
+
// OpenAI o1/o3 reasoning models
if modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3") {
return .openAIO1
}
-
+
// Groq gpt-oss models
if modelLower.contains("gpt-oss") || modelLower.hasPrefix("openai/") {
return .groqGPTOSS
}
-
+
// DeepSeek reasoner models
- if modelLower.contains("deepseek") && modelLower.contains("reasoner") {
+ if modelLower.contains("deepseek"), modelLower.contains("reasoner") {
return .deepSeekReasoner
}
-
+
// No reasoning config needed for standard models (gpt-4.x, claude, llama, etc.)
return nil
}
-
+
/// Set reasoning config for a specific model
func setReasoningConfig(_ config: ModelReasoningConfig?, forModel model: String, provider: String) {
let key = "\(provider):\(model)"
var configs = modelReasoningConfigs
-
+
if let config = config {
configs[key] = config
} else {
configs.removeValue(forKey: key)
}
-
+
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
}
-
- var rewriteModeShortcutEnabled: Bool
- {
+
+ var rewriteModeShortcutEnabled: Bool {
get {
let value = defaults.object(forKey: Keys.rewriteModeShortcutEnabled)
return value as? Bool ?? true
@@ -604,19 +582,18 @@ final class SettingsStore: ObservableObject
defaults.set(newValue, forKey: Keys.rewriteModeShortcutEnabled)
}
}
-
+
// MARK: - Stats Settings
-
+
/// User's typing speed in words per minute (for time saved calculation)
- var userTypingWPM: Int
- {
+ var userTypingWPM: Int {
get {
let value = defaults.integer(forKey: Keys.userTypingWPM)
- return value > 0 ? value : 40 // Default to 40 WPM
+ 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
+ defaults.set(max(1, min(200, newValue)), forKey: Keys.userTypingWPM) // Clamp 1-200
}
}
@@ -627,7 +604,10 @@ final class SettingsStore: ObservableObject
do {
try keychain.storeAllKeys(trimmed)
} catch {
- DebugLogger.shared.error("Failed to persist provider API keys: \(error.localizedDescription)", source: "SettingsStore")
+ DebugLogger.shared.error(
+ "Failed to persist provider API keys: \(error.localizedDescription)",
+ source: "SettingsStore"
+ )
}
}
@@ -638,14 +618,16 @@ final class SettingsStore: ObservableObject
var didMutate = false
if let legacyDefaults = defaults.dictionary(forKey: Keys.providerAPIKeys) as? [String: String],
- legacyDefaults.isEmpty == false {
+ legacyDefaults.isEmpty == false
+ {
merged.merge(sanitizeAPIKeys(legacyDefaults)) { _, new in new }
didMutate = true
}
defaults.removeObject(forKey: Keys.providerAPIKeys)
if let legacyKeychain = try? keychain.legacyProviderEntries(),
- legacyKeychain.isEmpty == false {
+ legacyKeychain.isEmpty == false
+ {
merged.merge(sanitizeAPIKeys(legacyKeychain)) { _, new in new }
didMutate = true
try? keychain.removeLegacyEntries(providerIDs: Array(legacyKeychain.keys))
@@ -671,18 +653,25 @@ final class SettingsStore: ObservableObject
try keychain.storeKey(trimmed, for: keyID)
didModify = true
} catch {
- DebugLogger.shared.error("Failed to migrate API key for \(provider.name): \(error.localizedDescription)", source: "SettingsStore")
+ DebugLogger.shared
+ .error(
+ "Failed to migrate API key for \(provider.name): \(error.localizedDescription)",
+ source: "SettingsStore"
+ )
}
- decoded[index] = SavedProvider(id: provider.id,
- name: provider.name,
- baseURL: provider.baseURL,
- apiKey: "",
- models: provider.models)
+ decoded[index] = SavedProvider(
+ id: provider.id,
+ name: provider.name,
+ baseURL: provider.baseURL,
+ apiKey: "",
+ models: provider.models
+ )
}
if didModify,
- let encoded = try? JSONEncoder().encode(decoded) {
+ let encoded = try? JSONEncoder().encode(decoded)
+ {
defaults.set(encoded, forKey: Keys.savedProviders)
}
@@ -739,11 +728,14 @@ final class SettingsStore: ObservableObject
// For now, we'll try multiple approaches with fallbacks
- DebugLogger.shared.debug("Attempting to update dock visibility to: \(visible ? "visible" : "hidden")", source: "SettingsStore")
+ DebugLogger.shared.debug(
+ "Attempting to update dock visibility to: \(visible ? "visible" : "hidden")",
+ source: "SettingsStore"
+ )
// Method 1: Try the deprecated TransformProcessType (may not work on all systems)
let transformState = visible ? ProcessApplicationTransformState(kProcessTransformToForegroundApplication)
- : ProcessApplicationTransformState(kProcessTransformToUIElementApplication)
+ : ProcessApplicationTransformState(kProcessTransformToUIElementApplication)
var psn = ProcessSerialNumber(highLongOfPSN: 0, lowLongOfPSN: UInt32(kCurrentProcess))
let result = TransformProcessType(&psn, transformState)
@@ -751,15 +743,25 @@ final class SettingsStore: ObservableObject
if result == 0 {
DebugLogger.shared.info("✓ Dock visibility updated using TransformProcessType", source: "SettingsStore")
} else {
- DebugLogger.shared.warning("⚠️ TransformProcessType failed (error: \(result)). This is expected on some macOS versions.", source: "SettingsStore")
- DebugLogger.shared.debug(" The setting is saved and will be applied when possible.", source: "SettingsStore")
+ DebugLogger.shared
+ .warning(
+ "⚠️ TransformProcessType failed (error: \(result)). This is expected on some macOS versions.",
+ source: "SettingsStore"
+ )
+ DebugLogger.shared.debug(
+ " The setting is saved and will be applied when possible.",
+ source: "SettingsStore"
+ )
}
// Method 2: Try to notify the system of the change
// This may help with some system caches
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
NSApp.setActivationPolicy(visible ? .regular : .accessory)
- DebugLogger.shared.info("✓ Activation policy updated to: \(visible ? "regular" : "accessory")", source: "SettingsStore")
+ DebugLogger.shared.info(
+ "✓ Activation policy updated to: \(visible ? "regular" : "accessory")",
+ source: "SettingsStore"
+ )
}
// Store the intended state for reference
@@ -770,7 +772,25 @@ final class SettingsStore: ObservableObject
// MARK: - Filler Words
- static let defaultFillerWords = ["um", "uh", "er", "ah", "eh", "umm", "uhh", "err", "ahh", "ehh", "hmm", "hm", "mm", "mmm", "erm", "urm", "ugh"]
+ static let defaultFillerWords = [
+ "um",
+ "uh",
+ "er",
+ "ah",
+ "eh",
+ "umm",
+ "uhh",
+ "err",
+ "ahh",
+ "ehh",
+ "hmm",
+ "hm",
+ "mm",
+ "mmm",
+ "erm",
+ "urm",
+ "ugh",
+ ]
var fillerWords: [String] {
get {
@@ -792,27 +812,29 @@ final class SettingsStore: ObservableObject
defaults.set(newValue, forKey: Keys.removeFillerWordsEnabled)
}
}
-
+
// MARK: - Speech Model (Unified ASR Model Selection)
-
+
/// Unified speech recognition model selection.
/// Replaces the old TranscriptionProviderOption + WhisperModelSize dual-setting.
enum SpeechModel: String, CaseIterable, Identifiable, Codable {
// MARK: - FluidAudio Models (Apple Silicon Only)
+
case parakeetTDT = "parakeet-tdt"
-
+
// MARK: - Whisper Models (Universal)
+
case whisperTiny = "whisper-tiny"
case whisperBase = "whisper-base"
case whisperSmall = "whisper-small"
case whisperMedium = "whisper-medium"
case whisperLargeTurbo = "whisper-large-turbo"
case whisperLarge = "whisper-large"
-
+
var id: String { rawValue }
-
+
// MARK: - Display Properties
-
+
var displayName: String {
switch self {
case .parakeetTDT: return "Parakeet TDT"
@@ -824,7 +846,7 @@ final class SettingsStore: ObservableObject
case .whisperLarge: return "Whisper Large"
}
}
-
+
var languageSupport: String {
switch self {
case .parakeetTDT: return "25 Languages"
@@ -832,7 +854,7 @@ final class SettingsStore: ObservableObject
return "99 Languages"
}
}
-
+
var downloadSize: String {
switch self {
case .parakeetTDT: return "~500 MB"
@@ -844,21 +866,21 @@ final class SettingsStore: ObservableObject
case .whisperLarge: return "~2.9 GB"
}
}
-
+
var requiresAppleSilicon: Bool {
switch self {
case .parakeetTDT: return true
default: return false
}
}
-
+
var isWhisperModel: Bool {
switch self {
case .parakeetTDT: return false
default: return true
}
}
-
+
/// The ggml filename for Whisper models
var whisperModelFile: String? {
switch self {
@@ -871,7 +893,7 @@ final class SettingsStore: ObservableObject
default: return nil
}
}
-
+
/// The short model name for whisper.cpp internal usage
var whisperModelName: String? {
switch self {
@@ -884,32 +906,32 @@ final class SettingsStore: ObservableObject
default: return nil
}
}
-
+
// MARK: - Architecture Filtering
-
+
/// Returns models available for the current Mac's architecture
static var availableModels: [SpeechModel] {
allCases.filter { model in
!model.requiresAppleSilicon || CPUArchitecture.isAppleSilicon
}
}
-
+
/// Default model for the current architecture
static var defaultModel: SpeechModel {
CPUArchitecture.isAppleSilicon ? .parakeetTDT : .whisperBase
}
}
-
+
// MARK: - Transcription Provider (ASR)
-
+
/// Available transcription providers
enum TranscriptionProviderOption: String, CaseIterable, Identifiable {
- case auto = "auto"
- case fluidAudio = "fluidAudio"
- case whisper = "whisper"
-
+ case auto
+ case fluidAudio
+ case whisper
+
var id: String { rawValue }
-
+
var displayName: String {
switch self {
case .auto: return "Automatic (Recommended)"
@@ -917,7 +939,7 @@ final class SettingsStore: ObservableObject
case .whisper: return "Whisper (Intel/Universal)"
}
}
-
+
var description: String {
switch self {
case .auto: return "Uses FluidAudio on Apple Silicon, Whisper on Intel"
@@ -926,7 +948,7 @@ final class SettingsStore: ObservableObject
}
}
}
-
+
/// Available Whisper model sizes
enum WhisperModelSize: String, CaseIterable, Identifiable {
case tiny = "ggml-tiny.bin"
@@ -934,9 +956,9 @@ final class SettingsStore: ObservableObject
case small = "ggml-small.bin"
case medium = "ggml-medium.bin"
case large = "ggml-large-v3.bin"
-
+
var id: String { rawValue }
-
+
var displayName: String {
switch self {
case .tiny: return "Tiny (~75 MB)"
@@ -946,7 +968,7 @@ final class SettingsStore: ObservableObject
case .large: return "Large (~2.9 GB)"
}
}
-
+
var description: String {
switch self {
case .tiny: return "Fastest, lower accuracy"
@@ -957,12 +979,13 @@ final class SettingsStore: ObservableObject
}
}
}
-
+
/// Selected transcription provider - defaults to "auto" which picks based on architecture
var selectedTranscriptionProvider: TranscriptionProviderOption {
get {
guard let rawValue = defaults.string(forKey: Keys.selectedTranscriptionProvider),
- let option = TranscriptionProviderOption(rawValue: rawValue) else {
+ let option = TranscriptionProviderOption(rawValue: rawValue)
+ else {
return .auto
}
return option
@@ -972,12 +995,13 @@ final class SettingsStore: ObservableObject
defaults.set(newValue.rawValue, forKey: Keys.selectedTranscriptionProvider)
}
}
-
+
/// Selected Whisper model size - defaults to "base"
var whisperModelSize: WhisperModelSize {
get {
guard let rawValue = defaults.string(forKey: Keys.whisperModelSize),
- let size = WhisperModelSize(rawValue: rawValue) else {
+ let size = WhisperModelSize(rawValue: rawValue)
+ else {
return .base
}
return size
@@ -987,23 +1011,24 @@ final class SettingsStore: ObservableObject
defaults.set(newValue.rawValue, forKey: Keys.whisperModelSize)
}
}
-
+
// MARK: - Unified Speech Model Selection
-
+
/// The selected speech recognition model.
/// This unified setting replaces the old TranscriptionProviderOption + WhisperModelSize combination.
var selectedSpeechModel: SpeechModel {
get {
// Check if already using new system
if let rawValue = defaults.string(forKey: Keys.selectedSpeechModel),
- let model = SpeechModel(rawValue: rawValue) {
+ let model = SpeechModel(rawValue: rawValue)
+ {
// Validate model is available on this architecture
if model.requiresAppleSilicon && !CPUArchitecture.isAppleSilicon {
return .whisperBase
}
return model
}
-
+
// Migration: Convert old settings to new SpeechModel
return migrateToSpeechModel()
}
@@ -1012,14 +1037,14 @@ final class SettingsStore: ObservableObject
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 newModel: SpeechModel
-
+
switch oldProvider {
case "whisper":
// Map old whisper size to new model
@@ -1036,11 +1061,15 @@ final class SettingsStore: ObservableObject
default: // "auto"
newModel = SpeechModel.defaultModel
}
-
+
// Persist the migrated value
defaults.set(newModel.rawValue, forKey: Keys.selectedSpeechModel)
- DebugLogger.shared.info("Migrated speech model settings: \(oldProvider)/\(oldWhisperSize) -> \(newModel.rawValue)", source: "SettingsStore")
-
+ DebugLogger.shared
+ .info(
+ "Migrated speech model settings: \(oldProvider)/\(oldWhisperSize) -> \(newModel.rawValue)",
+ source: "SettingsStore"
+ )
+
return newModel
}
}
diff --git a/Sources/Fluid/Persistence/TranscriptionHistoryStore.swift b/Sources/Fluid/Persistence/TranscriptionHistoryStore.swift
index 55d32682..a21accc3 100644
--- a/Sources/Fluid/Persistence/TranscriptionHistoryStore.swift
+++ b/Sources/Fluid/Persistence/TranscriptionHistoryStore.swift
@@ -1,12 +1,5 @@
-//
-// TranscriptionHistoryStore.swift
-// Fluid
-//
-// Persistence manager for Transcription Mode history
-//
-
-import Foundation
import Combine
+import Foundation
// MARK: - Transcription History Entry Model
@@ -19,7 +12,7 @@ struct TranscriptionHistoryEntry: Codable, Identifiable, Equatable {
let windowTitle: String
let characterCount: Int
let wasAIProcessed: Bool
-
+
init(
id: UUID = UUID(),
timestamp: Date = Date(),
@@ -34,10 +27,10 @@ struct TranscriptionHistoryEntry: Codable, Identifiable, Equatable {
self.processedText = processedText
self.appName = appName
self.windowTitle = windowTitle
- self.characterCount = processedText.count
- self.wasAIProcessed = rawText != processedText
+ characterCount = processedText.count
+ wasAIProcessed = rawText != processedText
}
-
+
/// Preview text for list display (first 80 chars)
var previewText: String {
let text = processedText.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -46,14 +39,14 @@ struct TranscriptionHistoryEntry: Codable, Identifiable, Equatable {
}
return text
}
-
+
/// Relative time string for display
var relativeTimeString: String {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .abbreviated
return formatter.localizedString(for: timestamp, relativeTo: Date())
}
-
+
/// Full formatted date string
var fullDateString: String {
let formatter = DateFormatter()
@@ -68,29 +61,29 @@ struct TranscriptionHistoryEntry: Codable, Identifiable, Equatable {
@MainActor
final class TranscriptionHistoryStore: ObservableObject {
static let shared = TranscriptionHistoryStore()
-
+
private let defaults = UserDefaults.standard
private let maxEntries = 1000
-
+
private enum Keys {
static let transcriptionHistory = "TranscriptionHistoryEntries"
}
-
+
@Published private(set) var entries: [TranscriptionHistoryEntry] = []
@Published var selectedEntryID: UUID?
-
+
private init() {
loadEntries()
}
-
+
// MARK: - Public Methods
-
+
/// Get selected entry
var selectedEntry: TranscriptionHistoryEntry? {
guard let id = selectedEntryID else { return nil }
return entries.first(where: { $0.id == id })
}
-
+
/// Add a new transcription entry
func addEntry(
rawText: String,
@@ -100,104 +93,108 @@ final class TranscriptionHistoryStore: ObservableObject {
) {
// Skip empty transcriptions
guard !processedText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
-
+
let entry = TranscriptionHistoryEntry(
rawText: rawText,
processedText: processedText,
appName: appName,
windowTitle: windowTitle
)
-
+
// Insert at beginning (newest first)
entries.insert(entry, at: 0)
-
+
// Trim old entries if over limit
trimOldEntries()
saveEntries()
-
- DebugLogger.shared.debug("Added transcription to history (total: \(entries.count))", source: "TranscriptionHistoryStore")
+
+ DebugLogger.shared.debug(
+ "Added transcription to history (total: \(entries.count))",
+ source: "TranscriptionHistoryStore"
+ )
}
-
+
/// Delete a specific entry
func deleteEntry(id: UUID) {
entries.removeAll { $0.id == id }
-
+
// Clear selection if deleted
if selectedEntryID == id {
selectedEntryID = entries.first?.id
}
-
+
saveEntries()
}
-
+
/// Delete multiple entries
func deleteEntries(ids: Set<UUID>) {
entries.removeAll { ids.contains($0.id) }
-
+
if let selected = selectedEntryID, ids.contains(selected) {
selectedEntryID = entries.first?.id
}
-
+
saveEntries()
}
-
+
/// Clear all history
func clearAllHistory() {
entries.removeAll()
selectedEntryID = nil
saveEntries()
-
+
DebugLogger.shared.info("Cleared all transcription history", source: "TranscriptionHistoryStore")
}
-
+
/// Search entries by text content
func search(query: String) -> [TranscriptionHistoryEntry] {
guard !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
return entries
}
-
+
let lowercased = query.lowercased()
return entries.filter { entry in
entry.rawText.lowercased().contains(lowercased) ||
- entry.processedText.lowercased().contains(lowercased) ||
- entry.appName.lowercased().contains(lowercased) ||
- entry.windowTitle.lowercased().contains(lowercased)
+ entry.processedText.lowercased().contains(lowercased) ||
+ entry.appName.lowercased().contains(lowercased) ||
+ entry.windowTitle.lowercased().contains(lowercased)
}
}
-
+
/// Get entries filtered by date range
func entriesInRange(from startDate: Date, to endDate: Date) -> [TranscriptionHistoryEntry] {
entries.filter { $0.timestamp >= startDate && $0.timestamp <= endDate }
}
-
+
/// Get total character count across all entries
var totalCharacterCount: Int {
entries.reduce(0) { $0 + $1.characterCount }
}
-
+
/// Get count of AI-processed entries
var aiProcessedCount: Int {
entries.filter { $0.wasAIProcessed }.count
}
-
+
// MARK: - Private Methods
-
+
private func loadEntries() {
guard let data = defaults.data(forKey: Keys.transcriptionHistory),
- let decoded = try? JSONDecoder().decode([TranscriptionHistoryEntry].self, from: data) else {
+ let decoded = try? JSONDecoder().decode([TranscriptionHistoryEntry].self, from: data)
+ else {
entries = []
return
}
entries = decoded
}
-
+
private func saveEntries() {
if let encoded = try? JSONEncoder().encode(entries) {
defaults.set(encoded, forKey: Keys.transcriptionHistory)
}
objectWillChange.send()
}
-
+
private func trimOldEntries() {
if entries.count > maxEntries {
// Keep most recent entries
@@ -209,59 +206,58 @@ final class TranscriptionHistoryStore: ObservableObject {
// MARK: - Stats Computation Extension
extension TranscriptionHistoryStore {
-
// MARK: - Word Counting
-
+
/// Count words in a string (handles multiple spaces, newlines)
private func wordCount(in text: String) -> Int {
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return 0 }
-
+
let words = trimmed.components(separatedBy: .whitespacesAndNewlines)
.filter { !$0.isEmpty }
return words.count
}
-
+
/// Total words across all transcriptions
var totalWords: Int {
- entries.reduce(0) { $0 + wordCount(in: $1.processedText) }
+ 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
.filter { calendar.isDate($0.timestamp, inSameDayAs: today) }
- .reduce(0) { $0 + wordCount(in: $1.processedText) }
+ .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
}
-
+
// MARK: - Time Saved Calculation
-
+
/// Calculate time saved in minutes
/// - Parameters:
/// - typingWPM: User's typing speed (default 40)
/// - speakingWPM: Average speaking speed (default 150)
func timeSavedMinutes(typingWPM: Int = 40, speakingWPM: Int = 150) -> Double {
guard typingWPM > 0 && speakingWPM > 0 else { return 0 }
-
+
let words = Double(totalWords)
- let typingTime = words / Double(typingWPM) // minutes to type
- let speakingTime = words / Double(speakingWPM) // minutes to speak
-
+ let typingTime = words / Double(typingWPM) // minutes to type
+ let speakingTime = words / Double(speakingWPM) // minutes to speak
+
return max(0, typingTime - speakingTime)
}
-
+
/// Formatted time saved string (e.g., "2h 45m" or "45m")
func formattedTimeSaved(typingWPM: Int = 40) -> String {
let minutes = timeSavedMinutes(typingWPM: typingWPM)
-
+
if minutes < 1 {
return "< 1m"
} else if minutes < 60 {
@@ -275,44 +271,45 @@ extension TranscriptionHistoryStore {
return "\(hours)h \(mins)m"
}
}
-
+
// MARK: - Streak Calculation
-
+
/// Get unique days with activity (sorted newest first)
private var activeDays: [Date] {
let calendar = Calendar.current
var uniqueDays = Set<Date>()
-
+
for entry in entries {
let day = calendar.startOfDay(for: entry.timestamp)
uniqueDays.insert(day)
}
-
- return uniqueDays.sorted(by: >) // newest first
+
+ return uniqueDays.sorted(by: >) // newest first
}
-
+
/// Current streak (consecutive days including today or yesterday)
var currentStreak: Int {
let calendar = Calendar.current
let days = activeDays
-
+
guard !days.isEmpty else { return 0 }
-
+
let today = calendar.startOfDay(for: Date())
let yesterday = calendar.date(byAdding: .day, value: -1, to: today)!
-
+
// Must have activity today or yesterday to have an active streak
guard let firstActiveDay = days.first,
- firstActiveDay == today || firstActiveDay == yesterday else {
+ firstActiveDay == today || firstActiveDay == yesterday
+ else {
return 0
}
-
+
var streak = 1
var previousDay = firstActiveDay
-
+
for day in days.dropFirst() {
let expectedPrevious = calendar.date(byAdding: .day, value: -1, to: previousDay)!
-
+
if day == expectedPrevious {
streak += 1
previousDay = day
@@ -320,24 +317,24 @@ extension TranscriptionHistoryStore {
break
}
}
-
+
return streak
}
-
+
/// Best streak ever achieved
var bestStreak: Int {
let calendar = Calendar.current
- let days = activeDays.sorted() // oldest first for this calculation
-
+ let days = activeDays.sorted() // oldest first for this calculation
+
guard !days.isEmpty else { return 0 }
-
+
var maxStreak = 1
var currentStreakCount = 1
var previousDay = days[0]
-
+
for day in days.dropFirst() {
let expectedNext = calendar.date(byAdding: .day, value: 1, to: previousDay)!
-
+
if day == expectedNext {
currentStreakCount += 1
maxStreak = max(maxStreak, currentStreakCount)
@@ -346,181 +343,182 @@ extension TranscriptionHistoryStore {
}
previousDay = day
}
-
+
return maxStreak
}
-
+
// MARK: - Daily Activity Data (for charts)
-
+
/// Daily word counts for the last N days
func dailyWordCounts(days: Int) -> [(date: Date, words: Int)] {
let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
-
+
var result: [(date: Date, words: Int)] = []
-
+
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 words = dayEntries.reduce(0) { $0 + wordCount(in: $1.processedText) }
-
+ let words = dayEntries.reduce(0) { $0 + self.wordCount(in: $1.processedText) }
+
result.append((date: date, words: words))
}
-
- return result.reversed() // oldest to newest for chart display
+
+ return result.reversed() // oldest to newest for chart display
}
-
+
/// Daily transcription counts for the last N days
func dailyTranscriptionCounts(days: Int) -> [(date: Date, count: Int)] {
let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
-
+
var result: [(date: Date, count: Int)] = []
-
+
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
result.append((date: date, count: count))
}
-
+
return result.reversed()
}
-
+
// MARK: - Top Apps
-
+
/// Most used apps (sorted by usage count)
var topApps: [(app: String, count: Int)] {
var appCounts: [String: Int] = [:]
-
+
for entry in entries {
let app = entry.appName.isEmpty ? "Unknown" : entry.appName
appCounts[app, default: 0] += 1
}
-
+
return appCounts
.map { (app: $0.key, count: $0.value) }
.sorted { $0.count > $1.count }
}
-
+
/// Top N apps formatted for display
func topAppsFormatted(limit: Int = 5) -> [String] {
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
}
-
+
// MARK: - Peak Usage Hours
-
+
/// Hour of day with most transcriptions (0-23)
var peakHour: Int? {
guard !entries.isEmpty else { return nil }
-
+
let calendar = Calendar.current
var hourCounts: [Int: Int] = [:]
-
+
for entry in entries {
let hour = calendar.component(.hour, from: entry.timestamp)
hourCounts[hour, default: 0] += 1
}
-
+
return hourCounts.max(by: { $0.value < $1.value })?.key
}
-
+
/// Formatted peak hour range (e.g., "2-3 PM")
var peakHourFormatted: String {
guard let hour = peakHour else { return "N/A" }
-
+
let formatter = DateFormatter()
formatter.dateFormat = "h a"
-
+
let calendar = Calendar.current
var components = DateComponents()
components.hour = hour
-
+
guard let startDate = calendar.date(from: components),
- let endDate = calendar.date(byAdding: .hour, value: 1, to: startDate) else {
+ let endDate = calendar.date(byAdding: .hour, value: 1, to: startDate)
+ else {
return "N/A"
}
-
+
let startStr = formatter.string(from: startDate)
let endStr = formatter.string(from: endDate)
-
+
return "\(startStr)-\(endStr)"
}
-
+
// MARK: - Personal Records
-
+
/// Longest single transcription (word count)
var longestTranscriptionWords: Int {
- entries.map { wordCount(in: $0.processedText) }.max() ?? 0
+ entries.map { self.wordCount(in: $0.processedText) }.max() ?? 0
}
-
+
/// Most words in a single day
var mostWordsInDay: Int {
let calendar = Calendar.current
var dayTotals: [Date: Int] = [:]
-
+
for entry in entries {
let day = calendar.startOfDay(for: entry.timestamp)
dayTotals[day, default: 0] += wordCount(in: entry.processedText)
}
-
+
return dayTotals.values.max() ?? 0
}
-
+
/// Most transcriptions in a single day
var mostTranscriptionsInDay: Int {
let calendar = Calendar.current
var dayCounts: [Date: Int] = [:]
-
+
for entry in entries {
let day = calendar.startOfDay(for: entry.timestamp)
dayCounts[day, default: 0] += 1
}
-
+
return dayCounts.values.max() ?? 0
}
-
+
// MARK: - Milestones
-
+
/// Word count milestones and whether they've been achieved
var wordMilestones: [(target: Int, achieved: Bool, label: String)] {
let milestones = [
- (1_000, "1K"),
+ (1000, "1K"),
(10_000, "10K"),
(50_000, "50K"),
(100_000, "100K"),
(500_000, "500K"),
- (1_000_000, "1M")
+ (1_000_000, "1M"),
]
-
+
let total = totalWords
return milestones.map { (target: $0.0, achieved: total >= $0.0, label: $0.1) }
}
-
+
/// Transcription count milestones
var transcriptionMilestones: [(target: Int, achieved: Bool, label: String)] {
let milestones = [
(50, "50"),
(100, "100"),
(500, "500"),
- (1_000, "1K"),
- (5_000, "5K"),
- (10_000, "10K")
+ (1000, "1K"),
+ (5000, "5K"),
+ (10_000, "10K"),
]
-
+
let total = entries.count
return milestones.map { (target: $0.0, achieved: total >= $0.0, label: $0.1) }
}
-
+
/// Streak milestones
var streakMilestones: [(target: Int, achieved: Bool, label: String)] {
let milestones = [
@@ -529,23 +527,22 @@ extension TranscriptionHistoryStore {
(30, "30 days"),
(60, "60 days"),
(100, "100 days"),
- (365, "1 year")
+ (365, "1 year"),
]
-
+
let best = 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
+ transcriptionMilestones.filter { $0.achieved }.count +
+ streakMilestones.filter { $0.achieved }.count
}
-
+
/// Total possible milestones
var totalMilestonesPossible: Int {
wordMilestones.count + transcriptionMilestones.count + streakMilestones.count
}
}
-
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 5d782120..58e5572c 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -1,12 +1,12 @@
-import Foundation
+import Accelerate
import AVFoundation
import Combine
-import Accelerate
+import Foundation
#if arch(arm64)
import FluidAudio
#endif
-import CoreAudio
import AppKit
+import CoreAudio
/// Serializes all CoreML transcription operations to prevent concurrent access issues.
/// The actor ensures only one transcription runs at a time, preventing CoreML race conditions.
@@ -48,8 +48,8 @@ private actor TranscriptionExecutor {
///
/// ## Language Support
/// The service automatically detects and transcribes 25 European languages with Parakeet TDT v3:
-/// Bulgarian, Croatian, Czech, Danish, Dutch, English, Estonian, Finnish, French, German,
-/// Greek, Hungarian, Italian, Latvian, Lithuanian, Maltese, Polish, Portuguese, Romanian,
+/// Bulgarian, Croatian, Czech, Danish, Dutch, English, Estonian, Finnish, French, German,
+/// Greek, Hungarian, Italian, Latvian, Lithuanian, Maltese, Polish, Portuguese, Romanian,
/// Slovak, Slovenian, Spanish, Swedish, Russian, and Ukrainian.
///
/// No manual language selection is required - the model automatically detects the spoken language.
@@ -61,22 +61,22 @@ private actor TranscriptionExecutor {
/// The service automatically downloads and manages ASR models from Hugging Face.
/// Models are cached locally to avoid repeated downloads.
@MainActor
-final class ASRService: ObservableObject
-{
+final class ASRService: ObservableObject {
@Published var isRunning: Bool = false
@Published var finalText: String = ""
@Published var partialTranscription: String = ""
@Published var micStatus: AVAuthorizationStatus = .notDetermined
@Published var isAsrReady: Bool = false
@Published var isDownloadingModel: Bool = false
- @Published var isLoadingModel: Bool = false // True when loading cached model into memory (not downloading)
+ @Published var isLoadingModel: Bool = false // True when loading cached model into memory (not downloading)
@Published var modelsExistOnDisk: Bool = false
-
+
// MARK: - Error Handling
+
@Published var errorTitle: String = "Error"
@Published var errorMessage: String = ""
@Published var showError: Bool = false
-
+
/// Returns a user-friendly status message for model loading state
var modelStatusMessage: String {
if isAsrReady { return "Model ready" }
@@ -85,30 +85,30 @@ final class ASRService: ObservableObject
if modelsExistOnDisk { return "Model cached, needs loading" }
return "Model not downloaded"
}
-
+
// MARK: - Transcription Provider (Settable)
-
+
/// Cached providers to avoid re-instantiation
private var fluidAudioProvider: FluidAudioProvider?
private var whisperProvider: WhisperProvider?
-
+
/// Prevent concurrent provider.prepare() calls (download/load) from overlapping.
/// Subsequent callers await the in-flight task.
private var ensureReadyTask: Task<Void, Error>?
private var ensureReadyProviderKey: String?
-
+
/// The transcription provider, selected based on the unified SpeechModel setting.
/// Uses the new SettingsStore.selectedSpeechModel instead of old TranscriptionProviderOption.
private var transcriptionProvider: TranscriptionProvider {
let model = SettingsStore.shared.selectedSpeechModel
-
+
if model.isWhisperModel {
return getWhisperProvider()
} else {
return getFluidAudioProvider()
}
}
-
+
private func getFluidAudioProvider() -> FluidAudioProvider {
if let existing = fluidAudioProvider {
return existing
@@ -118,7 +118,7 @@ final class ASRService: ObservableObject
DebugLogger.shared.info("ASRService: Created FluidAudio provider", source: "ASRService")
return provider
}
-
+
private func getWhisperProvider() -> WhisperProvider {
if let existing = whisperProvider {
return existing
@@ -128,12 +128,12 @@ final class ASRService: ObservableObject
DebugLogger.shared.info("ASRService: Created Whisper provider", source: "ASRService")
return provider
}
-
+
/// Returns the user-friendly name of the currently selected speech model
var activeProviderName: String {
SettingsStore.shared.selectedSpeechModel.displayName
}
-
+
/// Call this when the transcription provider setting changes to reset state
func resetTranscriptionProvider() {
isAsrReady = false
@@ -142,13 +142,12 @@ final class ASRService: ObservableObject
ensureReadyTask = nil
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()
}
-
// CRITICAL FIX (launch-time crash mitigation):
// Combine's default ObservableObject.objectWillChange implementation uses Swift reflection to walk *stored*
// properties. If we store an AVFoundation ObjC class type (like AVAudioEngine) directly, the reflection
@@ -169,6 +168,7 @@ final class ASRService: ObservableObject
engineStorage = created
return created
}
+
private var inputFormat: AVAudioFormat?
private var micPermissionGranted = false
@@ -190,7 +190,8 @@ final class ASRService: ObservableObject
// Streaming transcription state (no VAD)
private var streamingTask: Task<Void, Never>?
private var lastProcessedSampleCount: Int = 0
- private let chunkDurationSeconds: Double = 0.6 // Fast interval - TranscriptionExecutor actor handles CoreML serialization
+ private let chunkDurationSeconds: Double =
+ 0.6 // Fast interval - TranscriptionExecutor actor handles CoreML serialization
private var isProcessingChunk: Bool = false
private var skipNextChunk: Bool = false
private var previousFullTranscription: String = ""
@@ -199,15 +200,14 @@ final class ASRService: ObservableObject
private var audioLevelSubject = PassthroughSubject<CGFloat, Never>()
var audioLevelPublisher: AnyPublisher<CGFloat, Never> { audioLevelSubject.eraseToAnyPublisher() }
private var lastAudioLevelSentAt: TimeInterval = 0
-
+
// Audio smoothing properties - lighter smoothing for real-time response
private var audioLevelHistory: [CGFloat] = []
private var smoothedLevel: CGFloat = 0.0
private let historySize = 2 // Reduced for faster response
private let silenceThreshold: CGFloat = 0.04 // Reasonable default
private let noiseGateThreshold: CGFloat = 0.06
- init()
- {
+ init() {
// CRITICAL FIX: Do NOT call any framework-triggering APIs here!
// This includes:
// - AVCaptureDevice.authorizationStatus (triggers AVFCapture/CoreAudio)
@@ -221,19 +221,19 @@ final class ASRService: ObservableObject
// - micPermissionGranted = false
// - modelsExistOnDisk = false
}
-
+
/// Call this AFTER the app has finished launching to complete ASR initialization.
/// This must be called from onAppear or later, never during init.
func initialize() {
// Check microphone permission (deferred from init to avoid AVFCapture race condition)
- self.micStatus = AVCaptureDevice.authorizationStatus(for: .audio)
- self.micPermissionGranted = (self.micStatus == .authorized)
-
+ micStatus = AVCaptureDevice.authorizationStatus(for: .audio)
+ micPermissionGranted = (micStatus == .authorized)
+
registerDefaultDeviceChangeListener()
-
+
// Check if models exist on disk (deferred from init to avoid FluidAudio/CoreML race)
checkIfModelsExist()
-
+
// Auto-load models if they exist on disk to avoid "Downloaded but not loaded" state
if modelsExistOnDisk {
DebugLogger.shared.info("Models found on disk, auto-loading...", source: "ASRService")
@@ -248,18 +248,15 @@ 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")
}
-
- func requestMicAccess()
- {
- AVCaptureDevice.requestAccess(for: .audio)
- { [weak self] granted in
+ func requestMicAccess() {
+ AVCaptureDevice.requestAccess(for: .audio) { [weak self] granted in
guard let self = self else { return }
Task { @MainActor in
self.micPermissionGranted = granted
@@ -268,10 +265,8 @@ final class ASRService: ObservableObject
}
}
- func openSystemSettingsForMic()
- {
- if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone")
- {
+ func openSystemSettingsForMic() {
+ if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone") {
NSWorkspace.shared.open(url)
}
}
@@ -296,8 +291,7 @@ final class ASRService: ObservableObject
/// ## Errors
/// If audio session configuration fails, the method will silently fail
/// and `isRunning` will remain `false`. Check the debug logs for details.
- func start()
- {
+ func start() {
guard micStatus == .authorized else { return }
guard isRunning == false else { return }
@@ -310,16 +304,13 @@ final class ASRService: ObservableObject
skipNextChunk = false
isRecordingWholeSession = true
- do
- {
+ do {
try configureSession()
try startEngine()
setupEngineTap()
isRunning = true
startStreamingTranscription()
- }
- catch
- {
+ } catch {
// TODO: Add proper error handling and user notification
// For now, errors are logged but the UI doesn't show them
DebugLogger.shared.error("Failed to start ASR session: \(error)", source: "ASRService")
@@ -353,18 +344,17 @@ final class ASRService: ObservableObject
/// - ASR models are not available
/// - Transcription process fails
/// Check debug logs for detailed error information.
- func stop() async -> String
- {
+ func stop() async -> String {
guard 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
+ engine.reset() // Reset engine state to fully release Bluetooth mic
isRunning = false
-
+
isProcessingChunk = false
skipNextChunk = false
previousFullTranscription.removeAll()
@@ -374,55 +364,58 @@ final class ASRService: ObservableObject
audioBuffer.clear()
isRecordingWholeSession = false
- do
- {
- try await self.ensureAsrReady()
- guard transcriptionProvider.isReady else {
+ do {
+ try await ensureAsrReady()
+ guard transcriptionProvider.isReady else {
DebugLogger.shared.error("Transcription provider is not ready", source: "ASRService")
- return ""
+ return ""
}
-
- DebugLogger.shared.debug("Starting transcription with \(pcm.count) samples (\(Float(pcm.count)/16000.0) seconds)", source: "ASRService")
- DebugLogger.shared.debug("stop(): starting full transcription (samples: \(pcm.count)) using \(transcriptionProvider.name)", source: "ASRService")
+
+ DebugLogger.shared
+ .debug(
+ "Starting transcription with \(pcm.count) samples (\(Float(pcm.count) / 16_000.0) seconds)",
+ source: "ASRService"
+ )
+ DebugLogger.shared
+ .debug(
+ "stop(): starting full transcription (samples: \(pcm.count)) using \(transcriptionProvider.name)",
+ source: "ASRService"
+ )
let result = try await transcriptionExecutor.run { [provider = self.transcriptionProvider] in
try await provider.transcribe(pcm)
}
DebugLogger.shared.debug("stop(): full transcription finished", source: "ASRService")
- DebugLogger.shared.debug("Transcription completed: '\(result.text)' (confidence: \(result.confidence))", source: "ASRService")
+ DebugLogger.shared.debug(
+ "Transcription completed: '\(result.text)' (confidence: \(result.confidence))",
+ source: "ASRService"
+ )
// Do not update self.finalText here to avoid instant binding insert in playground
let cleanedText = ASRService.removeFillerWords(result.text)
DebugLogger.shared.debug("After filler removal: '\(cleanedText)'", source: "ASRService")
return cleanedText
- }
- catch
- {
+ } catch {
DebugLogger.shared.error("ASR transcription failed: \(error)", source: "ASRService")
DebugLogger.shared.error("Error details: \(error.localizedDescription)", source: "ASRService")
let nsError = error as NSError
DebugLogger.shared.error("Error domain: \(nsError.domain), code: \(nsError.code)", source: "ASRService")
DebugLogger.shared.error("Error userInfo: \(nsError.userInfo)", source: "ASRService")
-
+
// Note: We intentionally do NOT show an error popup here.
// Common errors like "audio too short" are expected during normal use
// (e.g., accidental hotkey press) and would disrupt the user's workflow.
// Errors are logged for debugging purposes.
-
+
return ""
}
}
-
-
-
-
- func stopWithoutTranscription()
- {
+ func stopWithoutTranscription() {
guard isRunning else { return }
-
+
stopStreamingTimer()
removeEngineTap()
engine.stop()
- engine.reset() // Reset engine state to fully release Bluetooth mic
+ engine.reset() // Reset engine state to fully release Bluetooth mic
isRunning = false
audioBuffer.clear()
isRecordingWholeSession = false
@@ -433,29 +426,22 @@ final class ASRService: ObservableObject
skipNextChunk = false
}
- private func configureSession() throws
- {
- if engine.isRunning
- {
+ private func configureSession() throws {
+ if engine.isRunning {
engine.stop()
}
engine.reset()
_ = engine.inputNode
}
- private func startEngine() throws
- {
+ private func startEngine() throws {
engine.reset()
var attempts = 0
- while attempts < 3
- {
- do
- {
+ while attempts < 3 {
+ do {
try engine.start()
return
- }
- catch
- {
+ } catch {
attempts += 1
Thread.sleep(forTimeInterval: 0.1)
engine.reset()
@@ -464,124 +450,112 @@ final class ASRService: ObservableObject
throw NSError(domain: "ASRService", code: -1)
}
- private func removeEngineTap()
- {
+ private func removeEngineTap() {
engine.inputNode.removeTap(onBus: 0)
}
- private func setupEngineTap()
- {
+ private func setupEngineTap() {
let input = engine.inputNode
let inFormat = input.inputFormat(forBus: 0)
inputFormat = inFormat
- input.installTap(onBus: 0, bufferSize: 4096, format: inFormat)
- { [weak self] (buffer, _) in
+ input.installTap(onBus: 0, bufferSize: 4096, format: inFormat) { [weak self] buffer, _ in
self?.processInputBuffer(buffer: buffer)
}
}
- private func handleDefaultInputChanged()
- {
+ private func handleDefaultInputChanged() {
// Restart engine to bind to the new default input and resume level publishing
- if isRunning
- {
+ if isRunning {
removeEngineTap()
engine.stop()
- do
- {
+ do {
try configureSession()
try startEngine()
setupEngineTap()
- }
- catch
- {
- }
+ } catch {}
}
// Nudge visualizer
DispatchQueue.main.async { self.audioLevelSubject.send(0.0) }
}
private var defaultInputListenerInstalled = false
- private func registerDefaultDeviceChangeListener()
- {
+ private func registerDefaultDeviceChangeListener() {
guard defaultInputListenerInstalled == false else { return }
var address = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDefaultInputDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
- let status = AudioObjectAddPropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &address, DispatchQueue.main)
- { [weak self] _, _ in
+ let status = AudioObjectAddPropertyListenerBlock(
+ AudioObjectID(kAudioObjectSystemObject),
+ &address,
+ DispatchQueue.main
+ ) { [weak self] _, _ in
self?.handleDefaultInputChanged()
}
if status == noErr { defaultInputListenerInstalled = true }
}
- private func processInputBuffer(buffer: AVAudioPCMBuffer)
- {
- guard isRecordingWholeSession else
- {
+ private func processInputBuffer(buffer: AVAudioPCMBuffer) {
+ guard isRecordingWholeSession else {
DispatchQueue.main.async { self.audioLevelSubject.send(0.0) }
return
}
- let mono16k = self.toMono16k(floatBuffer: buffer)
- if mono16k.isEmpty == false
- {
+ let mono16k = toMono16k(floatBuffer: buffer)
+ if mono16k.isEmpty == false {
// Thread-safe append
audioBuffer.append(mono16k)
// Publish audio level for visualization
- let audioLevel = self.calculateAudioLevel(mono16k)
+ let audioLevel = calculateAudioLevel(mono16k)
DispatchQueue.main.async { self.audioLevelSubject.send(audioLevel) }
}
}
- private func calculateAudioLevel(_ samples: [Float]) -> CGFloat
- {
+ private func calculateAudioLevel(_ samples: [Float]) -> CGFloat {
guard samples.isEmpty == false else { return 0.0 }
-
+
// Calculate RMS
var sum: Float = 0.0
vDSP_svesq(samples, 1, &sum, vDSP_Length(samples.count))
let rms = sqrt(sum / Float(samples.count))
-
+
// Apply noise gate at RMS level
if rms < 0.002 {
return 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))
}
-
+
private func applySmoothingAndThreshold(_ newLevel: CGFloat) -> CGFloat {
// Minimal smoothing for real-time response
audioLevelHistory.append(newLevel)
if audioLevelHistory.count > historySize {
audioLevelHistory.removeFirst()
}
-
+
// Light smoothing - mostly use current value
let average = audioLevelHistory.reduce(0, +) / CGFloat(audioLevelHistory.count)
let smoothingFactor: CGFloat = 0.7 // Much more responsive
smoothedLevel = (smoothingFactor * newLevel) + ((1 - smoothingFactor) * average)
-
+
// Simple threshold - just cut off below silence level
if smoothedLevel < silenceThreshold {
return 0.0
}
-
+
return smoothedLevel
}
- private func toMono16k(floatBuffer: AVAudioPCMBuffer) -> [Float]
- {
+ private func toMono16k(floatBuffer: AVAudioPCMBuffer) -> [Float] {
if let format = floatBuffer.format as AVAudioFormat?,
- format.sampleRate == 16000.0,
+ format.sampleRate == 16_000.0,
format.commonFormat == .pcmFormatFloat32,
format.channelCount == 1,
let channelData = floatBuffer.floatChannelData
@@ -590,22 +564,19 @@ final class ASRService: ObservableObject
let ptr = channelData[0]
return Array(UnsafeBufferPointer(start: ptr, count: frameCount))
}
- let mono = self.downmixToMono(floatBuffer)
- return self.resampleTo16k(mono, sourceSampleRate: floatBuffer.format.sampleRate)
+ let mono = downmixToMono(floatBuffer)
+ return resampleTo16k(mono, sourceSampleRate: floatBuffer.format.sampleRate)
}
- private func downmixToMono(_ buffer: AVAudioPCMBuffer) -> [Float]
- {
+ private func downmixToMono(_ buffer: AVAudioPCMBuffer) -> [Float] {
guard let channelData = buffer.floatChannelData else { return [] }
let frameCount = Int(buffer.frameLength)
let channels = Int(buffer.format.channelCount)
- if channels == 1
- {
+ if channels == 1 {
return Array(UnsafeBufferPointer(start: channelData[0], count: frameCount))
}
var mono = [Float](repeating: 0, count: frameCount)
- for c in 0..<channels
- {
+ for c in 0..<channels {
let src = channelData[c]
vDSP_vadd(src, 1, mono, 1, &mono, 1, vDSP_Length(frameCount))
}
@@ -614,27 +585,22 @@ final class ASRService: ObservableObject
return mono
}
- private func resampleTo16k(_ samples: [Float], sourceSampleRate: Double) -> [Float]
- {
+ private func resampleTo16k(_ samples: [Float], sourceSampleRate: Double) -> [Float] {
guard samples.isEmpty == false else { return [] }
- if sourceSampleRate == 16000.0 { return samples }
- let ratio = 16000.0 / sourceSampleRate
+ if sourceSampleRate == 16_000.0 { return samples }
+ let ratio = 16_000.0 / sourceSampleRate
let outCount = Int(Double(samples.count) * ratio)
var output = [Float](repeating: 0, count: max(outCount, 0))
if output.isEmpty { return [] }
- for i in 0..<outCount
- {
+ for i in 0..<outCount {
let srcPos = Double(i) / ratio
let idx = Int(srcPos)
let frac = Float(srcPos - Double(idx))
- if idx + 1 < samples.count
- {
+ if idx + 1 < samples.count {
let a = samples[idx]
let b = samples[idx + 1]
output[i] = a + (b - a) * frac
- }
- else if idx < samples.count
- {
+ } else if idx < samples.count {
output[i] = samples[idx]
}
}
@@ -657,57 +623,57 @@ final class ASRService: ObservableObject
/// Throws if model download or loading fails. Common causes:
/// - Network connectivity issues
/// - Insufficient disk space
- func ensureAsrReady() async throws
- {
+ func ensureAsrReady() async throws {
let provider = transcriptionProvider
let providerKey = "\(type(of: provider)):\(provider.name)"
-
+
// Single-flight: if a prepare is already running for this provider, await it.
if let task = ensureReadyTask, ensureReadyProviderKey == providerKey {
try await task.value
return
}
-
+
let task = Task { @MainActor in
try await self.performEnsureAsrReady(provider: provider)
}
ensureReadyTask = task
ensureReadyProviderKey = providerKey
-
+
defer {
if ensureReadyProviderKey == providerKey {
ensureReadyTask = nil
ensureReadyProviderKey = nil
}
}
-
+
try await task.value
}
-
- private func performEnsureAsrReady(provider: TranscriptionProvider) async throws
- {
+
+ private func performEnsureAsrReady(provider: TranscriptionProvider) async throws {
// Check if already ready
- if isAsrReady && provider.isReady {
- DebugLogger.shared.debug("ASR already ready with loaded models, skipping initialization", source: "ASRService")
+ if isAsrReady, provider.isReady {
+ DebugLogger.shared.debug(
+ "ASR already ready with loaded models, skipping initialization",
+ source: "ASRService"
+ )
return
}
-
+
// If the flag is set but provider isn't ready (e.g., provider switch without reset), re-init.
- if isAsrReady && !provider.isReady {
+ if isAsrReady, !provider.isReady {
DebugLogger.shared.debug("ASR marked ready but provider not ready; re-initializing", source: "ASRService")
}
-
+
isAsrReady = false
-
+
let totalStartTime = Date()
- do
- {
+ do {
DebugLogger.shared.info("=== ASR INITIALIZATION START ===", source: "ASRService")
DebugLogger.shared.info("Using provider: \(provider.name)", source: "ASRService")
-
+
let modelsAlreadyCached = provider.modelsExistOnDisk()
DebugLogger.shared.info("Models already cached on disk: \(modelsAlreadyCached)", source: "ASRService")
-
+
// Suppress stderr noise during model loading (ALWAYS restore, even on failure).
let originalStderr = dup(STDERR_FILENO)
var didRedirectStderr = false
@@ -729,7 +695,7 @@ final class ASRService: ObservableObject
close(originalStderr)
}
}
-
+
// Set correct loading state based on whether models are cached
DispatchQueue.main.async {
if modelsAlreadyCached {
@@ -742,28 +708,33 @@ final class ASRService: ObservableObject
DebugLogger.shared.info("⬇️ DOWNLOADING model...", source: "ASRService")
}
}
-
+
// Use the transcription provider to prepare models
let downloadStartTime = Date()
DebugLogger.shared.info("Calling transcriptionProvider.prepare()...", source: "ASRService")
try await provider.prepare(progressHandler: nil)
let downloadDuration = Date().timeIntervalSince(downloadStartTime)
- DebugLogger.shared.info("✓ Provider preparation completed in \(String(format: "%.1f", downloadDuration)) seconds", source: "ASRService")
-
+ DebugLogger.shared
+ .info(
+ "✓ Provider preparation completed in \(String(format: "%.1f", downloadDuration)) seconds",
+ source: "ASRService"
+ )
+
DispatchQueue.main.async {
self.isDownloadingModel = false
self.isLoadingModel = false
self.modelsExistOnDisk = true
}
-
+
let totalDuration = Date().timeIntervalSince(totalStartTime)
DebugLogger.shared.info("=== ASR INITIALIZATION COMPLETE ===", source: "ASRService")
- DebugLogger.shared.info("Total initialization time: \(String(format: "%.1f", totalDuration)) seconds", source: "ASRService")
-
+ DebugLogger.shared.info(
+ "Total initialization time: \(String(format: "%.1f", totalDuration)) seconds",
+ source: "ASRService"
+ )
+
isAsrReady = true
- }
- catch
- {
+ } catch {
DebugLogger.shared.error("ASR initialization failed with error: \(error)", source: "ASRService")
DebugLogger.shared.error("Error details: \(error.localizedDescription)", source: "ASRService")
DispatchQueue.main.async {
@@ -775,20 +746,16 @@ final class ASRService: ObservableObject
}
// MARK: - Model lifecycle helpers (parity with original API)
- func predownloadSelectedModel()
- {
- Task
- { [weak self] in
+
+ func predownloadSelectedModel() {
+ Task { [weak self] in
guard let self = self else { return }
DebugLogger.shared.info("Starting model predownload...", source: "ASRService")
// ensureAsrReady handles setting the correct loading/downloading state
- do
- {
+ do {
try await self.ensureAsrReady()
DebugLogger.shared.info("Model predownload completed successfully", source: "ASRService")
- }
- catch
- {
+ } catch {
DebugLogger.shared.error("Model predownload failed: \(error)", source: "ASRService")
self.errorTitle = "Download Failed"
self.errorMessage = error.localizedDescription
@@ -797,23 +764,18 @@ final class ASRService: ObservableObject
}
}
- func preloadModelAfterSelection() async
- {
+ func preloadModelAfterSelection() async {
// ensureAsrReady handles setting the correct loading/downloading state
- do
- {
- try await self.ensureAsrReady()
- }
- catch
- {
+ do {
+ try await ensureAsrReady()
+ } catch {
DebugLogger.shared.error("Model preload failed: \(error)", source: "ASRService")
}
}
-
// MARK: - Cache management
- func clearModelCache() async throws
- {
+
+ func clearModelCache() async throws {
DebugLogger.shared.debug("Clearing model cache via transcription provider", source: "ASRService")
try await transcriptionProvider.clearCache()
isAsrReady = false
@@ -821,12 +783,15 @@ final class ASRService: ObservableObject
}
// MARK: - Timer-based Streaming Transcription (No VAD)
-
+
private func startStreamingTranscription() {
streamingTask?.cancel()
guard isAsrReady else { return }
- DebugLogger.shared.debug("Starting streaming transcription task (interval: \(chunkDurationSeconds)s)", source: "ASRService")
+ DebugLogger.shared.debug(
+ "Starting streaming transcription task (interval: \(chunkDurationSeconds)s)",
+ source: "ASRService"
+ )
streamingTask = Task { [weak self] in
await self?.runStreamingLoop()
@@ -855,45 +820,52 @@ final class ASRService: ObservableObject
}
}
}
-
+
@MainActor
private func processStreamingChunk() async {
guard isRunning else { return }
-
+
// Skip if already processing to prevent queue buildup
guard !isProcessingChunk else {
- DebugLogger.shared.debug("⚠️ Skipping chunk - previous transcription still in progress", source: "ASRService")
+ DebugLogger.shared.debug(
+ "⚠️ Skipping chunk - previous transcription still in progress",
+ source: "ASRService"
+ )
skipNextChunk = true
return
}
-
+
if skipNextChunk {
DebugLogger.shared.debug("⚠️ Skipping chunk for ANE recovery", source: "ASRService")
skipNextChunk = false
return
}
-
+
guard isAsrReady, transcriptionProvider.isReady else { return }
-
+
// Thread-safe count check
let currentSampleCount = audioBuffer.count
- let minSamples = 8000 // 0.5 second minimum for faster initial feedback
+ 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)
-
+
isProcessingChunk = true
defer { isProcessingChunk = false }
-
+
let startTime = Date()
-
+
do {
- DebugLogger.shared.debug("Streaming chunk starting transcription (samples: \(chunk.count)) using \(transcriptionProvider.name)", source: "ASRService")
+ DebugLogger.shared
+ .debug(
+ "Streaming chunk starting transcription (samples: \(chunk.count)) using \(transcriptionProvider.name)",
+ source: "ASRService"
+ )
let result = try await transcriptionExecutor.run { [provider = self.transcriptionProvider] in
try await provider.transcribe(chunk)
}
-
+
let duration = Date().timeIntervalSince(startTime)
DebugLogger.shared.debug(
"Streaming chunk transcription finished in \(String(format: "%.2f", duration))s",
@@ -901,20 +873,27 @@ final class ASRService: ObservableObject
)
let rawText = result.text.trimmingCharacters(in: .whitespacesAndNewlines)
let newText = ASRService.removeFillerWords(rawText)
-
+
if !newText.isEmpty {
// Smart diff: only show truly new words
let updatedText = smartDiffUpdate(previous: previousFullTranscription, current: newText)
partialTranscription = updatedText
previousFullTranscription = newText
-
- DebugLogger.shared.debug("✅ Streaming: '\(updatedText)' (\(String(format: "%.2f", duration))s)", source: "ASRService")
+
+ DebugLogger.shared.debug(
+ "✅ Streaming: '\(updatedText)' (\(String(format: "%.2f", duration))s)",
+ source: "ASRService"
+ )
}
-
+
// 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 {
- DebugLogger.shared.debug("⚠️ Transcription slow (\(String(format: "%.2f", duration))s > \(chunkDurationSeconds)s), skipping next chunk", source: "ASRService")
+ DebugLogger.shared
+ .debug(
+ "⚠️ Transcription slow (\(String(format: "%.2f", duration))s > \(chunkDurationSeconds)s), skipping next chunk",
+ source: "ASRService"
+ )
skipNextChunk = true
}
} catch {
@@ -922,41 +901,42 @@ final class ASRService: ObservableObject
skipNextChunk = true
}
}
-
+
/// Smart diff to prevent text from jumping around
private func smartDiffUpdate(previous: String, current: String) -> String {
guard !previous.isEmpty else { return current }
guard !current.isEmpty else { return previous }
-
+
let prevWords = previous.split(separator: " ").map(String.init)
let currWords = current.split(separator: " ").map(String.init)
-
+
// Find longest common prefix
var commonPrefixLength = 0
for i in 0..<min(prevWords.count, currWords.count) {
if prevWords[i].lowercased().trimmingCharacters(in: .punctuationCharacters) ==
- currWords[i].lowercased().trimmingCharacters(in: .punctuationCharacters) {
+ currWords[i].lowercased().trimmingCharacters(in: .punctuationCharacters)
+ {
commonPrefixLength = i + 1
} else {
break
}
}
-
+
// If >50% overlap, keep stable prefix and add new words
if commonPrefixLength > prevWords.count / 2 {
let stableWords = Array(currWords[0..<min(commonPrefixLength, currWords.count)])
let newWords = currWords.count > commonPrefixLength ? Array(currWords[commonPrefixLength...]) : []
return (stableWords + newWords).joined(separator: " ")
} else {
- return current // Significant change
+ return current // Significant change
}
}
// MARK: - Typing convenience for compatibility
+
private let typingService = TypingService() // Reuse instance to avoid conflicts
- func typeTextToActiveField(_ text: String)
- {
+ func typeTextToActiveField(_ text: String) {
typingService.typeTextInstantly(text)
}
diff --git a/Sources/Fluid/Services/AppServices.swift b/Sources/Fluid/Services/AppServices.swift
index 46eba6b8..7ca7fa34 100644
--- a/Sources/Fluid/Services/AppServices.swift
+++ b/Sources/Fluid/Services/AppServices.swift
@@ -1,15 +1,5 @@
-//
-// AppServices.swift
-// Fluid
-//
-// Centralized service container to reduce SwiftUI view type complexity.
-// By holding heavy services here (outside ContentView's @StateObject declarations),
-// we reduce the generic type signature of ContentView, which helps avoid
-// Swift runtime type metadata crashes at app launch.
-//
-
-import Foundation
import Combine
+import Foundation
/// Centralized container for app-wide services.
/// This exists to reduce ContentView's generic type signature complexity,
@@ -19,29 +9,29 @@ import Combine
final class AppServices: ObservableObject {
/// Shared singleton instance
static let shared = AppServices()
-
+
/// Audio hardware observation service
let audioObserver = AudioHardwareObserver()
-
+
/// Automatic speech recognition service
let asr = ASRService()
-
+
private var cancellables = Set<AnyCancellable>()
-
+
private init() {
// Services are created but NOT started here.
// Actual initialization (CoreAudio listeners, model loading) is deferred
// to when the UI is ready, via AudioStartupGate.
-
+
// CRITICAL: Forward changes from child services to this container.
// This allows ContentView to observe 'AppServices' (which is metadata-safe)
// instead of observing 'ASRService' directly (which causes metadata crashes),
// while still triggering UI updates when transcription or audio state changes.
-
+
audioObserver.objectWillChange
.sink { [weak self] _ in self?.objectWillChange.send() }
.store(in: &cancellables)
-
+
asr.objectWillChange
.sink { [weak self] _ in self?.objectWillChange.send() }
.store(in: &cancellables)
diff --git a/Sources/Fluid/Services/AudioDeviceService.swift b/Sources/Fluid/Services/AudioDeviceService.swift
index 3cdb93c2..aaf09760 100644
--- a/Sources/Fluid/Services/AudioDeviceService.swift
+++ b/Sources/Fluid/Services/AudioDeviceService.swift
@@ -1,13 +1,6 @@
-//
-// AudioDeviceService.swift
-// fluid
-//
-// CoreAudio device management and monitoring
-//
-
-import Foundation
-import CoreAudio
import Combine
+import CoreAudio
+import Foundation
// MARK: - Audio Device Manager
@@ -28,14 +21,27 @@ enum AudioDevice {
)
var dataSize: UInt32 = 0
- var status = AudioObjectGetPropertyDataSize(AudioObjectID(kAudioObjectSystemObject), &address, 0, nil, &dataSize)
+ var status = AudioObjectGetPropertyDataSize(
+ AudioObjectID(kAudioObjectSystemObject),
+ &address,
+ 0,
+ nil,
+ &dataSize
+ )
if status != noErr || dataSize == 0 {
return []
}
let count = Int(dataSize) / MemoryLayout<AudioObjectID>.size
var deviceIDs = [AudioObjectID](repeating: 0, count: count)
- status = AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &address, 0, nil, &dataSize, &deviceIDs)
+ status = AudioObjectGetPropertyData(
+ AudioObjectID(kAudioObjectSystemObject),
+ &address,
+ 0,
+ nil,
+ &dataSize,
+ &deviceIDs
+ )
if status != noErr {
return []
}
@@ -44,8 +50,16 @@ enum AudioDevice {
devices.reserveCapacity(deviceIDs.count)
for devId in deviceIDs {
- let name = getStringProperty(devId, selector: kAudioObjectPropertyName, scope: kAudioObjectPropertyScopeGlobal) ?? "Unknown"
- let uid = getStringProperty(devId, selector: kAudioDevicePropertyDeviceUID, scope: kAudioObjectPropertyScopeGlobal) ?? ""
+ let name = getStringProperty(
+ devId,
+ selector: kAudioObjectPropertyName,
+ scope: kAudioObjectPropertyScopeGlobal
+ ) ?? "Unknown"
+ let uid = getStringProperty(
+ devId,
+ selector: kAudioDevicePropertyDeviceUID,
+ scope: kAudioObjectPropertyScopeGlobal
+ ) ?? ""
let hasIn = hasChannels(devId, scope: kAudioObjectPropertyScopeInput)
let hasOut = hasChannels(devId, scope: kAudioObjectPropertyScopeOutput)
devices.append(Device(id: devId, uid: uid, name: name, hasInput: hasIn, hasOutput: hasOut))
@@ -63,12 +77,14 @@ enum AudioDevice {
}
static func getDefaultInputDevice() -> Device? {
- guard let devId: AudioObjectID = getDefaultDeviceId(selector: kAudioHardwarePropertyDefaultInputDevice) else { return nil }
+ guard let devId: AudioObjectID = getDefaultDeviceId(selector: kAudioHardwarePropertyDefaultInputDevice)
+ else { return nil }
return listAllDevices().first { $0.id == devId }
}
static func getDefaultOutputDevice() -> Device? {
- guard let devId: AudioObjectID = getDefaultDeviceId(selector: kAudioHardwarePropertyDefaultOutputDevice) else { return nil }
+ guard let devId: AudioObjectID = getDefaultDeviceId(selector: kAudioHardwarePropertyDefaultOutputDevice)
+ else { return nil }
return listAllDevices().first { $0.id == devId }
}
@@ -92,7 +108,14 @@ enum AudioDevice {
)
var devId = AudioObjectID(0)
var size = UInt32(MemoryLayout<AudioObjectID>.size)
- let status = AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &address, 0, nil, &size, &devId)
+ let status = AudioObjectGetPropertyData(
+ AudioObjectID(kAudioObjectSystemObject),
+ &address,
+ 0,
+ nil,
+ &size,
+ &devId
+ )
return status == noErr ? devId : nil
}
@@ -104,11 +127,22 @@ enum AudioDevice {
)
var mutableDevId = devId
let size = UInt32(MemoryLayout<AudioObjectID>.size)
- let status = AudioObjectSetPropertyData(AudioObjectID(kAudioObjectSystemObject), &address, 0, nil, size, &mutableDevId)
+ let status = AudioObjectSetPropertyData(
+ AudioObjectID(kAudioObjectSystemObject),
+ &address,
+ 0,
+ nil,
+ size,
+ &mutableDevId
+ )
return status == noErr
}
- private static func getStringProperty(_ devId: AudioObjectID, selector: AudioObjectPropertySelector, scope: AudioObjectPropertyScope) -> String? {
+ private static func getStringProperty(
+ _ devId: AudioObjectID,
+ selector: AudioObjectPropertySelector,
+ scope: AudioObjectPropertyScope
+ ) -> String? {
var address = AudioObjectPropertyAddress(
mSelector: selector,
mScope: scope,
@@ -180,7 +214,7 @@ final class AudioHardwareObserver: ObservableObject {
// with SwiftUI's AttributeGraph metadata processing, leading to EXC_BAD_ACCESS crashes.
// Registration is deferred until startObserving() is called after app finishes launching.
}
-
+
/// 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() {
@@ -231,9 +265,3 @@ final class AudioHardwareObserver: ObservableObject {
installed = false
}
}
-
-
-
-
-
-
diff --git a/Sources/Fluid/Services/AudioStartupGate.swift b/Sources/Fluid/Services/AudioStartupGate.swift
index 5d9d2b19..29df8f2f 100644
--- a/Sources/Fluid/Services/AudioStartupGate.swift
+++ b/Sources/Fluid/Services/AudioStartupGate.swift
@@ -1,11 +1,3 @@
-//
-// AudioStartupGate.swift
-// Fluid
-//
-// A centralized gate to prevent CoreAudio/AVFoundation initialization during SwiftUI's
-// early AttributeGraph metadata processing (a known crash-prone window).
-//
-
import Foundation
/// Centralized startup gate for any code paths that can trigger CoreAudio initialization.
@@ -45,7 +37,7 @@ actor AudioStartupGate {
if isOpen { return }
await withCheckedContinuation { cont in
- waiters.append(cont)
+ self.waiters.append(cont)
}
}
@@ -58,5 +50,3 @@ actor AudioStartupGate {
pending.forEach { $0.resume() }
}
}
-
-
diff --git a/Sources/Fluid/Services/ClipboardService.swift b/Sources/Fluid/Services/ClipboardService.swift
index dd11b296..e26cfc2c 100644
--- a/Sources/Fluid/Services/ClipboardService.swift
+++ b/Sources/Fluid/Services/ClipboardService.swift
@@ -1,39 +1,35 @@
-import Foundation
import AppKit
+import Foundation
/// A simple service for clipboard operations
-final class ClipboardService
-{
+enum ClipboardService {
/// Copies the provided text to the system clipboard
/// - Parameter text: The text to copy to clipboard
/// - Returns: Boolean indicating success or failure
@discardableResult
- static func copyToClipboard(_ text: String) -> Bool
- {
+ static func copyToClipboard(_ text: String) -> Bool {
guard !text.isEmpty else {
DebugLogger.shared.debug("Attempted to copy empty text to clipboard, skipping", source: "ClipboardService")
return false
}
-
+
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
let success = pasteboard.setString(text, forType: .string)
-
+
if success {
DebugLogger.shared.info("Copied \(text.count) characters to clipboard", source: "ClipboardService")
} else {
DebugLogger.shared.error("Failed to copy text to clipboard", source: "ClipboardService")
}
-
+
return success
}
-
+
/// Retrieves the current text content from the clipboard
/// - Returns: The clipboard text, or nil if no text is available
- static func getFromClipboard() -> String?
- {
+ static func getFromClipboard() -> String? {
let pasteboard = NSPasteboard.general
return pasteboard.string(forType: .string)
}
}
-
diff --git a/Sources/Fluid/Services/CommandModeService.swift b/Sources/Fluid/Services/CommandModeService.swift
index d1678146..c451426e 100644
--- a/Sources/Fluid/Services/CommandModeService.swift
+++ b/Sources/Fluid/Services/CommandModeService.swift
@@ -1,5 +1,5 @@
-import Foundation
import Combine
+import Foundation
@MainActor
final class CommandModeService: ObservableObject {
@@ -7,32 +7,32 @@ final class CommandModeService: ObservableObject {
@Published var isProcessing = false
@Published var pendingCommand: PendingCommand? = nil
@Published var currentStep: AgentStep? = nil
- @Published var streamingText: String = "" // Real-time streaming text for UI
+ @Published var streamingText: String = "" // Real-time streaming text for UI
@Published private(set) var currentChatID: String?
-
+
private let terminalService = TerminalService()
private let chatStore = ChatHistoryStore.shared
private var currentTurnCount = 0
private let maxTurns = 20
-
+
// Flag to enable notch output display
var enableNotchOutput: Bool = true
-
+
// Streaming UI update throttling - adaptive rate based on content length
private var lastUIUpdate: CFAbsoluteTime = 0
- private var streamingBuffer: [String] = [] // Buffer tokens instead of string concat
-
+ private var streamingBuffer: [String] = [] // Buffer tokens instead of string concat
+
// MARK: - Initialization
-
+
init() {
// Load current chat from store
loadCurrentChatFromStore()
}
-
+
private func loadCurrentChatFromStore() {
if let session = chatStore.currentSession {
currentChatID = session.id
- conversationHistory = session.messages.map { chatMessageToMessage($0) }
+ conversationHistory = session.messages.map { self.chatMessageToMessage($0) }
syncToNotchState()
} else {
// Create new chat if none exists
@@ -41,9 +41,9 @@ final class CommandModeService: ObservableObject {
conversationHistory = []
}
}
-
+
// MARK: - Agent Step Tracking
-
+
enum AgentStep: Equatable {
case thinking(String)
case checking(String)
@@ -51,9 +51,9 @@ final class CommandModeService: ObservableObject {
case verifying(String)
case completed(Bool)
}
-
+
// MARK: - Models
-
+
struct Message: Identifiable, Equatable {
let id = UUID()
let role: Role
@@ -61,75 +61,75 @@ final class CommandModeService: ObservableObject {
let toolCall: ToolCall?
let stepType: StepType
let timestamp: Date
-
+
enum Role: Equatable {
case user
case assistant
case tool
}
-
+
enum StepType: Equatable {
case normal
- case thinking // AI reasoning
- case checking // Pre-flight verification
- case executing // Running command
- case verifying // Post-action check
- case success // Action completed
- case failure // Action failed
+ case thinking // AI reasoning
+ case checking // Pre-flight verification
+ case executing // Running command
+ case verifying // Post-action check
+ case success // Action completed
+ case failure // Action failed
}
-
+
struct ToolCall: Equatable {
let id: String
let command: String
let workingDirectory: String?
- let purpose: String? // Why this command is being run
+ let purpose: String? // Why this command is being run
}
-
+
init(role: Role, content: String, toolCall: ToolCall? = nil, stepType: StepType = .normal) {
self.role = role
self.content = content
self.toolCall = toolCall
self.stepType = stepType
- self.timestamp = Date()
+ timestamp = Date()
}
}
-
+
struct PendingCommand {
let id: String
let command: String
let workingDirectory: String?
let purpose: String?
}
-
+
// MARK: - Public Methods
-
+
func clearHistory() {
conversationHistory.removeAll()
pendingCommand = nil
currentTurnCount = 0
-
+
// Clear in store as well
chatStore.clearCurrentChat()
-
+
// Also clear notch state
NotchContentState.shared.clearCommandOutput()
}
-
+
// MARK: - Chat Management
-
+
/// Get recent chats for dropdown
func getRecentChats() -> [ChatSession] {
return chatStore.getRecentChats(excludingCurrent: false)
}
-
+
/// Create a new chat and switch to it
func createNewChat() {
// Can't switch while processing
guard !isProcessing else { return }
-
+
// Save current chat first
saveCurrentChat()
-
+
// Create new
let newSession = chatStore.createNewChat()
currentChatID = newSession.id
@@ -137,63 +137,63 @@ final class CommandModeService: ObservableObject {
pendingCommand = nil
currentTurnCount = 0
currentStep = nil
-
+
// Clear notch state
NotchContentState.shared.clearCommandOutput()
NotchContentState.shared.refreshRecentChats()
}
-
+
/// Switch to a different chat by ID
/// Returns false if switching is blocked (e.g., during processing)
@discardableResult
func switchToChat(id: String) -> Bool {
// Can't switch while processing
guard !isProcessing else { return false }
-
+
// Don't switch to current
guard id != currentChatID else { return true }
-
+
// Save current chat first
saveCurrentChat()
-
+
// Load the target chat
guard let session = chatStore.switchToChat(id: id) else { return false }
-
+
currentChatID = session.id
- conversationHistory = session.messages.map { chatMessageToMessage($0) }
+ conversationHistory = session.messages.map { self.chatMessageToMessage($0) }
pendingCommand = nil
currentTurnCount = 0
currentStep = nil
-
+
// Sync to notch state
syncToNotchState()
NotchContentState.shared.refreshRecentChats()
-
+
return true
}
-
+
/// Delete current chat and switch to next
func deleteCurrentChat() {
// Can't delete while processing
guard !isProcessing else { return }
-
+
chatStore.deleteCurrentChat()
-
+
// Load the new current chat
loadCurrentChatFromStore()
NotchContentState.shared.refreshRecentChats()
}
-
+
/// Save current conversation to store
func saveCurrentChat() {
guard currentChatID != nil else { return }
-
- let messages = conversationHistory.map { messageToChatMessage($0) }
+
+ let messages = conversationHistory.map { self.messageToChatMessage($0) }
chatStore.updateCurrentChat(messages: messages)
}
-
+
// MARK: - Conversion Helpers
-
+
private func messageToChatMessage(_ msg: Message) -> ChatMessage {
let role: ChatMessage.Role
switch msg.role {
@@ -201,7 +201,7 @@ final class CommandModeService: ObservableObject {
case .assistant: role = .assistant
case .tool: role = .tool
}
-
+
let stepType: ChatMessage.StepType
switch msg.stepType {
case .normal: stepType = .normal
@@ -212,7 +212,7 @@ final class CommandModeService: ObservableObject {
case .success: stepType = .success
case .failure: stepType = .failure
}
-
+
var toolCall: ChatMessage.ToolCall? = nil
if let tc = msg.toolCall {
toolCall = ChatMessage.ToolCall(
@@ -222,7 +222,7 @@ final class CommandModeService: ObservableObject {
purpose: tc.purpose
)
}
-
+
return ChatMessage(
id: msg.id,
role: role,
@@ -232,7 +232,7 @@ final class CommandModeService: ObservableObject {
timestamp: msg.timestamp
)
}
-
+
private func chatMessageToMessage(_ chatMsg: ChatMessage) -> Message {
let role: Message.Role
switch chatMsg.role {
@@ -240,7 +240,7 @@ final class CommandModeService: ObservableObject {
case .assistant: role = .assistant
case .tool: role = .tool
}
-
+
let stepType: Message.StepType
switch chatMsg.stepType {
case .normal: stepType = .normal
@@ -251,7 +251,7 @@ final class CommandModeService: ObservableObject {
case .success: stepType = .success
case .failure: stepType = .failure
}
-
+
var toolCall: Message.ToolCall? = nil
if let tc = chatMsg.toolCall {
toolCall = Message.ToolCall(
@@ -261,7 +261,7 @@ final class CommandModeService: ObservableObject {
purpose: tc.purpose
)
}
-
+
return Message(
role: role,
content: chatMsg.content,
@@ -269,72 +269,72 @@ final class CommandModeService: ObservableObject {
stepType: stepType
)
}
-
+
/// Sync conversation history to NotchContentState
private func syncToNotchState() {
NotchContentState.shared.clearCommandOutput()
-
+
for msg in conversationHistory {
let role: NotchContentState.CommandOutputMessage.Role
switch msg.role {
case .user: role = .user
case .assistant: role = .assistant
- case .tool: role = .status // Tool outputs shown as status in notch
+ case .tool: role = .status // Tool outputs shown as status in notch
}
-
+
// Skip tool outputs in notch (they're verbose)
if msg.role == .tool { continue }
-
+
NotchContentState.shared.addCommandMessage(role: role, content: msg.content)
}
}
-
+
/// Process user voice/text command
func processUserCommand(_ text: String) async {
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
-
+
isProcessing = true
currentTurnCount = 0
conversationHistory.append(Message(role: .user, content: text))
-
+
// Auto-save after adding user message
saveCurrentChat()
-
+
// Push to notch
if enableNotchOutput {
NotchContentState.shared.addCommandMessage(role: .user, content: text)
NotchContentState.shared.setCommandProcessing(true)
}
-
+
await processNextTurn()
}
-
+
/// Process follow-up command from notch input
func processFollowUpCommand(_ text: String) async {
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
-
+
// Add to both histories
conversationHistory.append(Message(role: .user, content: text))
NotchContentState.shared.addCommandMessage(role: .user, content: text)
-
+
// Auto-save after adding user message
saveCurrentChat()
-
+
isProcessing = true
NotchContentState.shared.setCommandProcessing(true)
-
+
await processNextTurn()
}
-
+
/// Execute pending command (after user confirmation)
func confirmAndExecute() async {
guard let pending = pendingCommand else { return }
pendingCommand = nil
isProcessing = true
-
+
await executeCommand(pending.command, workingDirectory: pending.workingDirectory, callId: pending.id)
}
-
+
/// Cancel pending command
func cancelPendingCommand() {
pendingCommand = nil
@@ -346,9 +346,9 @@ final class CommandModeService: ObservableObject {
isProcessing = false
currentStep = nil
}
-
+
// MARK: - Agent Loop
-
+
private func processNextTurn() async {
if currentTurnCount >= maxTurns {
let errorMsg = "Reached maximum steps limit. Please review the progress and continue if needed."
@@ -359,10 +359,10 @@ final class CommandModeService: ObservableObject {
))
isProcessing = false
currentStep = .completed(false)
-
+
// Auto-save on completion
saveCurrentChat()
-
+
// Push to notch
if enableNotchOutput {
NotchContentState.shared.addCommandMessage(role: .assistant, content: errorMsg)
@@ -371,23 +371,23 @@ final class CommandModeService: ObservableObject {
}
return
}
-
+
currentTurnCount += 1
currentStep = .thinking("Analyzing...")
-
+
// Push status to notch
if enableNotchOutput {
NotchContentState.shared.addCommandMessage(role: .status, content: "Thinking...")
}
-
+
do {
let response = try await callLLM()
-
+
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)
-
+
// AI wants to run a command
conversationHistory.append(Message(
role: .assistant,
@@ -395,20 +395,21 @@ final class CommandModeService: ObservableObject {
toolCall: Message.ToolCall(
id: tc.id,
command: tc.command,
- workingDirectory: tc.workingDirectory,
+ workingDirectory: tc
+ .workingDirectory,
purpose: tc.purpose
),
stepType: stepType
))
-
+
// Push step to notch
if enableNotchOutput {
let statusText = tc.purpose ?? 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) {
+ if SettingsStore.shared.commandModeConfirmBeforeExecute, isDestructiveCommand(tc.command) {
pendingCommand = PendingCommand(
id: tc.id,
command: tc.command,
@@ -417,25 +418,33 @@ final class CommandModeService: ObservableObject {
)
isProcessing = false
currentStep = nil
-
+
// Push confirmation needed to notch
if enableNotchOutput {
- NotchContentState.shared.addCommandMessage(role: .status, content: "⚠️ Confirmation needed in Command Mode window")
+ NotchContentState.shared.addCommandMessage(
+ role: .status,
+ content: "⚠️ Confirmation needed in Command Mode window"
+ )
NotchContentState.shared.setCommandProcessing(false)
}
return
}
-
+
// Auto-execute
- await executeCommand(tc.command, workingDirectory: tc.workingDirectory, callId: tc.id, purpose: tc.purpose)
-
+ await executeCommand(
+ tc.command,
+ workingDirectory: tc.workingDirectory,
+ callId: tc.id,
+ purpose: tc.purpose
+ )
+
} else {
// Just a text response - check if it's a final summary
let isFinal = response.content.lowercased().contains("complete") ||
- response.content.lowercased().contains("done") ||
- response.content.lowercased().contains("success") ||
- response.content.lowercased().contains("finished")
-
+ response.content.lowercased().contains("done") ||
+ response.content.lowercased().contains("success") ||
+ response.content.lowercased().contains("finished")
+
conversationHistory.append(Message(
role: .assistant,
content: response.content,
@@ -443,19 +452,19 @@ final class CommandModeService: ObservableObject {
))
isProcessing = false
currentStep = .completed(isFinal)
-
+
// Auto-save on completion
saveCurrentChat()
-
+
// Push final response to notch and show expanded view
if enableNotchOutput {
- NotchContentState.shared.updateCommandStreamingText("") // Clear streaming
+ NotchContentState.shared.updateCommandStreamingText("") // Clear streaming
NotchContentState.shared.addCommandMessage(role: .assistant, content: response.content)
NotchContentState.shared.setCommandProcessing(false)
showExpandedNotchIfNeeded()
}
}
-
+
} catch {
let errorMsg = "Error: \(error.localizedDescription)"
conversationHistory.append(Message(
@@ -465,10 +474,10 @@ final class CommandModeService: ObservableObject {
))
isProcessing = false
currentStep = .completed(false)
-
+
// Auto-save on error
saveCurrentChat()
-
+
// Push error to notch
if enableNotchOutput {
NotchContentState.shared.addCommandMessage(role: .assistant, content: errorMsg)
@@ -477,38 +486,39 @@ final class CommandModeService: ObservableObject {
}
}
}
-
+
/// Show expanded notch output if there's content to display
private func showExpandedNotchIfNeeded() {
guard enableNotchOutput else { return }
guard !NotchContentState.shared.commandConversationHistory.isEmpty else { return }
-
+
// Show the expanded notch
NotchOverlayManager.shared.showExpandedCommandOutput()
}
-
+
private func determineStepType(for command: String, purpose: String?) -> Message.StepType {
let cmd = command.lowercased()
let purposeLower = purpose?.lowercased() ?? ""
-
+
// Check commands
if purposeLower.contains("check") || purposeLower.contains("verify") || purposeLower.contains("exist") {
return .checking
}
if cmd.hasPrefix("ls ") || cmd.hasPrefix("cat ") || cmd.hasPrefix("test ") || cmd.hasPrefix("[ ") ||
- cmd.contains("--version") || cmd.contains("which ") || cmd.contains("file ") ||
- cmd.hasPrefix("stat ") || cmd.hasPrefix("head ") || cmd.hasPrefix("tail ") {
+ cmd.contains("--version") || cmd.contains("which ") || cmd.contains("file ") ||
+ cmd.hasPrefix("stat ") || cmd.hasPrefix("head ") || cmd.hasPrefix("tail ")
+ {
return .checking
}
-
+
// Verification commands
if purposeLower.contains("confirm") || purposeLower.contains("result") {
return .verifying
}
-
+
return .executing
}
-
+
private func stepDescription(for stepType: Message.StepType) -> String {
switch stepType {
case .checking: return "Checking prerequisites..."
@@ -517,29 +527,29 @@ final class CommandModeService: ObservableObject {
default: return ""
}
}
-
+
private func isDestructiveCommand(_ command: String) -> Bool {
let cmd = command.lowercased()
-
+
// Commands that start with these are destructive
let destructivePrefixes = [
"rm ", "rm\t", "rmdir ", "rm -", // delete
- "mv ", "mv\t", // move/rename
- "sudo ", // elevated privileges
- "kill ", "pkill ", "killall ", // terminate processes
- "chmod ", "chown ", "chgrp ", // change permissions/ownership
- "dd ", // disk operations
- "mkfs", "format", // filesystem formatting
- "> ", // overwrite file
- "truncate ", // truncate file
- "shred ", // secure delete
+ "mv ", "mv\t", // move/rename
+ "sudo ", // elevated privileges
+ "kill ", "pkill ", "killall ", // terminate processes
+ "chmod ", "chown ", "chgrp ", // change permissions/ownership
+ "dd ", // disk operations
+ "mkfs", "format", // filesystem formatting
+ "> ", // overwrite file
+ "truncate ", // truncate file
+ "shred ", // secure delete
]
-
+
// Check if command starts with any destructive prefix
if destructivePrefixes.contains(where: { cmd.hasPrefix($0) }) {
return true
}
-
+
// Check for destructive patterns anywhere in piped commands
let destructivePatterns = [
"| rm ", "| sudo ", "| dd ",
@@ -547,51 +557,56 @@ final class CommandModeService: ObservableObject {
"&& rm ", "&& sudo ",
"xargs rm", "xargs -I",
]
-
+
if destructivePatterns.contains(where: { cmd.contains($0) }) {
return true
}
-
+
// rm with flags like -rf, -r, -f anywhere
if cmd.contains("rm -") {
return true
}
-
+
return false
}
-
- private func executeCommand(_ command: String, workingDirectory: String?, callId: String, purpose: String? = nil) async {
+
+ private func executeCommand(
+ _ command: String,
+ workingDirectory: String?,
+ callId: String,
+ purpose: String? = nil
+ ) async {
currentStep = .executing(command)
-
+
let result = await terminalService.execute(
command: command,
workingDirectory: workingDirectory
)
-
+
// Create enhanced result with context
let enhancedResult = EnhancedCommandResult(
result: result,
purpose: purpose
)
-
+
let resultJSON = enhancedResult.toJSON()
-
+
// Determine result step type
let resultStepType: Message.StepType = result.success ? .success : .failure
-
+
// Add tool result to conversation
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()
}
-
+
// MARK: - Enhanced Result
-
+
private struct EnhancedCommandResult: Codable {
let success: Bool
let command: String
@@ -600,22 +615,23 @@ final class CommandModeService: ObservableObject {
let exitCode: Int32
let executionTimeMs: Int
let purpose: String?
-
+
init(result: TerminalService.CommandResult, purpose: String?) {
- self.success = result.success
- self.command = result.command
- self.output = result.output
- self.error = result.error
- self.exitCode = result.exitCode
- self.executionTimeMs = result.executionTimeMs
+ success = result.success
+ command = result.command
+ output = result.output
+ error = result.error
+ exitCode = result.exitCode
+ executionTimeMs = result.executionTimeMs
self.purpose = purpose
}
-
+
func toJSON() -> String {
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
if let data = try? encoder.encode(self),
- let json = String(data: data, encoding: .utf8) {
+ let json = String(data: data, encoding: .utf8)
+ {
return json
}
return """
@@ -623,13 +639,13 @@ final class CommandModeService: ObservableObject {
"""
}
}
-
+
// MARK: - LLM Integration
-
+
private struct LLMResponse {
let content: String
let toolCall: ToolCallData?
-
+
struct ToolCallData {
let id: String
let command: String
@@ -637,14 +653,14 @@ final class CommandModeService: ObservableObject {
let purpose: String?
}
}
-
+
private func callLLM() async throws -> LLMResponse {
let settings = SettingsStore.shared
// Use Command Mode's independent provider/model settings
let providerID = settings.commandModeSelectedProviderID
let model = settings.commandModeSelectedModel ?? "gpt-4o"
let apiKey = settings.getAPIKey(for: providerID) ?? ""
-
+
let baseURL: String
if let provider = settings.savedProviders.first(where: { $0.id == providerID }) {
baseURL = provider.baseURL
@@ -653,96 +669,96 @@ final class CommandModeService: ObservableObject {
} else {
baseURL = "https://api.openai.com/v1"
}
-
+
// Build conversation with agentic system prompt
let systemPrompt = """
You are an autonomous, thoughtful macOS terminal agent. Execute user requests reliably and safely.
-
+
## AGENTIC WORKFLOW (Follow this pattern):
-
+
### 1. PRE-FLIGHT CHECKS (Always do this first!)
Before ANY action, verify prerequisites:
- File operations: Check if file/folder exists first (`ls`, `test -e`, `[ -f file ]`)
- Deletions: List contents before removing, confirm target exists
- Modifications: Read current state before changing
- Installations: Check if already installed (`which`, `--version`)
-
+
### 2. EXECUTE WITH CONTEXT
When calling execute_terminal_command, ALWAYS include a `purpose` parameter explaining:
- "checking" - Verifying something exists/state
- "executing" - Performing the main action
- "verifying" - Confirming the result
Example purposes: "Checking if image1.png exists", "Creating the backup directory", "Verifying file was deleted"
-
+
### 3. POST-ACTION VERIFICATION
After modifying anything, verify it worked:
- Created file? `ls` to confirm it exists
- Deleted file? `ls` to confirm it's gone
- Modified content? `cat` or `head` to verify changes
- Installed app? Check version/existence
-
+
### 4. HANDLE FAILURES GRACEFULLY
- If something doesn't exist: Tell the user clearly
- If command fails: Analyze error, try alternative approach
- If permission denied: Explain and suggest solutions
- Never assume success without verification
-
+
## RESPONSE FORMAT:
- Keep reasoning brief and clear
- State what you're checking/doing before each command
- After verification, give a clear success/failure summary
- Use natural language, not code comments
-
+
## SAFETY RULES:
- For destructive ops (rm, mv, overwrite): ALWAYS check target exists first
- Show what will be affected before destroying
- Prefer `rm -i` or listing contents before bulk deletes
- Use full absolute paths when possible
-
+
## EXAMPLES OF GOOD BEHAVIOR:
-
+
User: "Delete image1.png in Downloads"
You: First check if it exists
→ execute_terminal_command(command: "ls -la ~/Downloads/image1.png", purpose: "Checking if image1.png exists")
If exists → execute_terminal_command(command: "rm ~/Downloads/image1.png", purpose: "Deleting the file")
Then verify → execute_terminal_command(command: "ls ~/Downloads/image1.png 2>&1", purpose: "Verifying file was deleted")
Finally: "✓ Successfully deleted image1.png from Downloads."
-
+
User: "Create a project folder with a readme"
You: → Check if folder exists, create it, create readme, verify both
-
+
## NATIVE macOS APP CONTROL (Use osascript):
For Reminders, Notes, Calendar, Messages, Mail, and other native macOS apps, use `osascript`:
-
+
### Reminders:
- Create reminder (default list): `osascript -e 'tell application "Reminders" to make new reminder with properties {name:"<text>"}'`
- Create in specific list: `osascript -e 'tell application "Reminders" to make new reminder at end of list "<ListName>" with properties {name:"<text>"}'`
- With due date: `osascript -e 'tell application "Reminders" to make new reminder with properties {name:"<text>", due date:date "12/25/2024 3:00 PM"}'`
- ⚠️ Do NOT use `reminders list 1` syntax - it causes errors. Use `list "<name>"` or omit the list entirely.
-
+
### Notes:
- Create note: `osascript -e 'tell application "Notes" to make new note at folder "Notes" with properties {name:"<title>", body:"<content>"}'`
-
+
### Calendar:
- Create event: `osascript -e 'tell application "Calendar" to tell calendar "<CalendarName>" to make new event with properties {summary:"<title>", start date:date "<date>", end date:date "<date>"}'`
-
+
### Messages:
- Send iMessage: `osascript -e 'tell application "Messages" to send "<message>" to buddy "<phone/email>"'`
-
+
### General Pattern:
Always use `osascript -e 'tell application "<AppName>" to ...'` for native app automation.
-
+
The user is on macOS with zsh shell. Be thorough but efficient.
When task is complete, provide a clear summary starting with ✓ or ✗.
"""
-
+
var messages: [[String: Any]] = [
- ["role": "system", "content": systemPrompt]
+ ["role": "system", "content": systemPrompt],
]
-
+
// Add conversation history
var lastToolCallId: String? = nil
-
+
for msg in conversationHistory {
switch msg.role {
case .user:
@@ -760,10 +776,10 @@ final class CommandModeService: ObservableObject {
"name": "execute_terminal_command",
"arguments": try! String(data: JSONSerialization.data(withJSONObject: [
"command": tc.command,
- "workingDirectory": tc.workingDirectory ?? ""
- ]), encoding: .utf8)!
- ]
- ]]
+ "workingDirectory": tc.workingDirectory ?? "",
+ ]), encoding: .utf8)!,
+ ],
+ ]],
])
} else {
messages.append(["role": "assistant", "content": msg.content])
@@ -772,48 +788,47 @@ final class CommandModeService: ObservableObject {
messages.append([
"role": "tool",
"content": msg.content,
- "tool_call_id": lastToolCallId ?? "call_unknown"
+ "tool_call_id": lastToolCallId ?? "call_unknown",
])
}
}
-
+
// We assume conversationHistory contains the user's latest message already
-
// Check streaming setting
let enableStreaming = SettingsStore.shared.enableAIStreaming
-
+
// Build request
// Reasoning models (o1, o3, gpt-5) don't support temperature parameter at all
let isReasoningModel = model.hasPrefix("o1") || model.hasPrefix("o3") || model.hasPrefix("gpt-5")
-
+
var body: [String: Any] = [
"model": model,
"messages": messages,
"tools": [TerminalService.toolDefinition],
- "tool_choice": "auto"
+ "tool_choice": "auto",
]
-
+
// Only add temperature for non-reasoning models
if !isReasoningModel {
body["temperature"] = 0.1
}
-
+
if enableStreaming {
body["stream"] = true
}
-
+
let endpoint = baseURL.hasSuffix("/chat/completions") ? baseURL : "\(baseURL)/chat/completions"
guard let url = URL(string: endpoint) else {
throw NSError(domain: "CommandMode", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])
}
-
+
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.httpBody = try JSONSerialization.data(withJSONObject: body)
-
+
// Retry logic for transient network errors (DNS resolution, connection cold start)
var lastError: Error?
for attempt in 1...3 {
@@ -823,11 +838,12 @@ final class CommandModeService: ObservableObject {
} else {
return try await processNonStreamingLLMResponse(request: request)
}
- } catch let error as URLError where error.code == .notConnectedToInternet ||
- error.code == .timedOut ||
- error.code == .networkConnectionLost ||
- error.code == .cannotFindHost ||
- error.code == .cannotConnectToHost {
+ } catch let error as URLError where error.code == .notConnectedToInternet ||
+ error.code == .timedOut ||
+ error.code == .networkConnectionLost ||
+ error.code == .cannotFindHost ||
+ error.code == .cannotConnectToHost
+ {
lastError = error
if attempt < 3 {
// Wait before retry (exponential backoff: 200ms, 400ms)
@@ -835,39 +851,46 @@ final class CommandModeService: ObservableObject {
continue
}
} catch {
- throw error // Non-retryable error
+ throw error // Non-retryable error
}
}
- throw lastError ?? NSError(domain: "CommandMode", code: -1, userInfo: [NSLocalizedDescriptionKey: "Network request failed after retries"])
+ throw lastError ?? NSError(
+ domain: "CommandMode",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Network request failed after retries"]
+ )
}
-
+
// MARK: - Non-Streaming Response
+
private func processNonStreamingLLMResponse(request: URLRequest) async throws -> LLMResponse {
let (data, response) = try await URLSession.shared.data(for: request)
-
+
if let http = response as? HTTPURLResponse, http.statusCode >= 400 {
let err = String(data: data, encoding: .utf8) ?? "Unknown error"
throw NSError(domain: "CommandMode", code: http.statusCode, userInfo: [NSLocalizedDescriptionKey: err])
}
-
+
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let choices = json["choices"] as? [[String: Any]],
let choice = choices.first,
- let message = choice["message"] as? [String: Any] else {
+ let message = choice["message"] as? [String: Any]
+ else {
throw NSError(domain: "CommandMode", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid response"])
}
-
+
return parseMessageResponse(message)
}
-
+
// MARK: - Streaming Response with Real-time UI Updates
+
private func processStreamingLLMResponse(request: URLRequest) async throws -> LLMResponse {
streamingText = ""
streamingBuffer = []
lastUIUpdate = CFAbsoluteTimeGetCurrent()
-
+
let (bytes, response) = try await URLSession.shared.bytes(for: request)
-
+
if let http = response as? HTTPURLResponse, http.statusCode >= 400 {
var errorData = Data()
for try await byte in bytes {
@@ -876,70 +899,71 @@ final class CommandModeService: ObservableObject {
let errText = String(data: errorData, encoding: .utf8) ?? "Unknown error"
throw NSError(domain: "CommandMode", code: http.statusCode, userInfo: [NSLocalizedDescriptionKey: errText])
}
-
+
var toolCallId: String?
var toolCallName: String?
var toolCallArguments = ""
-
+
// Use efficient line-based iteration instead of byte-by-byte
for try await rawLine in bytes.lines {
let line = rawLine.trimmingCharacters(in: .whitespaces)
-
+
guard line.hasPrefix("data:") else { continue }
-
+
var jsonString = String(line.dropFirst(5))
if jsonString.hasPrefix(" ") {
jsonString = String(jsonString.dropFirst(1))
}
-
+
if jsonString.trimmingCharacters(in: .whitespaces) == "[DONE]" {
continue
}
-
+
guard let jsonData = jsonString.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any],
let choices = json["choices"] as? [[String: Any]],
let firstChoice = choices.first,
- let delta = firstChoice["delta"] as? [String: Any] else {
+ let delta = firstChoice["delta"] as? [String: Any]
+ else {
continue
}
-
+
// Handle text content - use buffer to avoid O(n²) string concat
if let content = delta["content"] as? String {
streamingBuffer.append(content)
-
+
// Adaptive throttle: slower updates as content grows (reduces SwiftUI layout overhead)
let bufferLength = streamingBuffer.count
let updateInterval: CFAbsoluteTime
if bufferLength < 50 {
- updateInterval = 0.016 // 60fps for first ~50 tokens
+ updateInterval = 0.016 // 60fps for first ~50 tokens
} else if bufferLength < 200 {
- updateInterval = 0.033 // 30fps for medium content
+ updateInterval = 0.033 // 30fps for medium content
} else {
- updateInterval = 0.066 // 15fps for long content
+ updateInterval = 0.066 // 15fps for long content
}
-
+
let now = CFAbsoluteTimeGetCurrent()
if now - lastUIUpdate >= updateInterval {
lastUIUpdate = now
let fullContent = streamingBuffer.joined()
streamingText = fullContent
-
+
// Push to notch for real-time display
if enableNotchOutput {
NotchContentState.shared.updateCommandStreamingText(fullContent)
}
}
}
-
+
// Handle tool calls (streamed in parts)
if let toolCalls = delta["tool_calls"] as? [[String: Any]],
- let toolCall = toolCalls.first {
-
+ let toolCall = toolCalls.first
+ {
if let id = toolCall["id"] as? String {
toolCallId = id
}
-
+
if let function = toolCall["function"] as? [String: Any] {
if let name = function["name"] as? String {
toolCallName = name
@@ -950,7 +974,7 @@ final class CommandModeService: ObservableObject {
}
}
}
-
+
// Final update - join buffer once at the end
let fullContent = streamingBuffer.joined()
if !fullContent.isEmpty {
@@ -959,47 +983,49 @@ final class CommandModeService: ObservableObject {
NotchContentState.shared.updateCommandStreamingText(fullContent)
}
}
-
+
// 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
-
+ try? await Task.sleep(nanoseconds: 50_000_000) // 50ms
+
+ streamingText = "" // Clear streaming text when done
+ streamingBuffer = [] // Clear buffer
+
// Clear notch streaming text as well
if enableNotchOutput {
NotchContentState.shared.updateCommandStreamingText("")
}
-
+
// If we got a tool call, parse it
if let name = toolCallName, name == "execute_terminal_command",
let argsData = toolCallArguments.data(using: .utf8),
- let args = try? JSONSerialization.jsonObject(with: argsData) as? [String: Any] {
-
+ let args = try? JSONSerialization.jsonObject(with: argsData) as? [String: Any]
+ {
let command = args["command"] as? String ?? ""
let workDir = args["workingDirectory"] as? String
let purpose = args["purpose"] as? String
let callId = toolCallId ?? "call_\(UUID().uuidString.prefix(8))"
-
+
return LLMResponse(
content: fullContent,
toolCall: LLMResponse.ToolCallData(
id: callId,
command: command,
- workingDirectory: workDir?.isEmpty == true ? nil : workDir,
+ workingDirectory: workDir?
+ .isEmpty == true ? nil : workDir,
purpose: purpose
)
)
}
-
+
// Text response only
return LLMResponse(
content: fullContent.isEmpty ? "I couldn't understand that." : fullContent,
toolCall: nil
)
}
-
+
// MARK: - Parse Message Helper
+
private func parseMessageResponse(_ message: [String: Any]) -> LLMResponse {
// Check for tool calls
if let toolCalls = message["tool_calls"] as? [[String: Any]],
@@ -1009,24 +1035,25 @@ final class CommandModeService: ObservableObject {
name == "execute_terminal_command",
let argsString = function["arguments"] as? String,
let argsData = argsString.data(using: .utf8),
- let args = try? JSONSerialization.jsonObject(with: argsData) as? [String: Any] {
-
+ let args = try? JSONSerialization.jsonObject(with: argsData) as? [String: Any]
+ {
let command = args["command"] as? String ?? ""
let workDir = args["workingDirectory"] as? String
let purpose = args["purpose"] as? String
let callId = toolCall["id"] as? String ?? "call_\(UUID().uuidString.prefix(8))"
-
+
return LLMResponse(
content: message["content"] as? String ?? "",
toolCall: LLMResponse.ToolCallData(
id: callId,
command: command,
- workingDirectory: workDir?.isEmpty == true ? nil : workDir,
+ workingDirectory: workDir?
+ .isEmpty == true ? nil : workDir,
purpose: purpose
)
)
}
-
+
// Text response only
return LLMResponse(
content: message["content"] as? String ?? "I couldn't understand that.",
@@ -1034,4 +1061,3 @@ final class CommandModeService: ObservableObject {
)
}
}
-
diff --git a/Sources/Fluid/Services/DebugLogger.swift b/Sources/Fluid/Services/DebugLogger.swift
index 09ac3bcc..e7c063a9 100644
--- a/Sources/Fluid/Services/DebugLogger.swift
+++ b/Sources/Fluid/Services/DebugLogger.swift
@@ -1,14 +1,14 @@
+import Combine
import Foundation
import SwiftUI
-import Combine
class DebugLogger: ObservableObject {
static let shared = DebugLogger()
-
+
@Published var logs: [LogEntry] = []
private let maxLogs = 1000 // Keep last 1000 log entries
private let queue = DispatchQueue(label: "debug.logger", qos: .utility)
-
+
// IMPORTANT: Cached setting to avoid circular dependency with SettingsStore
// During SettingsStore.init(), if an error is logged, accessing SettingsStore.shared
// would cause a recursive dispatch_once deadlock. We use a cached value instead.
@@ -23,7 +23,7 @@ class DebugLogger: ObservableObject {
_loggingEnabledCache = enabled
return enabled
}
-
+
private static let logFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss.SSS"
@@ -31,7 +31,7 @@ class DebugLogger: ObservableObject {
formatter.timeZone = TimeZone.current
return formatter
}()
-
+
struct LogEntry: Identifiable, Equatable {
let id = UUID()
let timestamp: Date
@@ -48,13 +48,13 @@ class DebugLogger: ObservableObject {
self.formattedTimestamp = formattedTimestamp
}
}
-
+
enum LogLevel: String, CaseIterable {
case info = "INFO"
case warning = "WARN"
case error = "ERROR"
case debug = "DEBUG"
-
+
var color: Color {
switch self {
case .info: return .blue
@@ -64,14 +64,14 @@ class DebugLogger: ObservableObject {
}
}
}
-
+
private init() {}
-
+
/// Refresh the cached logging setting (call after SettingsStore is fully initialized)
func refreshLoggingEnabled() {
_loggingEnabledCache = UserDefaults.standard.bool(forKey: "EnableDebugLogs")
}
-
+
func log(_ message: String, level: LogLevel = .info, source: String = "App") {
let loggingEnabled = self.loggingEnabled
@@ -79,7 +79,13 @@ class DebugLogger: ObservableObject {
let timestamp = Date()
let timestampString = Self.logFormatter.string(from: timestamp)
let entry: LogEntry? = loggingEnabled
- ? LogEntry(timestamp: timestamp, level: level, message: message, source: source, formattedTimestamp: timestampString)
+ ? LogEntry(
+ timestamp: timestamp,
+ level: level,
+ message: message,
+ source: source,
+ formattedTimestamp: timestampString
+ )
: nil
let formattedLine = entry.map(self.formatLogEntry)
?? self.formatLogLine(timestamp: timestampString, level: level, source: source, message: message)
@@ -106,21 +112,26 @@ class DebugLogger: ObservableObject {
}
}
}
-
+
func clear() {
DispatchQueue.main.async {
self.logs.removeAll()
}
}
-
+
func exportLogs() -> String {
return logs.map { entry in
- formatLogEntry(entry)
+ self.formatLogEntry(entry)
}.joined(separator: "\n")
}
private func formatLogEntry(_ entry: LogEntry) -> String {
- formatLogLine(timestamp: entry.formattedTimestamp, level: entry.level, source: entry.source, message: entry.message)
+ formatLogLine(
+ timestamp: entry.formattedTimestamp,
+ level: entry.level,
+ source: entry.source,
+ message: entry.message
+ )
}
private func formatLogLine(timestamp: String, level: LogLevel, source: String, message: String) -> String {
@@ -133,16 +144,16 @@ extension DebugLogger {
func info(_ message: String, source: String = "App") {
log(message, level: .info, source: source)
}
-
+
func warning(_ message: String, source: String = "App") {
log(message, level: .warning, source: source)
}
-
+
func error(_ message: String, source: String = "App") {
log(message, level: .error, source: source)
}
-
+
func debug(_ message: String, source: String = "App") {
log(message, level: .debug, source: source)
}
-}
\ No newline at end of file
+}
diff --git a/Sources/Fluid/Services/FileLogger.swift b/Sources/Fluid/Services/FileLogger.swift
index c52f58f2..03e8fb0e 100644
--- a/Sources/Fluid/Services/FileLogger.swift
+++ b/Sources/Fluid/Services/FileLogger.swift
@@ -1,8 +1,7 @@
import Foundation
/// A lightweight file-backed logger that mirrors in-app debug logs to disk for diagnostics.
-final class FileLogger
-{
+final class FileLogger {
static let shared = FileLogger()
private let queue = DispatchQueue(label: "file.logger.queue", qos: .utility)
@@ -13,76 +12,61 @@ final class FileLogger
private let maxLogFileSize: UInt64 = 1 * 1024 * 1024 // 1 MB limit per log file
private let maxLogFileAge: TimeInterval = 72 * 60 * 60 // Rotate every 72 hours
- private init()
- {
- let baseDirectory = fileManager.urls(for: .libraryDirectory, in: .userDomainMask).first ?? URL(fileURLWithPath: NSTemporaryDirectory())
+ private init() {
+ let baseDirectory = 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)
queue.sync {
- createLogDirectoryIfNeeded()
- rotateIfNeeded(force: false)
+ self.createLogDirectoryIfNeeded()
+ self.rotateIfNeeded(force: false)
}
}
- func append(line: String)
- {
+ func append(line: String) {
queue.async { [weak self] in
guard let self = self else { return }
self.createLogDirectoryIfNeeded()
self.rotateIfNeeded(force: false)
let data = (line + "\n").data(using: .utf8) ?? Data()
- if !self.fileManager.fileExists(atPath: self.logFileURL.path)
- {
+ if !self.fileManager.fileExists(atPath: self.logFileURL.path) {
self.fileManager.createFile(atPath: self.logFileURL.path, contents: data)
- }
- else if let handle = try? FileHandle(forWritingTo: self.logFileURL)
- {
+ } else if let handle = try? FileHandle(forWritingTo: self.logFileURL) {
do {
try handle.seekToEnd()
try handle.write(contentsOf: data)
try handle.close()
- }
- catch
- {
+ } catch {
try? handle.close()
}
}
}
}
- func currentLogFileURL() -> URL
- {
+ func currentLogFileURL() -> URL {
return logFileURL
}
// MARK: - Private helpers
- private func createLogDirectoryIfNeeded()
- {
+ private func createLogDirectoryIfNeeded() {
guard !fileManager.fileExists(atPath: logDirectory.path) else { return }
- do
- {
+ do {
try fileManager.createDirectory(at: logDirectory, withIntermediateDirectories: true)
- }
- catch
- {
+ } catch {
// If the directory cannot be created, fall back to /tmp
}
}
- private func rotateIfNeeded(force: Bool)
- {
+ private func rotateIfNeeded(force: Bool) {
guard fileManager.fileExists(atPath: logFileURL.path) else { return }
let shouldRotate: Bool
- if force
- {
+ if force {
shouldRotate = true
- }
- else
- {
+ } else {
let attributes = try? fileManager.attributesOfItem(atPath: logFileURL.path)
let size = attributes?[.size] as? UInt64 ?? 0
let modifiedDate = attributes?[.modificationDate] as? Date ?? Date()
@@ -93,8 +77,7 @@ final class FileLogger
guard shouldRotate else { return }
// Remove existing backup if present
- if fileManager.fileExists(atPath: backupLogURL.path)
- {
+ if fileManager.fileExists(atPath: backupLogURL.path) {
try? fileManager.removeItem(at: backupLogURL)
}
diff --git a/Sources/Fluid/Services/FluidAudioProvider.swift b/Sources/Fluid/Services/FluidAudioProvider.swift
index 3799efe5..112f64b8 100644
--- a/Sources/Fluid/Services/FluidAudioProvider.swift
+++ b/Sources/Fluid/Services/FluidAudioProvider.swift
@@ -5,70 +5,72 @@ import FluidAudio
/// TranscriptionProvider implementation using FluidAudio (optimized for Apple Silicon)
/// This wraps the existing FluidAudio-based ASR for use on Apple Silicon Macs.
final class FluidAudioProvider: TranscriptionProvider {
-
let name = "FluidAudio (Apple Silicon Optimized)"
-
+
/// Whether this provider is supported on the current system.
/// FluidAudio is optimized for Apple Silicon, but may still function on Intel.
var isAvailable: Bool {
true
}
-
+
private var asrManager: AsrManager?
private(set) var isReady: Bool = false
-
+
func prepare(progressHandler: ((Double) -> Void)? = nil) async throws {
guard isReady == false else { return }
-
+
DebugLogger.shared.info("FluidAudioProvider: Starting model preparation", source: "FluidAudioProvider")
-
+
// Download and load models
let models = try await AsrModels.downloadAndLoad()
-
+
// Initialize AsrManager
let manager = AsrManager(config: ASRConfig.default)
try await manager.initialize(models: models)
- self.asrManager = manager
-
+ asrManager = manager
+
isReady = true
DebugLogger.shared.info("FluidAudioProvider: Models ready", source: "FluidAudioProvider")
}
-
+
func transcribe(_ samples: [Float]) async throws -> ASRTranscriptionResult {
guard let manager = asrManager else {
- throw NSError(domain: "FluidAudioProvider", code: -1,
- userInfo: [NSLocalizedDescriptionKey: "ASR manager not initialized"])
+ throw NSError(
+ domain: "FluidAudioProvider",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "ASR manager not initialized"]
+ )
}
-
+
let result = try await manager.transcribe(samples, source: AudioSource.microphone)
return ASRTranscriptionResult(text: result.text, confidence: result.confidence)
}
-
+
func modelsExistOnDisk() -> Bool {
let baseCacheDir = AsrModels.defaultCacheDirectory().deletingLastPathComponent()
let v3CacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v3-coreml")
return FileManager.default.fileExists(atPath: v3CacheDir.path)
}
-
+
func clearCache() async throws {
let baseCacheDir = AsrModels.defaultCacheDirectory().deletingLastPathComponent()
-
+
// Clear v2 cache
let v2CacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v2-coreml")
if FileManager.default.fileExists(atPath: v2CacheDir.path) {
try FileManager.default.removeItem(at: v2CacheDir)
}
-
+
// Clear v3 cache
let v3CacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v3-coreml")
if FileManager.default.fileExists(atPath: v3CacheDir.path) {
try FileManager.default.removeItem(at: v3CacheDir)
}
-
+
isReady = false
asrManager = nil
}
-
+
/// Provides direct access to the underlying AsrManager for advanced use cases
/// (e.g., MeetingTranscriptionService sharing)
var underlyingManager: AsrManager? {
@@ -81,13 +83,21 @@ final class FluidAudioProvider: TranscriptionProvider {
let name = "FluidAudio (Apple Silicon ONLY)"
var isAvailable: Bool { false }
var isReady: Bool { false }
-
+
func prepare(progressHandler: ((Double) -> Void)?) async throws {
- throw NSError(domain: "FluidAudioProvider", code: -1, userInfo: [NSLocalizedDescriptionKey: "FluidAudio is not supported on Intel Macs"])
+ throw NSError(
+ domain: "FluidAudioProvider",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "FluidAudio is not supported on Intel Macs"]
+ )
}
-
+
func transcribe(_ samples: [Float]) async throws -> ASRTranscriptionResult {
- throw NSError(domain: "FluidAudioProvider", code: -1, userInfo: [NSLocalizedDescriptionKey: "FluidAudio is not supported on Intel Macs"])
+ throw NSError(
+ domain: "FluidAudioProvider",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "FluidAudio is not supported on Intel Macs"]
+ )
}
}
#endif
diff --git a/Sources/Fluid/Services/GlobalHotkeyManager.swift b/Sources/Fluid/Services/GlobalHotkeyManager.swift
index ffa31642..1391cf60 100644
--- a/Sources/Fluid/Services/GlobalHotkeyManager.swift
+++ b/Sources/Fluid/Services/GlobalHotkeyManager.swift
@@ -1,11 +1,10 @@
-import Foundation
import AppKit
+import Foundation
@MainActor
-final class GlobalHotkeyManager: NSObject
-{
- nonisolated(unsafe) private var eventTap: CFMachPort?
- nonisolated(unsafe) private var runLoopSource: CFRunLoopSource?
+final class GlobalHotkeyManager: NSObject {
+ private nonisolated(unsafe) var eventTap: CFMachPort?
+ private nonisolated(unsafe) var runLoopSource: CFRunLoopSource?
private let asrService: ASRService
private var shortcut: HotkeyShortcut
private var commandModeShortcut: HotkeyShortcut
@@ -16,15 +15,15 @@ final class GlobalHotkeyManager: NSObject
private var stopAndProcessCallback: (() async -> Void)?
private var commandModeCallback: (() async -> Void)?
private var rewriteModeCallback: (() async -> Void)?
- private var cancelCallback: (() -> Bool)? // Returns true if handled
+ private var cancelCallback: (() -> Bool)? // Returns true if handled
private var pressAndHoldMode: Bool = SettingsStore.shared.pressAndHoldMode
private var isKeyPressed = false
private var isCommandModeKeyPressed = false
private var isRewriteKeyPressed = false
-
+
// Busy flag to prevent race conditions during stop processing
private var isProcessingStop = false
-
+
private var isInitialized = false
private var initializationTask: Task<Void, Never>?
private var healthCheckTask: Task<Void, Never>?
@@ -43,8 +42,7 @@ final class GlobalHotkeyManager: NSObject
stopAndProcessCallback: (() async -> Void)? = nil,
commandModeCallback: (() async -> Void)? = nil,
rewriteModeCallback: (() async -> Void)? = nil
- )
- {
+ ) {
self.asrService = asrService
self.shortcut = shortcut
self.commandModeShortcut = commandModeShortcut
@@ -56,91 +54,91 @@ final class GlobalHotkeyManager: NSObject
self.commandModeCallback = commandModeCallback
self.rewriteModeCallback = rewriteModeCallback
super.init()
-
+
initializeWithDelay()
}
-
+
private func initializeWithDelay() {
DebugLogger.shared.debug("Starting delayed initialization...", source: "GlobalHotkeyManager")
-
+
initializationTask = Task {
try? await Task.sleep(nanoseconds: 1_500_000_000) // 1.5 second delay
-
+
await MainActor.run {
self.setupGlobalHotkeyWithRetry()
}
}
}
- func setStopAndProcessCallback(_ callback: @escaping () async -> Void)
- {
- self.stopAndProcessCallback = callback
+ func setStopAndProcessCallback(_ callback: @escaping () async -> Void) {
+ stopAndProcessCallback = callback
}
-
- func setCommandModeCallback(_ callback: @escaping () async -> Void)
- {
- self.commandModeCallback = callback
+
+ func setCommandModeCallback(_ callback: @escaping () async -> Void) {
+ commandModeCallback = callback
}
-
- func updateShortcut(_ newShortcut: HotkeyShortcut)
- {
- self.shortcut = newShortcut
+
+ func updateShortcut(_ newShortcut: HotkeyShortcut) {
+ shortcut = newShortcut
DebugLogger.shared.info("Updated transcription hotkey", source: "GlobalHotkeyManager")
}
-
- func updateCommandModeShortcut(_ newShortcut: HotkeyShortcut)
- {
- self.commandModeShortcut = newShortcut
+
+ func updateCommandModeShortcut(_ newShortcut: HotkeyShortcut) {
+ commandModeShortcut = newShortcut
DebugLogger.shared.info("Updated command mode hotkey", source: "GlobalHotkeyManager")
}
-
- func setRewriteModeCallback(_ callback: @escaping () async -> Void)
- {
- self.rewriteModeCallback = callback
+
+ func setRewriteModeCallback(_ callback: @escaping () async -> Void) {
+ rewriteModeCallback = callback
}
-
- func updateRewriteModeShortcut(_ newShortcut: HotkeyShortcut)
- {
- self.rewriteModeShortcut = newShortcut
+
+ func updateRewriteModeShortcut(_ newShortcut: HotkeyShortcut) {
+ rewriteModeShortcut = newShortcut
DebugLogger.shared.info("Updated rewrite mode hotkey", source: "GlobalHotkeyManager")
}
-
- func updateCommandModeShortcutEnabled(_ enabled: Bool)
- {
+
+ func updateCommandModeShortcutEnabled(_ enabled: Bool) {
commandModeShortcutEnabled = enabled
if !enabled {
isCommandModeKeyPressed = false
}
- DebugLogger.shared.info("Command mode shortcut \(enabled ? "enabled" : "disabled")", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Command mode shortcut \(enabled ? "enabled" : "disabled")",
+ source: "GlobalHotkeyManager"
+ )
}
-
- func updateRewriteModeShortcutEnabled(_ enabled: Bool)
- {
+
+ func updateRewriteModeShortcutEnabled(_ enabled: Bool) {
rewriteModeShortcutEnabled = enabled
if !enabled {
isRewriteKeyPressed = false
}
- DebugLogger.shared.info("Rewrite mode shortcut \(enabled ? "enabled" : "disabled")", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Rewrite mode shortcut \(enabled ? "enabled" : "disabled")",
+ source: "GlobalHotkeyManager"
+ )
}
-
- func setCancelCallback(_ callback: @escaping () -> Bool)
- {
- self.cancelCallback = callback
+
+ func setCancelCallback(_ callback: @escaping () -> Bool) {
+ cancelCallback = callback
}
private func setupGlobalHotkeyWithRetry() {
for attempt in 1...maxRetryAttempts {
DebugLogger.shared.debug("Setup attempt \(attempt)/\(maxRetryAttempts)", source: "GlobalHotkeyManager")
-
+
if setupGlobalHotkey() {
isInitialized = true
DebugLogger.shared.info("Successfully initialized on attempt \(attempt)", source: "GlobalHotkeyManager")
startHealthCheckTimer()
return
}
-
+
if attempt < maxRetryAttempts {
- DebugLogger.shared.warning("Attempt \(attempt) failed, retrying in \(self.retryDelay) seconds...", source: "GlobalHotkeyManager")
+ DebugLogger.shared.warning(
+ "Attempt \(attempt) failed, retrying in \(retryDelay) seconds...",
+ source: "GlobalHotkeyManager"
+ )
Task { [weak self] in
try? await Task.sleep(nanoseconds: UInt64((self?.retryDelay ?? 0.5) * 1_000_000_000))
await MainActor.run { [weak self] in
@@ -150,15 +148,17 @@ final class GlobalHotkeyManager: NSObject
return
}
}
-
- DebugLogger.shared.error("Failed to initialize after \(maxRetryAttempts) attempts", source: "GlobalHotkeyManager")
+
+ DebugLogger.shared.error(
+ "Failed to initialize after \(maxRetryAttempts) attempts",
+ source: "GlobalHotkeyManager"
+ )
}
-
+
@discardableResult
- private func setupGlobalHotkey() -> Bool
- {
+ private func setupGlobalHotkey() -> Bool {
cleanupEventTap()
-
+
if !AXIsProcessTrusted() {
if UserDefaults.standard.bool(forKey: "enableDebugLogs") {
print("[GlobalHotkeyManager] Accessibility permissions not granted")
@@ -167,22 +167,23 @@ final class GlobalHotkeyManager: NSObject
}
let eventMask = (1 << CGEventType.keyDown.rawValue)
- | (1 << CGEventType.keyUp.rawValue)
- | (1 << CGEventType.flagsChanged.rawValue)
+ | (1 << CGEventType.keyUp.rawValue)
+ | (1 << CGEventType.flagsChanged.rawValue)
eventTap = CGEvent.tapCreate(
tap: .cgSessionEventTap,
place: .headInsertEventTap,
options: .defaultTap,
eventsOfInterest: CGEventMask(eventMask),
- callback: { (proxy, type, event, refcon) -> Unmanaged<CGEvent>? in
+ callback: { proxy, type, event, refcon -> Unmanaged<CGEvent>? in
guard let refcon = refcon else { return Unmanaged.passUnretained(event) }
- let manager = Unmanaged<GlobalHotkeyManager>.fromOpaque(refcon).takeUnretainedValue()
+ let manager = Unmanaged<GlobalHotkeyManager>.fromOpaque(refcon)
+ .takeUnretainedValue()
return manager.handleKeyEvent(proxy: proxy, type: type, event: event)
},
userInfo: Unmanaged.passUnretained(self).toOpaque()
)
-
+
guard let tap = eventTap else {
if UserDefaults.standard.bool(forKey: "enableDebugLogs") {
print("[GlobalHotkeyManager] Failed to create CGEvent tap")
@@ -197,10 +198,10 @@ final class GlobalHotkeyManager: NSObject
}
return false
}
-
+
CFRunLoopAddSource(CFRunLoopGetMain(), source, .commonModes)
CGEvent.tapEnable(tap: tap, enable: true)
-
+
if !isEventTapEnabled() {
if UserDefaults.standard.bool(forKey: "enableDebugLogs") {
print("[GlobalHotkeyManager] Event tap could not be enabled")
@@ -208,28 +209,27 @@ final class GlobalHotkeyManager: NSObject
cleanupEventTap()
return false
}
-
+
if UserDefaults.standard.bool(forKey: "enableDebugLogs") {
print("[GlobalHotkeyManager] Event tap successfully created and enabled")
}
return true
}
-
- nonisolated private func cleanupEventTap() {
+
+ private nonisolated func cleanupEventTap() {
if let tap = eventTap {
CGEvent.tapEnable(tap: tap, enable: false)
}
-
+
if let source = runLoopSource {
CFRunLoopRemoveSource(CFRunLoopGetMain(), source, .commonModes)
}
-
+
eventTap = nil
runLoopSource = nil
}
- private func handleKeyEvent(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent) -> Unmanaged<CGEvent>?
- {
+ private func handleKeyEvent(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent) -> Unmanaged<CGEvent>? {
let keyCode = UInt16(event.getIntegerValueField(.keyboardEventKeycode))
let flags = event.flags
@@ -240,13 +240,12 @@ final class GlobalHotkeyManager: NSObject
if flags.contains(.maskControl) { eventModifiers.insert(.control) }
if flags.contains(.maskShift) { eventModifiers.insert(.shift) }
- switch type
- {
+ switch type {
case .keyDown:
// Check Escape key first (keyCode 53) - cancels recording and closes mode views
- if keyCode == 53 && eventModifiers.isEmpty {
+ if keyCode == 53, eventModifiers.isEmpty {
var handled = false
-
+
if asrService.isRunning {
DebugLogger.shared.info("Escape pressed - cancelling recording", source: "GlobalHotkeyManager")
Task { @MainActor in
@@ -254,77 +253,94 @@ final class GlobalHotkeyManager: NSObject
}
handled = true
}
-
+
// Trigger cancel callback to close mode views / reset state
if let callback = cancelCallback, callback() {
DebugLogger.shared.info("Escape pressed - cancel callback handled", source: "GlobalHotkeyManager")
handled = true
}
-
+
if handled {
- return nil // Consume event only if we did something
+ return nil // Consume event only if we did something
}
}
-
+
// Check command mode hotkey first
- if commandModeShortcutEnabled && matchesCommandModeShortcut(keyCode: keyCode, modifiers: eventModifiers)
- {
+ if commandModeShortcutEnabled, matchesCommandModeShortcut(
+ keyCode: keyCode,
+ modifiers: eventModifiers
+ ) {
if pressAndHoldMode {
// Press and hold: start on keyDown, stop on keyUp
if !isCommandModeKeyPressed {
isCommandModeKeyPressed = true
- DebugLogger.shared.info("Command mode shortcut pressed (hold mode) - starting", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Command mode shortcut pressed (hold mode) - starting",
+ source: "GlobalHotkeyManager"
+ )
triggerCommandMode()
}
} else {
// Toggle mode: press to start, press again to stop
if asrService.isRunning {
- DebugLogger.shared.info("Command mode shortcut pressed while recording - stopping", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Command mode shortcut pressed while recording - stopping",
+ source: "GlobalHotkeyManager"
+ )
stopRecordingIfNeeded()
} else {
- DebugLogger.shared.info("Command mode shortcut triggered - starting", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Command mode shortcut triggered - starting",
+ source: "GlobalHotkeyManager"
+ )
triggerCommandMode()
}
}
return nil
}
-
+
// Check dedicated rewrite mode hotkey
- if rewriteModeShortcutEnabled && matchesRewriteModeShortcut(keyCode: keyCode, modifiers: eventModifiers)
- {
+ if rewriteModeShortcutEnabled, matchesRewriteModeShortcut(
+ keyCode: keyCode,
+ modifiers: eventModifiers
+ ) {
if pressAndHoldMode {
// Press and hold: start on keyDown, stop on keyUp
if !isRewriteKeyPressed {
isRewriteKeyPressed = true
- DebugLogger.shared.info("Rewrite mode shortcut pressed (hold mode) - starting", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Rewrite mode shortcut pressed (hold mode) - starting",
+ source: "GlobalHotkeyManager"
+ )
triggerRewriteMode()
}
} else {
// Toggle mode: press to start, press again to stop
if asrService.isRunning {
- DebugLogger.shared.info("Rewrite mode shortcut pressed while recording - stopping", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Rewrite mode shortcut pressed while recording - stopping",
+ source: "GlobalHotkeyManager"
+ )
stopRecordingIfNeeded()
} else {
- DebugLogger.shared.info("Rewrite mode shortcut triggered - starting", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Rewrite mode shortcut triggered - starting",
+ source: "GlobalHotkeyManager"
+ )
triggerRewriteMode()
}
}
return nil
}
-
+
// Then check transcription hotkey
- if matchesShortcut(keyCode: keyCode, modifiers: eventModifiers)
- {
- if pressAndHoldMode
- {
- if !isKeyPressed
- {
+ if matchesShortcut(keyCode: keyCode, modifiers: eventModifiers) {
+ if pressAndHoldMode {
+ if !isKeyPressed {
isKeyPressed = true
startRecordingIfNeeded()
}
- }
- else
- {
+ } else {
toggleRecording()
}
return nil
@@ -332,26 +348,42 @@ final class GlobalHotkeyManager: NSObject
case .keyUp:
// Command mode key up (press and hold mode)
- if commandModeShortcutEnabled && pressAndHoldMode && isCommandModeKeyPressed && matchesCommandModeShortcut(keyCode: keyCode, modifiers: eventModifiers)
+ if commandModeShortcutEnabled, pressAndHoldMode, isCommandModeKeyPressed,
+ matchesCommandModeShortcut(
+ keyCode: keyCode,
+ modifiers: eventModifiers
+ )
{
isCommandModeKeyPressed = false
- DebugLogger.shared.info("Command mode shortcut released (hold mode) - stopping", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Command mode shortcut released (hold mode) - stopping",
+ source: "GlobalHotkeyManager"
+ )
stopRecordingIfNeeded()
return nil
}
-
+
// Rewrite mode key up (press and hold mode)
- if rewriteModeShortcutEnabled && pressAndHoldMode && isRewriteKeyPressed && matchesRewriteModeShortcut(keyCode: keyCode, modifiers: eventModifiers)
+ if rewriteModeShortcutEnabled, pressAndHoldMode, isRewriteKeyPressed,
+ matchesRewriteModeShortcut(
+ keyCode: keyCode,
+ modifiers: eventModifiers
+ )
{
isRewriteKeyPressed = false
- DebugLogger.shared.info("Rewrite mode shortcut released (hold mode) - stopping", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Rewrite mode shortcut released (hold mode) - stopping",
+ source: "GlobalHotkeyManager"
+ )
stopRecordingIfNeeded()
return nil
}
-
+
// Transcription key up
- if pressAndHoldMode && isKeyPressed && matchesShortcut(keyCode: keyCode, modifiers: eventModifiers)
- {
+ if pressAndHoldMode, isKeyPressed, matchesShortcut(
+ keyCode: keyCode,
+ modifiers: eventModifiers
+ ) {
isKeyPressed = false
stopRecordingIfNeeded()
return nil
@@ -363,62 +395,86 @@ final class GlobalHotkeyManager: NSObject
|| flags.contains(.maskAlternate)
|| flags.contains(.maskControl)
|| flags.contains(.maskShift)
-
+
// Check command mode shortcut (if it's a modifier-only shortcut)
- if commandModeShortcutEnabled && commandModeShortcut.modifierFlags.isEmpty && keyCode == commandModeShortcut.keyCode
+ if commandModeShortcutEnabled, commandModeShortcut.modifierFlags.isEmpty,
+ keyCode == commandModeShortcut.keyCode
{
- if isModifierPressed
- {
+ if isModifierPressed {
if pressAndHoldMode {
if !isCommandModeKeyPressed {
isCommandModeKeyPressed = true
- DebugLogger.shared.info("Command mode modifier pressed (hold mode) - starting", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Command mode modifier pressed (hold mode) - starting",
+ source: "GlobalHotkeyManager"
+ )
triggerCommandMode()
}
} else {
// Toggle mode
if asrService.isRunning {
- DebugLogger.shared.info("Command mode modifier pressed while recording - stopping", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Command mode modifier pressed while recording - stopping",
+ source: "GlobalHotkeyManager"
+ )
stopRecordingIfNeeded()
} else {
- DebugLogger.shared.info("Command mode modifier pressed - starting", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Command mode modifier pressed - starting",
+ source: "GlobalHotkeyManager"
+ )
triggerCommandMode()
}
}
- } else if pressAndHoldMode && isCommandModeKeyPressed {
+ } else if pressAndHoldMode, isCommandModeKeyPressed {
// Key released in press-and-hold mode
isCommandModeKeyPressed = false
- DebugLogger.shared.info("Command mode modifier released (hold mode) - stopping", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Command mode modifier released (hold mode) - stopping",
+ source: "GlobalHotkeyManager"
+ )
stopRecordingIfNeeded()
}
return nil
}
-
+
// Check rewrite mode shortcut (if it's a modifier-only shortcut)
- if rewriteModeShortcutEnabled && rewriteModeShortcut.modifierFlags.isEmpty && keyCode == rewriteModeShortcut.keyCode
+ if rewriteModeShortcutEnabled, rewriteModeShortcut.modifierFlags.isEmpty,
+ keyCode == rewriteModeShortcut.keyCode
{
- if isModifierPressed
- {
+ if isModifierPressed {
if pressAndHoldMode {
if !isRewriteKeyPressed {
isRewriteKeyPressed = true
- DebugLogger.shared.info("Rewrite mode modifier pressed (hold mode) - starting", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Rewrite mode modifier pressed (hold mode) - starting",
+ source: "GlobalHotkeyManager"
+ )
triggerRewriteMode()
}
} else {
// Toggle mode
if asrService.isRunning {
- DebugLogger.shared.info("Rewrite mode modifier pressed while recording - stopping", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Rewrite mode modifier pressed while recording - stopping",
+ source: "GlobalHotkeyManager"
+ )
stopRecordingIfNeeded()
} else {
- DebugLogger.shared.info("Rewrite mode modifier pressed - starting", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Rewrite mode modifier pressed - starting",
+ source: "GlobalHotkeyManager"
+ )
triggerRewriteMode()
}
}
- } else if pressAndHoldMode && isRewriteKeyPressed {
+ } else if pressAndHoldMode, isRewriteKeyPressed {
// Key released in press-and-hold mode
isRewriteKeyPressed = false
- DebugLogger.shared.info("Rewrite mode modifier released (hold mode) - stopping", source: "GlobalHotkeyManager")
+ DebugLogger.shared.info(
+ "Rewrite mode modifier released (hold mode) - stopping",
+ source: "GlobalHotkeyManager"
+ )
stopRecordingIfNeeded()
}
return nil
@@ -427,26 +483,18 @@ final class GlobalHotkeyManager: NSObject
// Check transcription shortcut (if it's a modifier-only shortcut)
guard shortcut.modifierFlags.isEmpty else { break }
- if keyCode == shortcut.keyCode
- {
- if pressAndHoldMode
- {
- if isModifierPressed
- {
- if !isKeyPressed
- {
+ if keyCode == shortcut.keyCode {
+ if pressAndHoldMode {
+ if isModifierPressed {
+ if !isKeyPressed {
isKeyPressed = true
startRecordingIfNeeded()
}
- }
- else if isKeyPressed
- {
+ } else if isKeyPressed {
isKeyPressed = false
stopRecordingIfNeeded()
}
- }
- else if isModifierPressed
- {
+ } else if isModifierPressed {
toggleRecording()
}
return nil
@@ -458,18 +506,16 @@ final class GlobalHotkeyManager: NSObject
return Unmanaged.passUnretained(event)
}
-
- private func triggerCommandMode()
- {
+
+ private func triggerCommandMode() {
Task { @MainActor [weak self] in
guard let self = self else { return }
DebugLogger.shared.info("Command mode hotkey triggered", source: "GlobalHotkeyManager")
await self.commandModeCallback?()
}
}
-
- private func triggerRewriteMode()
- {
+
+ private func triggerRewriteMode() {
Task { @MainActor [weak self] in
guard let self = self else { return }
DebugLogger.shared.info("Rewrite mode hotkey triggered", source: "GlobalHotkeyManager")
@@ -477,41 +523,33 @@ final class GlobalHotkeyManager: NSObject
}
}
- func enablePressAndHoldMode(_ enable: Bool)
- {
+ func enablePressAndHoldMode(_ enable: Bool) {
pressAndHoldMode = enable
- if !enable && isKeyPressed
- {
+ if !enable, isKeyPressed {
isKeyPressed = false
stopRecordingIfNeeded()
- }
- else if enable
- {
+ } else if enable {
isKeyPressed = false
}
}
- private func toggleRecording()
- {
+ private func toggleRecording() {
// Capture state at event time to prevent race conditions
let shouldStop = asrService.isRunning
let alreadyProcessing = isProcessingStop
-
+
Task { @MainActor [weak self] in
guard let self = self else { return }
-
+
// Prevent new operations while stop is processing
if alreadyProcessing {
DebugLogger.shared.debug("Ignoring toggle - stop already in progress", source: "GlobalHotkeyManager")
return
}
-
- if shouldStop
- {
+
+ if shouldStop {
await self.stopRecordingInternal()
- }
- else
- {
+ } else {
// Use callback if available, otherwise fallback to direct start
if let callback = self.startRecordingCallback {
await callback()
@@ -522,23 +560,21 @@ final class GlobalHotkeyManager: NSObject
}
}
- private func startRecordingIfNeeded()
- {
+ private func startRecordingIfNeeded() {
// Capture state at event time
let alreadyRunning = asrService.isRunning
let alreadyProcessing = isProcessingStop
-
+
Task { @MainActor [weak self] in
guard let self = self else { return }
-
+
// Prevent starting while stop is processing
if alreadyProcessing {
DebugLogger.shared.debug("Ignoring start - stop in progress", source: "GlobalHotkeyManager")
return
}
-
- if !alreadyRunning
- {
+
+ if !alreadyRunning {
// Use callback if available, otherwise fallback to direct start
if let callback = self.startRecordingCallback {
await callback()
@@ -549,15 +585,14 @@ final class GlobalHotkeyManager: NSObject
}
}
- private func stopRecordingIfNeeded()
- {
+ private func stopRecordingIfNeeded() {
// Capture state at event time
let shouldStop = asrService.isRunning
let alreadyProcessing = isProcessingStop
-
+
Task { @MainActor [weak self] in
guard let self = self else { return }
-
+
// Only stop if was running and not already processing
if !shouldStop || alreadyProcessing {
if alreadyProcessing {
@@ -565,59 +600,88 @@ final class GlobalHotkeyManager: NSObject
}
return
}
-
+
await self.stopRecordingInternal()
}
}
@MainActor
- private func stopRecordingInternal() async
- {
+ private func stopRecordingInternal() async {
guard asrService.isRunning else { return }
guard !isProcessingStop else {
DebugLogger.shared.debug("Stop already in progress, ignoring", source: "GlobalHotkeyManager")
return
}
-
+
isProcessingStop = true
defer { isProcessingStop = false }
-
- if let callback = stopAndProcessCallback
- {
+
+ if let callback = stopAndProcessCallback {
await callback()
- }
- else
- {
+ } else {
asrService.stopWithoutTranscription()
}
}
- private func matchesShortcut(keyCode: UInt16, modifiers: NSEvent.ModifierFlags) -> Bool
- {
- let relevantModifiers: NSEvent.ModifierFlags = modifiers.intersection([.function, .command, .option, .control, .shift])
- let shortcutModifiers = shortcut.modifierFlags.intersection([.function, .command, .option, .control, .shift])
+ private func matchesShortcut(keyCode: UInt16, modifiers: NSEvent.ModifierFlags) -> Bool {
+ let relevantModifiers: NSEvent.ModifierFlags = modifiers.intersection([
+ .function,
+ .command,
+ .option,
+ .control,
+ .shift,
+ ])
+ let shortcutModifiers = shortcut.modifierFlags.intersection([
+ .function,
+ .command,
+ .option,
+ .control,
+ .shift,
+ ])
return keyCode == shortcut.keyCode && relevantModifiers == shortcutModifiers
}
-
- private func matchesCommandModeShortcut(keyCode: UInt16, modifiers: NSEvent.ModifierFlags) -> Bool
- {
- let relevantModifiers: NSEvent.ModifierFlags = modifiers.intersection([.function, .command, .option, .control, .shift])
- let shortcutModifiers = commandModeShortcut.modifierFlags.intersection([.function, .command, .option, .control, .shift])
+
+ private func matchesCommandModeShortcut(keyCode: UInt16, modifiers: NSEvent.ModifierFlags) -> Bool {
+ let relevantModifiers: NSEvent.ModifierFlags = modifiers.intersection([
+ .function,
+ .command,
+ .option,
+ .control,
+ .shift,
+ ])
+ let shortcutModifiers = commandModeShortcut.modifierFlags.intersection([
+ .function,
+ .command,
+ .option,
+ .control,
+ .shift,
+ ])
return keyCode == commandModeShortcut.keyCode && relevantModifiers == shortcutModifiers
}
-
- private func matchesRewriteModeShortcut(keyCode: UInt16, modifiers: NSEvent.ModifierFlags) -> Bool
- {
- let relevantModifiers: NSEvent.ModifierFlags = modifiers.intersection([.function, .command, .option, .control, .shift])
- let shortcutModifiers = rewriteModeShortcut.modifierFlags.intersection([.function, .command, .option, .control, .shift])
+
+ private func matchesRewriteModeShortcut(keyCode: UInt16, modifiers: NSEvent.ModifierFlags) -> Bool {
+ let relevantModifiers: NSEvent.ModifierFlags = modifiers.intersection([
+ .function,
+ .command,
+ .option,
+ .control,
+ .shift,
+ ])
+ let shortcutModifiers = rewriteModeShortcut.modifierFlags.intersection([
+ .function,
+ .command,
+ .option,
+ .control,
+ .shift,
+ ])
return keyCode == rewriteModeShortcut.keyCode && relevantModifiers == shortcutModifiers
}
-
+
func isEventTapEnabled() -> Bool {
guard let tap = eventTap else { return false }
return CGEvent.tapIsEnabled(tap: tap)
}
-
+
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.
@@ -627,12 +691,12 @@ final class GlobalHotkeyManager: NSObject
}
return enabled
}
-
+
func reinitialize() {
if UserDefaults.standard.bool(forKey: "enableDebugLogs") {
print("[GlobalHotkeyManager] Manual reinitialization requested")
}
-
+
initializationTask?.cancel()
healthCheckTask?.cancel()
isInitialized = false
@@ -643,16 +707,16 @@ final class GlobalHotkeyManager: NSObject
healthCheckTask?.cancel()
healthCheckTask = Task {
while !Task.isCancelled {
- try? await Task.sleep(nanoseconds: UInt64(healthCheckInterval * 1_000_000_000))
-
+ try? await Task.sleep(nanoseconds: UInt64(self.healthCheckInterval * 1_000_000_000))
+
guard !Task.isCancelled else { break }
-
+
await MainActor.run {
if !self.validateEventTapHealth() {
if UserDefaults.standard.bool(forKey: "enableDebugLogs") {
print("[GlobalHotkeyManager] Health check failed, attempting to recover")
}
-
+
if self.setupGlobalHotkey() {
self.isInitialized = true
if UserDefaults.standard.bool(forKey: "enableDebugLogs") {
@@ -667,17 +731,14 @@ final class GlobalHotkeyManager: NSObject
}
}
}
-
- deinit
- {
+
+ deinit {
initializationTask?.cancel()
healthCheckTask?.cancel()
cleanupEventTap()
-
+
if UserDefaults.standard.bool(forKey: "enableDebugLogs") {
print("[GlobalHotkeyManager] Deinitialized and cleaned up")
}
}
}
-
-
diff --git a/Sources/Fluid/Services/MeetingTranscriptionService.swift b/Sources/Fluid/Services/MeetingTranscriptionService.swift
index 67f75786..252cfe11 100644
--- a/Sources/Fluid/Services/MeetingTranscriptionService.swift
+++ b/Sources/Fluid/Services/MeetingTranscriptionService.swift
@@ -1,5 +1,5 @@
-import Foundation
import AVFoundation
+import Foundation
#if arch(arm64)
import FluidAudio
#endif
@@ -13,8 +13,8 @@ struct TranscriptionResult: Identifiable, Sendable, Codable {
let duration: TimeInterval
let processingTime: TimeInterval
let fileName: String
- let timestamp: Date = Date()
-
+ let timestamp: Date = .init()
+
enum CodingKeys: String, CodingKey {
case text, confidence, duration, processingTime, fileName, timestamp
}
@@ -29,51 +29,51 @@ final class MeetingTranscriptionService: ObservableObject {
@Published var currentStatus: String = ""
@Published var error: String?
@Published var result: TranscriptionResult?
-
+
// Share the ASR service instance to avoid loading models twice
private let asrService: ASRService
-
+
init(asrService: ASRService) {
self.asrService = asrService
}
-
+
enum TranscriptionError: LocalizedError {
case modelLoadFailed(String)
case audioConversionFailed(String)
case transcriptionFailed(String)
case fileNotSupported(String)
-
+
var errorDescription: String? {
switch self {
- case .modelLoadFailed(let msg):
+ case let .modelLoadFailed(msg):
return "Failed to load ASR models: \(msg)"
- case .audioConversionFailed(let msg):
+ case let .audioConversionFailed(msg):
return "Failed to convert audio: \(msg)"
- case .transcriptionFailed(let msg):
+ case let .transcriptionFailed(msg):
return "Transcription failed: \(msg)"
- case .fileNotSupported(let msg):
+ case let .fileNotSupported(msg):
return "File format not supported: \(msg)"
}
}
}
-
+
/// Initialize the ASR models (reuses models from ASRService - no duplicate download!)
func initializeModels() async throws {
guard !asrService.isAsrReady else { return }
-
+
currentStatus = "Preparing ASR models..."
progress = 0.1
-
+
do {
try await asrService.ensureAsrReady()
-
+
currentStatus = "Models ready"
progress = 0.0
} catch {
throw TranscriptionError.modelLoadFailed(error.localizedDescription)
}
}
-
+
/// Transcribe an audio or video file
/// - Parameters:
/// - fileURL: URL to the audio/video file
@@ -82,57 +82,58 @@ final class MeetingTranscriptionService: ObservableObject {
error = nil
progress = 0.0
let startTime = Date()
-
+
defer {
isTranscribing = false
progress = 0.0
}
-
+
do {
// Initialize models if not already done (reuses ASRService models)
if !asrService.isAsrReady {
try await initializeModels()
}
-
+
#if arch(arm64)
guard let asrManager = asrService.asrManager else {
throw TranscriptionError.modelLoadFailed("ASR Manager not initialized")
}
-
+
// Convert audio to required format (16kHz mono Float32)
currentStatus = "Converting audio..."
progress = 0.3
-
+
let converter = AudioConverter()
let samples: [Float]
-
+
// Check file extension
let fileExtension = fileURL.pathExtension.lowercased()
let supportedFormats = ["wav", "mp3", "m4a", "aac", "flac", "aiff", "caf", "mp4", "mov"]
-
+
guard supportedFormats.contains(fileExtension) else {
- throw TranscriptionError.fileNotSupported("Format .\(fileExtension) not supported. Supported: \(supportedFormats.joined(separator: ", "))")
+ throw TranscriptionError
+ .fileNotSupported("Format .\(fileExtension) not supported. Supported: \(supportedFormats.joined(separator: ", "))")
}
-
+
do {
samples = try converter.resampleAudioFile(fileURL)
} catch {
throw TranscriptionError.audioConversionFailed(error.localizedDescription)
}
-
- let duration = Double(samples.count) / 16000.0 // 16kHz sample rate
-
+
+ let duration = Double(samples.count) / 16_000.0 // 16kHz sample rate
+
// Transcribe
currentStatus = "Transcribing audio (\(Int(duration))s)..."
progress = 0.6
-
+
let transcriptionResult = try await asrManager.transcribe(samples, source: .system)
-
+
currentStatus = "Complete!"
progress = 1.0
-
+
let processingTime = Date().timeIntervalSince(startTime)
-
+
let result = TranscriptionResult(
text: transcriptionResult.text,
confidence: transcriptionResult.confidence,
@@ -140,13 +141,14 @@ final class MeetingTranscriptionService: ObservableObject {
processingTime: processingTime,
fileName: fileURL.lastPathComponent
)
-
+
self.result = result
return result
#else
- throw TranscriptionError.transcriptionFailed("File transcription is only supported on Apple Silicon Macs at this time.")
+ throw TranscriptionError
+ .transcriptionFailed("File transcription is only supported on Apple Silicon Macs at this time.")
#endif
-
+
} catch let error as TranscriptionError {
self.error = error.localizedDescription
throw error
@@ -156,7 +158,7 @@ final class MeetingTranscriptionService: ObservableObject {
throw wrappedError
}
}
-
+
/// Export transcription result to text file
nonisolated func exportToText(_ result: TranscriptionResult, to destinationURL: URL) throws {
let content = """
@@ -165,25 +167,25 @@ final class MeetingTranscriptionService: ObservableObject {
Duration: \(String(format: "%.1f", result.duration))s
Processing Time: \(String(format: "%.1f", result.processingTime))s
Confidence: \(String(format: "%.1f%%", result.confidence * 100))
-
+
---
-
+
\(result.text)
"""
-
+
try content.write(to: destinationURL, atomically: true, encoding: .utf8)
}
-
+
/// Export transcription result to JSON
nonisolated func exportToJSON(_ result: TranscriptionResult, to destinationURL: URL) throws {
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
encoder.dateEncodingStrategy = .iso8601
-
+
let jsonData = try encoder.encode(result)
try jsonData.write(to: destinationURL)
}
-
+
/// Reset the service state
func reset() {
result = nil
diff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swift
index 8e25ce4c..2285258a 100644
--- a/Sources/Fluid/Services/MenuBarManager.swift
+++ b/Sources/Fluid/Services/MenuBarManager.swift
@@ -13,35 +13,35 @@ final class MenuBarManager: ObservableObject {
private var menu: NSMenu?
private var isSetup: Bool = false
private var hostedWindow: NSWindow?
-
+
// Cached menu items to avoid rebuilding entire menu
private var statusMenuItem: NSMenuItem?
private var aiMenuItem: NSMenuItem?
-
+
// References to app state
private weak var asrService: ASRService?
private var cancellables = Set<AnyCancellable>()
-
+
// Overlay management (persistent, independent of window lifecycle)
private var overlayVisible: Bool = false
-
+
@Published var isRecording: Bool = false
@Published var aiProcessingEnabled: Bool = false
-
+
/// One-shot navigation requests from the menu bar into the main window UI.
/// `ContentView` consumes this and clears it.
@Published var requestedNavigationDestination: MenuBarNavigationDestination? = nil
-
+
// Track current overlay mode for notch
private var currentOverlayMode: OverlayMode = .dictation
-
+
// Track pending overlay operations to prevent spam
private var pendingShowOperation: DispatchWorkItem?
private var pendingHideOperation: DispatchWorkItem?
-
+
// Subscription for forwarding audio levels to expanded command notch
private var expandedModeAudioSubscription: AnyCancellable?
-
+
init() {
// Don't setup menu bar immediately - defer until app is ready
// Initialize from persisted setting
@@ -54,23 +54,23 @@ final class MenuBarManager: ObservableObject {
}
.store(in: &cancellables)
}
-
+
func initializeMenuBar() {
guard !isSetup else { return }
-
+
// Ensure we're on main thread and app is active
DispatchQueue.main.async { [weak self] in
self?.setupMenuBarSafely()
}
}
-
+
deinit {
statusItem = nil
}
-
+
func configure(asrService: ASRService) {
self.asrService = asrService
-
+
// Subscribe to recording state changes
asrService.$isRunning
.receive(on: DispatchQueue.main)
@@ -78,12 +78,12 @@ final class MenuBarManager: ObservableObject {
self?.isRecording = isRunning
self?.updateMenuBarIcon()
self?.updateMenu()
-
+
// Handle overlay lifecycle (independent of window state)
self?.handleOverlayState(isRunning: isRunning, asrService: asrService)
}
.store(in: &cancellables)
-
+
// Subscribe to partial transcription updates for streaming preview
asrService.$partialTranscription
.receive(on: DispatchQueue.main)
@@ -96,23 +96,23 @@ final class MenuBarManager: ObservableObject {
}
}
.store(in: &cancellables)
-
+
// Subscribe to AI processing state
aiProcessingEnabled = SettingsStore.shared.enableAIProcessing
}
-
+
private func handleOverlayState(isRunning: Bool, asrService: ASRService) {
// Prevent rapid state changes that could cause cycles
guard overlayVisible != isRunning else { return }
-
+
let delay: DispatchTimeInterval = .milliseconds(150)
if isRunning {
// Cancel any pending hide operation
pendingHideOperation?.cancel()
pendingHideOperation = nil
-
+
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)
@@ -120,14 +120,14 @@ final class MenuBarManager: ObservableObject {
if 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
.receive(on: DispatchQueue.main)
.sink { level in
NotchContentState.shared.updateExpandedModeAudioLevel(level)
}
-
+
pendingShowOperation = nil
return
} else {
@@ -135,23 +135,23 @@ final class MenuBarManager: ObservableObject {
NotchOverlayManager.shared.hideExpandedCommandOutput()
}
}
-
+
let showItem = DispatchWorkItem { [weak self] in
guard let self = self, self.overlayVisible else { return }
-
+
// Double-check expanded notch isn't showing (could have changed during delay)
// But only block if we're in command mode
if NotchOverlayManager.shared.isCommandOutputExpanded && self.currentOverlayMode == .command {
self.pendingShowOperation = nil
return
}
-
+
// Show notch overlay
NotchOverlayManager.shared.show(
audioLevelPublisher: asrService.audioLevelPublisher,
mode: self.currentOverlayMode
)
-
+
self.pendingShowOperation = nil
}
pendingShowOperation = showItem
@@ -160,49 +160,50 @@ final class MenuBarManager: ObservableObject {
// Cancel any pending show operation
pendingShowOperation?.cancel()
pendingShowOperation = nil
-
+
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
-
+
pendingHideOperation = nil
return
}
-
+
let hideItem = DispatchWorkItem { [weak self] in
guard let self = self, !self.overlayVisible else { return }
-
+
// Don't hide if expanded command output is now showing
if NotchOverlayManager.shared.isCommandOutputExpanded {
self.pendingHideOperation = nil
return
}
-
+
// Hide notch overlay
NotchOverlayManager.shared.hide()
-
+
self.pendingHideOperation = nil
}
pendingHideOperation = hideItem
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: hideItem)
}
}
-
+
// MARK: - Public API for overlay management
+
func updateOverlayTranscription(_ text: String) {
NotchOverlayManager.shared.updateTranscriptionText(text)
}
-
+
func setOverlayMode(_ mode: OverlayMode) {
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
@@ -212,23 +213,23 @@ final class MenuBarManager: ObservableObject {
} else {
// When processing ends, schedule the hide (unless expanded output is showing)
overlayVisible = false
-
+
// If expanded command output is showing, don't hide it
if NotchOverlayManager.shared.isCommandOutputExpanded {
pendingHideOperation = nil
NotchOverlayManager.shared.setProcessing(processing)
return
}
-
+
let hideItem = DispatchWorkItem { [weak self] in
guard let self = self, !self.overlayVisible else { return }
-
+
// Don't hide if expanded command output is now showing
if NotchOverlayManager.shared.isCommandOutputExpanded {
self.pendingHideOperation = nil
return
}
-
+
NotchOverlayManager.shared.hide()
self.pendingHideOperation = nil
}
@@ -237,7 +238,7 @@ final class MenuBarManager: ObservableObject {
}
NotchOverlayManager.shared.setProcessing(processing)
}
-
+
private func setupMenuBarSafely() {
// Check if window server connection is available
guard NSApp.isActive || NSApp.isRunning else {
@@ -247,7 +248,7 @@ final class MenuBarManager: ObservableObject {
}
return
}
-
+
do {
try setupMenuBar()
isSetup = true
@@ -259,127 +260,139 @@ final class MenuBarManager: ObservableObject {
}
}
}
-
+
private func setupMenuBar() throws {
// Ensure we're not already set up
guard !isSetup else { return }
-
+
// Create status item with error handling
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
-
- guard let statusItem = statusItem else {
- throw NSError(domain: "MenuBarManager", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to create status item"])
+
+ guard let statusItem = statusItem else {
+ throw NSError(
+ domain: "MenuBarManager",
+ code: 1,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to create status item"]
+ )
}
-
+
// Set initial icon
updateMenuBarIcon()
-
+
// Create menu
menu = NSMenu()
statusItem.menu = menu
-
+
updateMenu()
}
-
+
private func updateMenuBarIcon() {
guard let statusItem = statusItem else { return }
-
+
// Use custom F icon instead of microphone
let image = createFluidIcon(isRecording: isRecording)
-
+
statusItem.button?.image = image
statusItem.button?.imagePosition = .imageOnly
}
-
+
private func createFluidIcon(isRecording: Bool) -> NSImage {
let size = NSSize(width: 16, height: 16)
let image = NSImage(size: size)
-
+
image.lockFocus()
-
+
// Create F shape path
let path = NSBezierPath()
let lineWidth: CGFloat = 2.0
-
+
// F shape coordinates (scaled to 16x16)
let leftX: CGFloat = 2
let rightX: CGFloat = 12
let topY: CGFloat = 14
let bottomY: CGFloat = 2
let middleY: CGFloat = 8.5
-
+
// Vertical line (left side of F)
path.move(to: NSPoint(x: leftX, y: bottomY))
path.line(to: NSPoint(x: leftX, y: topY))
-
+
// Top horizontal line (full width)
path.line(to: NSPoint(x: rightX, y: topY))
-
+
// Middle horizontal line
path.move(to: NSPoint(x: leftX, y: middleY))
path.line(to: NSPoint(x: rightX - 2, y: middleY))
-
+
// Set color based on recording state
let color = isRecording ? NSColor.systemRed : NSColor.controlAccentColor
color.set()
-
+
path.lineWidth = lineWidth
path.lineCapStyle = .round
path.lineJoinStyle = .round
path.stroke()
-
+
image.unlockFocus()
image.isTemplate = true
-
+
return image
}
-
+
private func buildMenuStructure() {
guard let menu = menu else { return }
-
+
menu.removeAllItems()
-
+
// Status indicator with hotkey info
statusMenuItem = NSMenuItem(title: "", action: nil, keyEquivalent: "")
statusMenuItem?.isEnabled = false
menu.addItem(statusMenuItem!)
-
+
menu.addItem(.separator())
-
+
// AI Processing Toggle
aiMenuItem = NSMenuItem(title: "", action: #selector(toggleAIProcessing), keyEquivalent: "")
aiMenuItem?.target = self
menu.addItem(aiMenuItem!)
-
+
menu.addItem(.separator())
-
+
// Open Main Window
let openItem = NSMenuItem(title: "Open Fluid Voice", action: #selector(openMainWindow), keyEquivalent: "")
openItem.target = self
menu.addItem(openItem)
-
+
// Preferences
let preferencesItem = NSMenuItem(title: "Preferences", action: #selector(openPreferences), keyEquivalent: ",")
preferencesItem.target = self
preferencesItem.keyEquivalentModifierMask = [.command]
menu.addItem(preferencesItem)
-
+
// Check for Updates
- let updateItem = NSMenuItem(title: "Check for Updates...", action: #selector(checkForUpdates(_:)), keyEquivalent: "")
+ let updateItem = NSMenuItem(
+ title: "Check for Updates...",
+ action: #selector(checkForUpdates(_:)),
+ keyEquivalent: ""
+ )
updateItem.target = self
menu.addItem(updateItem)
-
+
menu.addItem(.separator())
-
+
// Quit
- let quitItem = NSMenuItem(title: "Quit Fluid Voice", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
+ let quitItem = NSMenuItem(
+ title: "Quit Fluid Voice",
+ action: #selector(NSApplication.terminate(_:)),
+ keyEquivalent: "q"
+ )
quitItem.target = NSApp
menu.addItem(quitItem)
-
+
// Now update the text content
updateMenuItemsText()
}
-
+
private func updateMenu() {
// If menu structure hasn't been built yet, build it
if statusMenuItem == nil {
@@ -389,19 +402,19 @@ final class MenuBarManager: ObservableObject {
updateMenuItemsText()
}
}
-
+
private func updateMenuItemsText() {
// 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
-
+
// Update AI toggle text
let aiTitle = aiProcessingEnabled ? "Disable AI Processing" : "Enable AI Processing"
aiMenuItem?.title = aiTitle
}
-
+
@objc private func toggleAIProcessing() {
aiProcessingEnabled.toggle()
// Persist and broadcast change
@@ -409,17 +422,17 @@ final class MenuBarManager: ObservableObject {
// If a ContentView has bound to MenuBarManager, its onChange sync will mirror this
updateMenu()
}
-
+
@objc private func checkForUpdates(_ sender: Any?) {
print("🔎 Menu action: Check for Updates…")
NSLog("🔎 Menu action: Check for Updates…")
-
+
// Call the AppDelegate's manual update check method if available
if let appDelegate = NSApp.delegate as? AppDelegate {
appDelegate.checkForUpdatesManually()
return
}
-
+
// Fallback: perform direct, tolerant check so the menu item always does something
Task { @MainActor in
do {
@@ -444,16 +457,16 @@ final class MenuBarManager: ObservableObject {
}
}
}
-
+
@objc private func openMainWindow() {
// First, unhide the app if it's hidden
if NSApp.isHidden {
NSApp.unhide(nil)
}
-
+
// Activate the app and bring it to the front
NSApp.activate(ignoringOtherApps: true)
-
+
// Find an existing *non-minimized* primary window.
// Important: avoid programmatic deminiaturize() — it creates internal window transform animations
// (NSWindowTransformAnimation) that have been unstable on macOS 26.x for this app.
@@ -467,7 +480,7 @@ final class MenuBarManager: ObservableObject {
guard win.styleMask.contains(.titled) else { return false }
guard win.canBecomeKey else { return false }
guard win.isMiniaturized == false else { return false }
-
+
// Prefer our main window title when present (both SwiftUI and our fallback window use this)
return win.title == "FluidVoice" || win.title.contains("FluidVoice")
}) {
@@ -479,18 +492,18 @@ final class MenuBarManager: ObservableObject {
// If there is no suitable window (or it's minimized), create a fresh one.
createAndShowMainWindow()
}
-
+
// Final attempt: ensure app is active and visible
NSApp.activate(ignoringOtherApps: true)
}
-
+
@objc private func openPreferences() {
// Ensure a fresh one-shot request every time the menu item is clicked.
requestedNavigationDestination = nil
requestedNavigationDestination = .preferences
-
+
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.
DispatchQueue.main.async { [weak self] in
@@ -498,7 +511,7 @@ final class MenuBarManager: ObservableObject {
self?.requestedNavigationDestination = .preferences
}
}
-
+
/// Create and present a fresh main window hosting `ContentView`
private func createAndShowMainWindow() {
// Build the SwiftUI root view with required environment
@@ -506,7 +519,7 @@ final class MenuBarManager: ObservableObject {
.environmentObject(self)
.appTheme(.dark)
.preferredColorScheme(.dark)
-
+
// Host inside an AppKit window
let hostingController = NSHostingController(rootView: rootView)
let window = NSWindow(
@@ -523,22 +536,22 @@ final class MenuBarManager: ObservableObject {
window.setFrame(defaultWindowFrame(), display: false)
window.makeKeyAndOrderFront(nil)
hostedWindow = window
-
+
// Bring app to front in case we're running as an accessory app (no Dock)
NSApp.activate(ignoringOtherApps: true)
}
-
+
private func ensureUsableMainWindow(_ window: NSWindow) {
// If the window is too small (e.g., height collapsed), reset to the default frame.
let minSize = NSSize(width: 800, height: 500)
window.minSize = minSize
-
+
let frame = window.frame
if frame.height < minSize.height || frame.width < minSize.width {
window.setFrame(defaultWindowFrame(), display: false)
}
}
-
+
private func defaultWindowFrame() -> NSRect {
// Center a sensible default frame on the main screen.
let size = NSSize(width: 1000, height: 700)
diff --git a/Sources/Fluid/Services/NotchOverlayManager.swift b/Sources/Fluid/Services/NotchOverlayManager.swift
index 75e8a7e9..f2c3ec9e 100644
--- a/Sources/Fluid/Services/NotchOverlayManager.swift
+++ b/Sources/Fluid/Services/NotchOverlayManager.swift
@@ -1,16 +1,10 @@
-//
-// NotchOverlayManager.swift
-// Fluid
-//
-// Created by Assistant
-//
-
+import AppKit
+import Combine
import DynamicNotchKit
import SwiftUI
-import Combine
-import AppKit
// MARK: - Overlay Mode
+
enum OverlayMode: String {
case dictation = "Dictation"
case rewrite = "Rewrite"
@@ -21,17 +15,21 @@ enum OverlayMode: String {
@MainActor
final class NotchOverlayManager {
static let shared = NotchOverlayManager()
-
+
private var notch: DynamicNotch<NotchExpandedView, NotchCompactLeadingView, NotchCompactTrailingView>?
- private var commandOutputNotch: DynamicNotch<NotchCommandOutputExpandedView, NotchCompactLeadingView, NotchCompactTrailingView>?
+ private var commandOutputNotch: DynamicNotch<
+ NotchCommandOutputExpandedView,
+ NotchCompactLeadingView,
+ NotchCompactTrailingView
+ >?
private var currentMode: OverlayMode = .dictation
-
+
// Store last audio publisher for re-showing during processing
private var lastAudioPublisher: AnyPublisher<CGFloat, Never>?
-
+
// Current audio publisher (can be updated for expanded notch recording)
@Published private(set) var currentAudioPublisher: AnyPublisher<CGFloat, Never>?
-
+
// State machine to prevent race conditions
private enum State {
case idle
@@ -39,38 +37,39 @@ final class NotchOverlayManager {
case visible
case hiding
}
+
private var state: State = .idle
private var commandOutputState: State = .idle
-
+
// Track if expanded command output is showing
private(set) var isCommandOutputExpanded: Bool = false
-
+
// Callbacks for command output interaction
var onCommandOutputDismiss: (() -> Void)?
var onCommandFollowUp: ((String) async -> Void)?
- var onNotchClicked: (() -> Void)? // Called when regular notch is clicked in command mode
-
+ var onNotchClicked: (() -> Void)? // Called when regular notch is clicked in command mode
+
// Callbacks for chat management
var onNewChat: (() -> Void)?
var onSwitchChat: ((String) -> Void)?
var onClearChat: (() -> Void)?
-
+
// Generation counter to track show/hide cycles and prevent race conditions
// Uses UInt64 to avoid overflow concerns in long-running sessions
private var generation: UInt64 = 0
private var commandOutputGeneration: UInt64 = 0
-
+
// Track pending retry task for cancellation
private var pendingRetryTask: Task<Void, Never>?
-
+
// Escape key monitors for dismissing notch
private var globalEscapeMonitor: Any?
private var localEscapeMonitor: Any?
-
+
private init() {
setupEscapeKeyMonitors()
}
-
+
deinit {
if let monitor = globalEscapeMonitor {
NSEvent.removeMonitor(monitor)
@@ -79,15 +78,15 @@ final class NotchOverlayManager {
NSEvent.removeMonitor(monitor)
}
}
-
+
/// Setup escape key monitors - both global (other apps) and local (our app)
private func setupEscapeKeyMonitors() {
let escapeHandler: (NSEvent) -> NSEvent? = { [weak self] event in
- guard event.keyCode == 53 else { return event } // Escape key
-
+ guard event.keyCode == 53 else { return event } // Escape key
+
Task { @MainActor in
guard let self = self else { return }
-
+
// If expanded command output is showing, hide it
if self.isCommandOutputExpanded {
self.hideExpandedCommandOutput()
@@ -98,18 +97,18 @@ final class NotchOverlayManager {
self.hide()
}
}
- return nil // Consume the event
+ return nil // Consume the event
}
-
+
// Global monitor - catches escape when OTHER apps have focus
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)
}
-
+
func show(audioLevelPublisher: AnyPublisher<CGFloat, Never>, mode: OverlayMode) {
// Don't show regular notch if expanded command output is visible
if isCommandOutputExpanded {
@@ -117,56 +116,56 @@ final class NotchOverlayManager {
lastAudioPublisher = audioLevelPublisher
return
}
-
+
// Cancel any pending retry operations
pendingRetryTask?.cancel()
pendingRetryTask = nil
-
+
// If already visible or in transition, wait for cleanup to complete
if notch != nil || state != .idle {
// Increment generation to invalidate stale operations
generation &+= 1
let targetGeneration = generation
-
+
// Start async cleanup and retry
pendingRetryTask = Task { [weak self] in
guard let self = self else { return }
-
+
// Perform cleanup synchronously first
await self.performCleanup()
-
+
// Small delay to ensure cleanup completes
try? await Task.sleep(nanoseconds: 50_000_000) // 50ms
-
+
// Check if we're still the active operation
guard !Task.isCancelled, self.generation == targetGeneration else { return }
-
+
// Retry show
self.showInternal(audioLevelPublisher: audioLevelPublisher, mode: mode)
}
return
}
-
+
showInternal(audioLevelPublisher: audioLevelPublisher, mode: mode)
}
-
+
private func showInternal(audioLevelPublisher: AnyPublisher<CGFloat, Never>, mode: OverlayMode) {
guard state == .idle else { return }
-
+
// Store for potential re-show during processing
lastAudioPublisher = audioLevelPublisher
-
+
// Increment generation for this operation
generation &+= 1
let currentGeneration = generation
-
+
state = .showing
currentMode = mode
-
+
// Update shared content state immediately
NotchContentState.shared.mode = mode
NotchContentState.shared.updateTranscription("")
-
+
// Create notch with SwiftUI views
let newNotch = DynamicNotch(
hoverBehavior: [.keepVisible, .hapticFeedback],
@@ -178,9 +177,9 @@ final class NotchOverlayManager {
} compactTrailing: {
NotchCompactTrailingView()
}
-
- self.notch = newNotch
-
+
+ notch = newNotch
+
// Show in expanded state
Task { [weak self] in
await newNotch.expand()
@@ -189,28 +188,28 @@ final class NotchOverlayManager {
self.state = .visible
}
}
-
+
func hide() {
// Cancel any pending retry operations
pendingRetryTask?.cancel()
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
-
+
// Handle visible or showing states (can hide while still expanding)
guard state == .visible || state == .showing, let currentNotch = notch else {
// Force cleanup if stuck or in inconsistent state
Task { [weak self] in await self?.performCleanup() }
return
}
-
+
state = .hiding
-
+
Task { [weak self] in
await currentNotch.hide()
// Only clear if we're still the active operation
@@ -219,39 +218,39 @@ final class NotchOverlayManager {
self.state = .idle
}
}
-
+
/// Async cleanup that properly waits for hide to complete
private func performCleanup() async {
// Cancel any pending retry operations
pendingRetryTask?.cancel()
pendingRetryTask = nil
-
+
if let existingNotch = notch {
await existingNotch.hide()
}
notch = nil
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
NotchContentState.shared.mode = mode
}
-
+
func updateTranscriptionText(_ text: String) {
NotchContentState.shared.updateTranscription(text)
}
-
+
func setProcessing(_ processing: Bool) {
NotchContentState.shared.setProcessing(processing)
-
+
// If expanded command output is showing, don't mess with regular notch
if isCommandOutputExpanded {
return
}
-
+
if processing {
// If notch isn't visible, re-show it for processing state
if state == .idle || state == .hiding {
@@ -261,40 +260,41 @@ final class NotchOverlayManager {
}
}
}
-
+
// MARK: - Expanded Command Output
-
+
/// Show expanded command output notch
func showExpandedCommandOutput() {
// Hide regular notch first if visible
if notch != nil {
hide()
}
-
+
// Wait a bit for cleanup
Task { [weak self] in
try? await Task.sleep(nanoseconds: 100_000_000) // 100ms
await self?.showExpandedCommandOutputInternal()
}
}
-
+
private func showExpandedCommandOutputInternal() async {
guard commandOutputState == .idle else { return }
-
+
commandOutputGeneration &+= 1
let currentGeneration = commandOutputGeneration
-
+
commandOutputState = .showing
isCommandOutputExpanded = true
-
+
// Update content state
NotchContentState.shared.mode = .command
NotchContentState.shared.isExpandedForCommandOutput = true
-
+
let publisher = lastAudioPublisher ?? Empty<CGFloat, Never>().eraseToAnyPublisher()
-
+
let newNotch = DynamicNotch(
- hoverBehavior: [], // No keepVisible - allows closing with X/Escape even when cursor is on notch
+ hoverBehavior: [], // No keepVisible - allows closing with X/Escape even when cursor
+ // is on notch
style: .notch(topCornerRadius: 12, bottomCornerRadius: 16)
) {
NotchCommandOutputExpandedView(
@@ -333,36 +333,37 @@ final class NotchOverlayManager {
} compactTrailing: {
NotchCompactTrailingView()
}
-
- self.commandOutputNotch = newNotch
-
+
+ commandOutputNotch = newNotch
+
await newNotch.expand()
-
- guard self.commandOutputGeneration == currentGeneration else { return }
- self.commandOutputState = .visible
+
+ guard commandOutputGeneration == currentGeneration else { return }
+ commandOutputState = .visible
}
-
+
/// Hide expanded command output notch - force close regardless of hover state
func hideExpandedCommandOutput() {
commandOutputGeneration &+= 1
let currentGeneration = commandOutputGeneration
-
+
// Force cleanup state immediately
isCommandOutputExpanded = false
NotchContentState.shared.collapseCommandOutput()
-
+
guard commandOutputState == .visible || commandOutputState == .showing,
- let currentNotch = commandOutputNotch else {
+ let currentNotch = commandOutputNotch
+ else {
commandOutputState = .idle
return
}
-
+
commandOutputState = .hiding
-
+
// Store reference and nil out immediately to prevent hover from keeping it alive
let notchToHide = currentNotch
- self.commandOutputNotch = nil
-
+ commandOutputNotch = nil
+
Task { [weak self] in
// Try to hide gracefully, but we've already removed our reference
await notchToHide.hide()
@@ -370,7 +371,7 @@ final class NotchOverlayManager {
self.commandOutputState = .idle
}
}
-
+
/// Toggle expanded command output (for hotkey handling)
func toggleExpandedCommandOutput() {
if isCommandOutputExpanded {
@@ -380,16 +381,15 @@ final class NotchOverlayManager {
showExpandedCommandOutput()
}
}
-
+
/// Check if any notch (regular or expanded) is visible
var isAnyNotchVisible: Bool {
return state == .visible || state == .showing || isCommandOutputExpanded
}
-
+
/// Update audio publisher for expanded notch (when recording starts within it)
func updateAudioPublisher(_ publisher: AnyPublisher<CGFloat, Never>) {
lastAudioPublisher = publisher
currentAudioPublisher = publisher
}
}
-
diff --git a/Sources/Fluid/Services/RewriteModeService.swift b/Sources/Fluid/Services/RewriteModeService.swift
index e9bc0d8d..a927d28a 100644
--- a/Sources/Fluid/Services/RewriteModeService.swift
+++ b/Sources/Fluid/Services/RewriteModeService.swift
@@ -1,6 +1,6 @@
-import Foundation
-import Combine
import AppKit
+import Combine
+import Foundation
@MainActor
final class RewriteModeService: ObservableObject {
@@ -8,60 +8,60 @@ final class RewriteModeService: ObservableObject {
@Published var rewrittenText: String = ""
@Published var isProcessing = false
@Published var conversationHistory: [Message] = []
- @Published var isWriteMode: Bool = false // true = no text selected (write/improve), false = text selected (rewrite)
-
+ @Published var isWriteMode: Bool = false // true = no text selected (write/improve), false = text selected (rewrite)
+
private let textSelectionService = TextSelectionService.shared
private let typingService = TypingService()
-
+
struct Message: Identifiable, Equatable {
let id = UUID()
let role: Role
let content: String
-
+
enum Role: Equatable {
case user
case assistant
}
}
-
+
func captureSelectedText() -> Bool {
if let text = textSelectionService.getSelectedText(), !text.isEmpty {
- self.originalText = text
- self.rewrittenText = ""
- self.conversationHistory = []
- self.isWriteMode = false
+ originalText = text
+ rewrittenText = ""
+ conversationHistory = []
+ isWriteMode = false
return true
}
return false
}
-
+
/// Start rewrite mode without selected text - user will provide text via voice
func startWithoutSelection() {
- self.originalText = ""
- self.rewrittenText = ""
- self.conversationHistory = []
- self.isWriteMode = true
+ originalText = ""
+ rewrittenText = ""
+ conversationHistory = []
+ isWriteMode = true
}
-
+
/// Set the original text directly (from voice input when no text was selected)
func setOriginalText(_ text: String) {
- self.originalText = text
- self.rewrittenText = ""
- self.conversationHistory = []
+ originalText = text
+ rewrittenText = ""
+ 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
-
+
// Write Mode: User is asking AI to write/generate something
conversationHistory.append(Message(role: .user, content: prompt))
} else {
// Rewrite Mode: User has selected text and is giving instructions
isWriteMode = false
-
+
if conversationHistory.isEmpty {
let rewritePrompt = """
Here is the text to rewrite:
@@ -75,14 +75,17 @@ final class RewriteModeService: ObservableObject {
conversationHistory.append(Message(role: .user, content: rewritePrompt))
} else {
// Follow-up request
- conversationHistory.append(Message(role: .user, content: "Follow-up instruction: \(prompt)\n\nApply this to the previous result. Output ONLY the updated text."))
+ 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 }
-
+
isProcessing = true
-
+
do {
let response = try await callLLM(messages: conversationHistory, isWriteMode: isWriteMode)
conversationHistory.append(Message(role: .assistant, content: response))
@@ -93,43 +96,48 @@ final class RewriteModeService: ObservableObject {
isProcessing = false
}
}
-
+
func acceptRewrite() {
guard !rewrittenText.isEmpty else { return }
NSApp.hide(nil) // Restore focus to the previous app
typingService.typeTextInstantly(rewrittenText)
}
-
+
func clearState() {
originalText = ""
rewrittenText = ""
conversationHistory = []
isWriteMode = false
}
-
+
// MARK: - LLM Integration
-
+
private func callLLM(messages: [Message], isWriteMode: Bool) async throws -> String {
let settings = SettingsStore.shared
// Use Write Mode's independent provider/model settings
let providerID = settings.rewriteModeSelectedProviderID
-
+
// Route to Apple Intelligence if selected
if providerID == "apple-intelligence" {
#if canImport(FoundationModels)
if #available(macOS 26.0, *) {
let provider = AppleIntelligenceProvider()
- let messageTuples = messages.map { (role: $0.role == .user ? "user" : "assistant", content: $0.content) }
+ let messageTuples = messages
+ .map { (role: $0.role == .user ? "user" : "assistant", content: $0.content) }
DebugLogger.shared.debug("Using Apple Intelligence for rewrite mode", source: "RewriteModeService")
return try await provider.processRewrite(messages: messageTuples, isWriteMode: isWriteMode)
}
#endif
- throw NSError(domain: "RewriteMode", code: -1, userInfo: [NSLocalizedDescriptionKey: "Apple Intelligence not available"])
+ throw NSError(
+ domain: "RewriteMode",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Apple Intelligence not available"]
+ )
}
-
+
let model = settings.rewriteModeSelectedModel ?? "gpt-4o"
let apiKey = settings.getAPIKey(for: providerID) ?? ""
-
+
let baseURL: String
if let provider = settings.savedProviders.first(where: { $0.id == providerID }) {
baseURL = provider.baseURL
@@ -138,7 +146,7 @@ final class RewriteModeService: ObservableObject {
} else {
baseURL = "https://api.openai.com/v1"
}
-
+
// Different system prompts for each mode
let systemPrompt: String
if isWriteMode {
@@ -168,74 +176,80 @@ final class RewriteModeService: ObservableObject {
Output ONLY the rewritten text. No explanations, no quotes around the text, no preamble.
"""
}
-
+
var apiMessages: [[String: Any]] = [
- ["role": "system", "content": systemPrompt]
+ ["role": "system", "content": systemPrompt],
]
-
+
for msg in messages {
apiMessages.append(["role": msg.role == .user ? "user" : "assistant", "content": msg.content])
}
-
+
// Check streaming setting
let enableStreaming = settings.enableAIStreaming
-
+
// Reasoning models (o1, o3, gpt-5) don't support temperature parameter at all
let isReasoningModel = model.hasPrefix("o1") || model.hasPrefix("o3") || model.hasPrefix("gpt-5")
var body: [String: Any] = [
"model": model,
- "messages": apiMessages
+ "messages": apiMessages,
]
-
+
// Only add temperature for non-reasoning models
if !isReasoningModel {
body["temperature"] = 0.7
}
-
+
if enableStreaming {
// TODO: Streamed text is still buffered; add incremental UI updates so write mode visibly streams.
body["stream"] = true
}
-
+
let endpoint = baseURL.hasSuffix("/chat/completions") ? baseURL : "\(baseURL)/chat/completions"
guard let url = URL(string: endpoint) else {
throw NSError(domain: "RewriteMode", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])
}
-
+
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.httpBody = try JSONSerialization.data(withJSONObject: body)
-
+
if enableStreaming {
DebugLogger.shared.info("Using STREAMING mode for Write/Rewrite", source: "RewriteModeService")
return try await processStreamingResponse(request: request)
} else {
let (data, response) = try await URLSession.shared.data(for: request)
-
+
if let http = response as? HTTPURLResponse, http.statusCode >= 400 {
let err = String(data: data, encoding: .utf8) ?? "Unknown error"
throw NSError(domain: "RewriteMode", code: http.statusCode, userInfo: [NSLocalizedDescriptionKey: err])
}
-
+
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let choices = json["choices"] as? [[String: Any]],
let choice = choices.first,
let message = choice["message"] as? [String: Any],
- let content = message["content"] as? String else {
- throw NSError(domain: "RewriteMode", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid response"])
+ let content = message["content"] as? String
+ else {
+ throw NSError(
+ domain: "RewriteMode",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Invalid response"]
+ )
}
-
+
return content
}
}
-
+
// MARK: - Streaming Response Handler
+
private func processStreamingResponse(request: URLRequest) async throws -> String {
let (bytes, response) = try await URLSession.shared.bytes(for: request)
-
+
if let http = response as? HTTPURLResponse, http.statusCode >= 400 {
var errorData = Data()
for try await byte in bytes {
@@ -244,37 +258,41 @@ final class RewriteModeService: ObservableObject {
let errText = String(data: errorData, encoding: .utf8) ?? "Unknown error"
throw NSError(domain: "RewriteMode", code: http.statusCode, userInfo: [NSLocalizedDescriptionKey: errText])
}
-
+
var fullContent = ""
-
+
// Use efficient line-based iteration instead of byte-by-byte
for try await rawLine in bytes.lines {
let line = rawLine.trimmingCharacters(in: .whitespaces)
-
+
guard line.hasPrefix("data:") else { continue }
-
+
var jsonString = String(line.dropFirst(5))
if jsonString.hasPrefix(" ") {
jsonString = String(jsonString.dropFirst(1))
}
-
+
if jsonString.trimmingCharacters(in: .whitespaces) == "[DONE]" {
continue
}
-
+
if let jsonData = jsonString.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any],
let choices = json["choices"] as? [[String: Any]],
let firstChoice = choices.first,
let delta = firstChoice["delta"] as? [String: Any],
- let content = delta["content"] as? String {
+ let content = delta["content"] as? String
+ {
fullContent += content
// Update UI in real-time for streaming feedback
rewrittenText = fullContent
}
}
-
- DebugLogger.shared.debug("Streaming complete. Content length: \(fullContent.count)", source: "RewriteModeService")
+
+ DebugLogger.shared.debug(
+ "Streaming complete. Content length: \(fullContent.count)",
+ source: "RewriteModeService"
+ )
return fullContent.isEmpty ? "" : fullContent
}
}
diff --git a/Sources/Fluid/Services/SimpleUpdater.swift b/Sources/Fluid/Services/SimpleUpdater.swift
index 9822dd0e..1a09a647 100644
--- a/Sources/Fluid/Services/SimpleUpdater.swift
+++ b/Sources/Fluid/Services/SimpleUpdater.swift
@@ -1,5 +1,5 @@
-import Foundation
import AppKit
+import Foundation
import PromiseKit
enum SimpleUpdateError: Error, LocalizedError {
@@ -32,6 +32,7 @@ struct GHRelease: Decodable {
let browser_download_url: URL
let content_type: String
}
+
let tag_name: String
let prerelease: Bool
let assets: [Asset]
@@ -47,33 +48,33 @@ final class SimpleUpdater {
// Allowed Apple Developer Team IDs for code-sign validation
// Configured per your request; restrict to your actual Team ID only.
private let allowedTeamIDs: Set<String> = [
- "V4J43B279J"
+ "V4J43B279J",
]
// Fetch latest release notes from GitHub
func fetchLatestReleaseNotes(owner: String, repo: String) async throws -> (version: String, notes: String) {
let releasesURL = URL(string: "https://api.github.com/repos/\(owner)/\(repo)/releases")!
-
+
let (data, response) = try await URLSession.shared.data(from: releasesURL)
guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
throw SimpleUpdateError.invalidResponse
}
-
+
let releases: [GHRelease]
do {
releases = try JSONDecoder().decode([GHRelease].self, from: data)
} catch {
throw SimpleUpdateError.jsonDecoding
}
-
+
// Get latest non-prerelease release
guard let latest = releases.first(where: { !$0.prerelease }) else {
throw SimpleUpdateError.noSuitableRelease
}
-
+
let version = latest.tag_name
let notes = latest.body ?? "No release notes available."
-
+
return (version, notes)
}
@@ -142,15 +143,21 @@ final class SimpleUpdater {
let prefix = "\(repo.lowercased())-\(verString)"
let asset = latest.assets.first { asset in
let base = (asset.name as NSString).deletingPathExtension.lowercased()
- return (base == prefix) && (asset.content_type == "application/zip" || asset.content_type == "application/x-zip-compressed")
+ return (base == prefix) &&
+ (asset.content_type == "application/zip" || asset.content_type == "application/x-zip-compressed")
} ?? latest.assets.first { asset in
let base = (asset.name as NSString).deletingPathExtension.lowercased()
- return (base == prefix)
+ return base == prefix
}
guard let asset = asset else { throw SimpleUpdateError.noAsset }
- let tempDir = try FileManager.default.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: Bundle.main.bundleURL, create: true)
+ let tempDir = try FileManager.default.url(
+ for: .itemReplacementDirectory,
+ in: .userDomainMask,
+ appropriateFor: Bundle.main.bundleURL,
+ create: true
+ )
let downloadURL = tempDir.appendingPathComponent(asset.browser_download_url.lastPathComponent)
do {
@@ -187,7 +194,7 @@ final class SimpleUpdater {
if identity.hasPrefix("TeamIdentifier=") {
return String(identity.dropFirst("TeamIdentifier=".count))
}
-
+
// Handle Authority= format (extract team ID from parentheses)
guard let l = identity.lastIndex(of: "("), let r = identity.lastIndex(of: ")"), l < r else { return nil }
let inside = identity[identity.index(after: l)..<r]
@@ -204,7 +211,7 @@ final class SimpleUpdater {
let newTeam = teamID(from: newID)
let sameTeam = (curTeam != nil && curTeam == newTeam)
let bothAllowed = (curTeam != nil && newTeam != nil && allowedTeamIDs.contains(curTeam!) && allowedTeamIDs.contains(newTeam!))
-
+
guard sameIdentity || sameTeam || bothAllowed else {
print("SimpleUpdater: Code-sign mismatch. Current=\(curID) New=\(newID)")
print("SimpleUpdater: Current Team=\(curTeam ?? "none") New Team=\(newTeam ?? "none")")
@@ -217,10 +224,11 @@ final class SimpleUpdater {
}
// MARK: - Helpers
+
private func parseVersion(_ s: String) -> [Int] {
let t = s.hasPrefix("v") ? String(s.dropFirst()) : s
let comps = t.split(separator: ".").map { Int($0) ?? 0 }
- return [comps[safe:0] ?? 0, comps[safe:1] ?? 0, comps[safe:2] ?? 0]
+ return [comps[safe: 0] ?? 0, comps[safe: 1] ?? 0, comps[safe: 2] ?? 0]
}
private func versionString(_ v: [Int]) -> String {
@@ -245,7 +253,15 @@ final class SimpleUpdater {
return try await withCheckedThrowingContinuation { cont in
proc.terminationHandler = { _ in
// Find first .app in workDir
- if let appURL = try? FileManager.default.contentsOfDirectory(at: workDir, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsSubdirectoryDescendants]).first(where: { $0.pathExtension == "app" }) {
+ if let appURL = try? FileManager.default.contentsOfDirectory(
+ at: workDir,
+ includingPropertiesForKeys: [
+ .isDirectoryKey,
+ ],
+ options: [.skipsSubdirectoryDescendants]
+ )
+ .first(where: { $0.pathExtension == "app"
+ }) {
cont.resume(returning: appURL)
} else {
cont.resume(throwing: SimpleUpdateError.unzipFailed)
@@ -266,7 +282,7 @@ final class SimpleUpdater {
proc.terminationHandler = { _ in
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let s = String(data: data, encoding: .utf8) ?? ""
-
+
// First try to get TeamIdentifier (most reliable)
if let teamLine = s.split(separator: "\n").first(where: { $0.hasPrefix("TeamIdentifier=") }) {
cont.resume(returning: String(teamLine))
@@ -285,27 +301,27 @@ final class SimpleUpdater {
// we need to replace the old app and use the new name
let installedAppName = installedAppURL.lastPathComponent
let downloadedAppName = downloadedAppURL.lastPathComponent
-
+
print("SimpleUpdater: Installing app - Current: \(installedAppName), New: \(downloadedAppName)")
-
+
let finalAppURL: URL
if installedAppName != downloadedAppName {
// App name changed - use the new name
finalAppURL = installedAppURL.deletingLastPathComponent().appendingPathComponent(downloadedAppName)
print("SimpleUpdater: App name changed, installing to: \(finalAppURL.path)")
-
+
// Safety check: ensure we don't overwrite an existing app with the new name
if FileManager.default.fileExists(atPath: finalAppURL.path) {
print("SimpleUpdater: Removing existing app at new location: \(finalAppURL.path)")
try FileManager.default.removeItem(at: finalAppURL)
}
-
+
// Remove old app if it exists
if FileManager.default.fileExists(atPath: installedAppURL.path) {
print("SimpleUpdater: Removing old app: \(installedAppURL.path)")
try FileManager.default.removeItem(at: installedAppURL)
}
-
+
// Move new app to Applications with new name
try FileManager.default.moveItem(at: downloadedAppURL, to: finalAppURL)
print("SimpleUpdater: Successfully installed new app at: \(finalAppURL.path)")
@@ -322,25 +338,25 @@ final class SimpleUpdater {
// Use modern NSWorkspace API for more reliable app launching
DispatchQueue.main.async {
print("SimpleUpdater: Attempting to relaunch app at: \(finalAppURL.path)")
-
+
// Verify the app exists before trying to launch
guard FileManager.default.fileExists(atPath: finalAppURL.path) else {
print("SimpleUpdater: ERROR - App not found at expected location: \(finalAppURL.path)")
// Don't terminate if we can't find the new app
return
}
-
+
let configuration = NSWorkspace.OpenConfiguration()
configuration.createsNewApplicationInstance = true
-
- NSWorkspace.shared.openApplication(at: finalAppURL, configuration: configuration) { app, error in
+
+ NSWorkspace.shared.openApplication(at: finalAppURL, configuration: configuration) { _, error in
if let error = error {
print("SimpleUpdater: Failed to relaunch app: \(error)")
print("SimpleUpdater: App location: \(finalAppURL.path)")
// Don't terminate if relaunch failed - let user manually restart
return
}
-
+
print("SimpleUpdater: Successfully relaunched app, terminating old instance")
// Give the new instance time to fully start before terminating
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
diff --git a/Sources/Fluid/Services/TerminalService.swift b/Sources/Fluid/Services/TerminalService.swift
index 6fa4023e..79bde7ea 100644
--- a/Sources/Fluid/Services/TerminalService.swift
+++ b/Sources/Fluid/Services/TerminalService.swift
@@ -3,9 +3,8 @@ import Foundation
/// Simple terminal command execution service
/// All responses are JSON-parsable for easy AI processing
final class TerminalService {
-
// MARK: - JSON Response Types
-
+
struct CommandResult: Codable {
let success: Bool
let command: String
@@ -14,9 +13,9 @@ final class TerminalService {
let exitCode: Int32
let executionTimeMs: Int
}
-
+
// MARK: - Tool Definition for AI
-
+
/// Returns the tool definition in OpenAI function calling format
static var toolDefinition: [String: Any] {
return [
@@ -24,40 +23,40 @@ final class TerminalService {
"function": [
"name": "execute_terminal_command",
"description": """
- Execute a terminal/shell command on the user's macOS computer.
- Use this for file operations (ls, cat, mkdir, rm), git commands, brew, npm, python, or any CLI tool.
-
- IMPORTANT: Follow the agentic workflow:
- 1. ALWAYS check prerequisites first (file exists, command available)
- 2. Execute the main action
- 3. Verify the result
-
- Returns JSON with: success (bool), output (stdout), error (stderr), exitCode, purpose.
- """,
+ Execute a terminal/shell command on the user's macOS computer.
+ Use this for file operations (ls, cat, mkdir, rm), git commands, brew, npm, python, or any CLI tool.
+
+ IMPORTANT: Follow the agentic workflow:
+ 1. ALWAYS check prerequisites first (file exists, command available)
+ 2. Execute the main action
+ 3. Verify the result
+
+ Returns JSON with: success (bool), output (stdout), error (stderr), exitCode, purpose.
+ """,
"parameters": [
"type": "object",
"properties": [
"command": [
"type": "string",
- "description": "The shell command to execute (e.g., 'ls -la', 'git status', 'rm file.txt')"
+ "description": "The shell command to execute (e.g., 'ls -la', 'git status', 'rm file.txt')",
],
"workingDirectory": [
"type": "string",
- "description": "Optional working directory path. Defaults to user's home directory."
+ "description": "Optional working directory path. Defaults to user's home directory.",
],
"purpose": [
"type": "string",
- "description": "Brief description of why this command is being run. Must be one of: 'checking' (verifying prerequisites), 'executing' (main action), 'verifying' (confirming result). Example: 'Checking if config.json exists'"
- ]
+ "description": "Brief description of why this command is being run. Must be one of: 'checking' (verifying prerequisites), 'executing' (main action), 'verifying' (confirming result). Example: 'Checking if config.json exists'",
+ ],
],
- "required": ["command", "purpose"]
- ]
- ]
+ "required": ["command", "purpose"],
+ ],
+ ],
]
}
-
+
// MARK: - Execution
-
+
/// Execute a terminal command and return JSON-parsable result
func execute(
command: String,
@@ -65,22 +64,22 @@ final class TerminalService {
timeout: TimeInterval = 30
) async -> CommandResult {
let startTime = Date()
-
+
let process = Process()
let outputPipe = Pipe()
let errorPipe = Pipe()
-
+
// Use zsh (default macOS shell)
process.executableURL = URL(fileURLWithPath: "/bin/zsh")
process.arguments = ["-c", command]
-
+
// Set working directory
if let dir = workingDirectory, !dir.isEmpty {
process.currentDirectoryURL = URL(fileURLWithPath: dir)
} else {
process.currentDirectoryURL = FileManager.default.homeDirectoryForCurrentUser
}
-
+
// Inherit user's environment (PATH, etc.)
var environment = ProcessInfo.processInfo.environment
// Ensure common paths are available
@@ -88,13 +87,13 @@ final class TerminalService {
environment["PATH"] = "/opt/homebrew/bin:/usr/local/bin:\(path)"
}
process.environment = environment
-
+
process.standardOutput = outputPipe
process.standardError = errorPipe
-
+
do {
try process.run()
-
+
// Wait with timeout
let timeoutTask = Task {
try await Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000))
@@ -102,18 +101,18 @@ final class TerminalService {
process.terminate()
}
}
-
+
process.waitUntilExit()
timeoutTask.cancel()
-
+
let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()
-
+
let output = String(data: outputData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let errorOutput = String(data: errorData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)
-
+
let executionTime = Int(Date().timeIntervalSince(startTime) * 1000)
-
+
return CommandResult(
success: process.terminationStatus == 0,
command: command,
@@ -122,7 +121,7 @@ final class TerminalService {
exitCode: process.terminationStatus,
executionTimeMs: executionTime
)
-
+
} catch {
let executionTime = Int(Date().timeIntervalSince(startTime) * 1000)
return CommandResult(
@@ -135,23 +134,21 @@ final class TerminalService {
)
}
}
-
+
/// Convert result to JSON string for AI processing
func resultToJSON(_ result: CommandResult) -> String {
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
-
+
if let data = try? encoder.encode(result),
- let json = String(data: data, encoding: .utf8) {
+ let json = String(data: data, encoding: .utf8)
+ {
return json
}
-
+
// Fallback
return """
{"success": \(result.success), "output": "\(result.output)", "exitCode": \(result.exitCode)}
"""
}
}
-
-
-
diff --git a/Sources/Fluid/Services/TextSelectionService.swift b/Sources/Fluid/Services/TextSelectionService.swift
index bde36625..b5c62574 100644
--- a/Sources/Fluid/Services/TextSelectionService.swift
+++ b/Sources/Fluid/Services/TextSelectionService.swift
@@ -1,12 +1,12 @@
-import Foundation
import AppKit
import ApplicationServices
+import Foundation
final class TextSelectionService {
static let shared = TextSelectionService()
-
+
private init() {}
-
+
/// Attempts to get the currently selected text using Accessibility APIs
func getSelectedText() -> String? {
// Check accessibility permissions
@@ -14,14 +14,14 @@ final class TextSelectionService {
DebugLogger.shared.error("Accessibility permissions not granted", source: "TextSelectionService")
return nil
}
-
+
// 1. Try to get the system-wide focused element
if let focusedElement = getFocusedElement() {
if let text = getSelectedText(from: focusedElement) {
return text
}
}
-
+
// 2. Fallback: Try to find focused element in frontmost app
if let frontmostApp = NSWorkspace.shared.frontmostApplication {
let appElement = AXUIElementCreateApplication(frontmostApp.processIdentifier)
@@ -31,48 +31,56 @@ final class TextSelectionService {
}
}
}
-
+
return nil
}
-
+
// MARK: - Private Helpers
-
+
private func getFocusedElement() -> AXUIElement? {
let systemWideElement = AXUIElementCreateSystemWide()
var focusedElement: CFTypeRef?
-
- let result = AXUIElementCopyAttributeValue(systemWideElement, kAXFocusedUIElementAttribute as CFString, &focusedElement)
-
+
+ let result = AXUIElementCopyAttributeValue(
+ systemWideElement,
+ kAXFocusedUIElementAttribute as CFString,
+ &focusedElement
+ )
+
if result == .success {
return (focusedElement as! AXUIElement)
}
-
+
return nil
}
-
+
private func getFocusedElement(from appElement: AXUIElement) -> AXUIElement? {
var focusedElement: CFTypeRef?
- let result = AXUIElementCopyAttributeValue(appElement, kAXFocusedUIElementAttribute as CFString, &focusedElement)
-
+ let result = AXUIElementCopyAttributeValue(
+ appElement,
+ kAXFocusedUIElementAttribute as CFString,
+ &focusedElement
+ )
+
if result == .success {
return (focusedElement as! AXUIElement)
}
-
+
return nil
}
-
+
private func getSelectedText(from element: AXUIElement) -> String? {
var value: CFTypeRef?
let result = AXUIElementCopyAttributeValue(element, kAXSelectedTextAttribute as CFString, &value)
-
+
if result == .success, let text = value as? String {
return text
}
-
+
// Fallback: If no text is selected, some apps might return the value attribute
// But for "rewrite selected", we strictly want selected text.
// We could optionally return all text if we wanted to rewrite the whole field.
-
+
return nil
}
}
diff --git a/Sources/Fluid/Services/TranscriptionProvider.swift b/Sources/Fluid/Services/TranscriptionProvider.swift
index 5ee5a17e..f3ed9bca 100644
--- a/Sources/Fluid/Services/TranscriptionProvider.swift
+++ b/Sources/Fluid/Services/TranscriptionProvider.swift
@@ -7,7 +7,7 @@ import Foundation
struct ASRTranscriptionResult {
let text: String
let confidence: Float
-
+
init(text: String, confidence: Float = 1.0) {
self.text = text
self.confidence = confidence
@@ -21,25 +21,25 @@ struct ASRTranscriptionResult {
protocol TranscriptionProvider {
/// Display name of the provider
var name: String { get }
-
+
/// Whether this provider is available on the current system
var isAvailable: Bool { get }
-
+
/// Whether models are downloaded and ready
var isReady: Bool { get }
-
+
/// Download/prepare models for transcription
/// - Parameter progressHandler: Optional callback for download progress (0.0 to 1.0)
func prepare(progressHandler: ((Double) -> Void)?) async throws
-
+
/// Transcribe audio samples
/// - Parameter samples: 16kHz mono PCM float samples
/// - Returns: Transcription result with text and confidence
func transcribe(_ samples: [Float]) async throws -> ASRTranscriptionResult
-
+
/// Check if models exist on disk (without loading them)
func modelsExistOnDisk() -> Bool
-
+
/// Clear cached models
func clearCache() async throws
}
@@ -47,7 +47,7 @@ protocol TranscriptionProvider {
// Default implementation for optional methods
extension TranscriptionProvider {
func modelsExistOnDisk() -> Bool { return false }
- func clearCache() async throws { }
+ func clearCache() async throws {}
}
// MARK: - Architecture Detection
@@ -56,7 +56,7 @@ extension TranscriptionProvider {
enum CPUArchitecture {
case applesilicon
case intel
-
+
static var current: CPUArchitecture {
#if arch(arm64)
return .applesilicon
@@ -64,11 +64,11 @@ enum CPUArchitecture {
return .intel
#endif
}
-
+
static var isAppleSilicon: Bool {
current == .applesilicon
}
-
+
static var isIntel: Bool {
current == .intel
}
diff --git a/Sources/Fluid/Services/TypingService.swift b/Sources/Fluid/Services/TypingService.swift
index 052d5455..8e939aac 100644
--- a/Sources/Fluid/Services/TypingService.swift
+++ b/Sources/Fluid/Services/TypingService.swift
@@ -1,36 +1,35 @@
-import Foundation
import AppKit
+import Foundation
-final class TypingService
-{
+final class TypingService {
// Logging toggle (off by default). Enable by setting env FLUID_TYPING_LOGS=1
// or UserDefaults bool for key "enableTypingLogs".
private static var isLoggingEnabled: Bool {
if let env = ProcessInfo.processInfo.environment["FLUID_TYPING_LOGS"], env == "1" { return true }
return UserDefaults.standard.bool(forKey: "enableTypingLogs")
}
+
private func log(_ message: @autoclosure () -> String) {
if Self.isLoggingEnabled { print(message()) }
}
private var isCurrentlyTyping = false
-
- func typeTextInstantly(_ text: String)
- {
+
+ func typeTextInstantly(_ text: String) {
log("[TypingService] ENTRY: typeTextInstantly called with text length: \(text.count)")
log("[TypingService] Text preview: \"\(String(text.prefix(100)))\"")
-
- guard text.isEmpty == false else {
+
+ guard text.isEmpty == false else {
log("[TypingService] ERROR: Empty text provided, aborting")
- return
+ return
}
-
+
// Prevent concurrent typing operations
guard !isCurrentlyTyping else {
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")
@@ -40,37 +39,35 @@ final class TypingService
log("[TypingService] Accessibility check passed, proceeding with text injection")
isCurrentlyTyping = true
-
- DispatchQueue.global(qos: .userInitiated).async
- {
- defer {
- self.isCurrentlyTyping = false
+
+ DispatchQueue.global(qos: .userInitiated).async {
+ defer {
+ self.isCurrentlyTyping = false
self.log("[TypingService] Typing operation completed, isCurrentlyTyping set to false")
}
-
+
self.log("[TypingService] Starting async text insertion process")
// Longer delay to ensure target app is ready and focused
- usleep(200000) // 200ms delay - more reliable for app switching
+ usleep(200_000) // 200ms delay - more reliable for app switching
self.log("[TypingService] Delay completed, calling insertTextInstantly")
self.insertTextInstantly(text)
}
}
- private func insertTextInstantly(_ text: String)
- {
+ 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 ? "..." : "")\"")
-
+
// Get frontmost app info
if let frontApp = NSWorkspace.shared.frontmostApplication {
log("[TypingService] Target app: \(frontApp.localizedName ?? "Unknown") (\(frontApp.bundleIdentifier ?? "Unknown"))")
} else {
log("[TypingService] WARNING: Could not get frontmost application")
}
-
+
// Check if we have permission to create events
log("[TypingService] Accessibility trusted: \(AXIsProcessTrusted())")
-
+
// Try direct bulk CGEvent insertion (NO CLIPBOARD)
log("[TypingService] Trying INSTANT bulk CGEvent insertion (no clipboard)")
if insertTextBulkInstant(text) {
@@ -79,45 +76,45 @@ final class TypingService
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)'")
+ if index % 10 == 0 { // Log every 10th character to avoid spam
+ log("[TypingService] Typing character \(index + 1)/\(text.count): '\(char)'")
}
typeCharacter(char)
usleep(1000) // Small delay between characters (1ms)
}
-
+
log("[TypingService] Character-by-character typing completed")
}
}
-
+
private func insertTextBulkInstant(_ text: String) -> Bool {
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")
return false
}
-
+
// Convert entire text to UTF16
let utf16Array = Array(text.utf16)
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!")
-
+
return true
}
-
+
private func insertTextViaAccessibility(_ text: String) -> Bool {
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...")
if let textElement = getFocusedTextElement() {
@@ -126,7 +123,7 @@ final class TypingService
return true
}
}
-
+
// Strategy 2: Traverse frontmost app UI hierarchy to find text elements
log("[TypingService] Strategy 2: Traversing app UI hierarchy...")
if let textElement = findTextElementInFrontmostApp() {
@@ -135,7 +132,7 @@ final class TypingService
return true
}
}
-
+
// Strategy 3: Find element with keyboard focus
log("[TypingService] Strategy 3: Looking for keyboard focus...")
if let textElement = findKeyboardFocusedElement() {
@@ -144,17 +141,21 @@ final class TypingService
return true
}
}
-
+
log("[TypingService] All Accessibility API strategies failed")
return false
}
-
+
private func getFocusedTextElement() -> AXUIElement? {
let systemWideElement = AXUIElementCreateSystemWide()
var focusedElement: CFTypeRef?
-
- let result = AXUIElementCopyAttributeValue(systemWideElement, kAXFocusedUIElementAttribute as CFString, &focusedElement)
-
+
+ let result = AXUIElementCopyAttributeValue(
+ systemWideElement,
+ kAXFocusedUIElementAttribute as CFString,
+ &focusedElement
+ )
+
if result == .success, let element = focusedElement {
let axElement = element as! AXUIElement
if let role = getElementAttribute(axElement, kAXRoleAttribute as CFString) {
@@ -164,23 +165,23 @@ final class TypingService
} else {
log("[TypingService] Could not get focused UI element - result: \(result.rawValue)")
}
-
+
return nil
}
-
+
private func findTextElementInFrontmostApp() -> AXUIElement? {
guard let frontmostApp = NSWorkspace.shared.frontmostApplication else {
log("[TypingService] Could not get frontmost app")
return nil
}
-
+
let appElement = AXUIElementCreateApplication(frontmostApp.processIdentifier)
return findTextElementRecursively(appElement, depth: 0, maxDepth: 8)
}
-
+
private func findTextElementRecursively(_ element: AXUIElement, depth: Int, maxDepth: Int) -> AXUIElement? {
if depth > maxDepth { return nil }
-
+
// Check if this element is a text input element
if let role = getElementAttribute(element, kAXRoleAttribute as CFString) {
let textRoles = ["AXTextField", "AXTextArea", "AXComboBox", "AXSearchField", "AXStaticText"]
@@ -189,11 +190,11 @@ final class TypingService
return element
}
}
-
+
// Get children and search recursively
var children: CFTypeRef?
let result = AXUIElementCopyAttributeValue(element, kAXChildrenAttribute as CFString, &children)
-
+
if result == .success, let childrenArray = children as? [AXUIElement] {
for child in childrenArray.prefix(10) { // Limit to first 10 children per level
if let found = findTextElementRecursively(child, depth: depth + 1, maxDepth: maxDepth) {
@@ -201,18 +202,22 @@ final class TypingService
}
}
}
-
+
return nil
}
-
+
private func findKeyboardFocusedElement() -> AXUIElement? {
guard let frontmostApp = NSWorkspace.shared.frontmostApplication else { return nil }
-
+
let appElement = AXUIElementCreateApplication(frontmostApp.processIdentifier)
var focusedElement: CFTypeRef?
-
- let result = AXUIElementCopyAttributeValue(appElement, kAXFocusedUIElementAttribute as CFString, &focusedElement)
-
+
+ let result = AXUIElementCopyAttributeValue(
+ appElement,
+ kAXFocusedUIElementAttribute as CFString,
+ &focusedElement
+ )
+
if result == .success, let element = focusedElement {
let axElement = element as! AXUIElement
if let role = getElementAttribute(axElement, kAXRoleAttribute as CFString) {
@@ -220,39 +225,39 @@ final class TypingService
return axElement
}
}
-
+
return nil
}
-
+
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)")
-
+
if let title = getElementAttribute(element, kAXTitleAttribute as CFString) {
log("[TypingService] Element title: \(title)")
}
}
-
+
// Try multiple approaches for text insertion
log("[TypingService] Trying approach 1: Direct kAXValueAttribute")
if setTextViaValue(element, text) {
return true
}
-
+
log("[TypingService] Trying approach 2: kAXSelectedTextAttribute (replace selection)")
if setTextViaSelection(element, text) {
return true
}
-
+
log("[TypingService] Trying approach 3: Insert text at insertion point")
if insertTextAtInsertionPoint(element, text) {
return true
}
-
+
return false
}
-
+
private func getElementAttribute(_ element: AXUIElement, _ attribute: CFString) -> String? {
var value: CFTypeRef?
let result = AXUIElementCopyAttributeValue(element, attribute, &value)
@@ -261,11 +266,12 @@ final class TypingService
}
return nil
}
- //Why is it working now? And why is it not working now?
+
+ // Why is it working now? And why is it not working now?
private func setTextViaValue(_ element: AXUIElement, _ text: String) -> Bool {
let cfText = text as CFString
let result = AXUIElementSetAttributeValue(element, kAXValueAttribute as CFString, cfText)
-
+
if result == .success {
log("[TypingService] SUCCESS: Set text via kAXValueAttribute")
return true
@@ -274,16 +280,20 @@ final class TypingService
return false
}
}
-
+
private func setTextViaSelection(_ element: AXUIElement, _ text: String) -> Bool {
// First, select all existing text
- let selectAllResult = AXUIElementSetAttributeValue(element, kAXSelectedTextAttribute as CFString, "" as CFString)
+ let selectAllResult = AXUIElementSetAttributeValue(
+ element,
+ kAXSelectedTextAttribute as CFString,
+ "" as CFString
+ )
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")
return true
@@ -292,17 +302,21 @@ final class TypingService
return false
}
}
-
+
private func insertTextAtInsertionPoint(_ element: AXUIElement, _ text: String) -> Bool {
// Try to get the insertion point
var insertionPoint: CFTypeRef?
- let getResult = AXUIElementCopyAttributeValue(element, kAXInsertionPointLineNumberAttribute as CFString, &insertionPoint)
+ let getResult = AXUIElementCopyAttributeValue(
+ element,
+ kAXInsertionPointLineNumberAttribute as CFString,
+ &insertionPoint
+ )
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")
return true
@@ -311,78 +325,81 @@ final class TypingService
return false
}
}
-
+
private func insertTextBulk(_ text: String) -> Bool {
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")
return false
}
-
+
let targetPID = frontApp.processIdentifier
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)
+
+ // 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")
-
+
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")
return false
}
-
+
if index % 5 == 0 && index > 0 {
log("[TypingService] Bulk insertion progress: \(index + 1)/\(words.count) words")
}
}
-
+
log("[TypingService] Successfully completed bulk word-by-word insertion")
return true
}
-
+
private func insertWordViaCGEvent(_ word: String, targetPID: pid_t) -> Bool {
// Convert word to UTF16 for CGEvent
let utf16Array = Array(word.utf16)
-
+
// Create keyboard event for this word
guard let keyDownEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true),
- let keyUpEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false) else {
+ let keyUpEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)
+ else {
log("[TypingService] ERROR: Failed to create CGEvents for word: '\(word)'")
return false
}
-
+
// Set the unicode string for both events
keyDownEvent.keyboardSetUnicodeString(stringLength: utf16Array.count, unicodeString: utf16Array)
keyUpEvent.keyboardSetUnicodeString(stringLength: utf16Array.count, unicodeString: utf16Array)
-
+
// Post events to specific PID
keyDownEvent.postToPid(targetPID)
usleep(2000) // 2ms delay between keyDown and keyUp
keyUpEvent.postToPid(targetPID)
-
+
return true
}
-
+
private func typeCharacter(_ char: Character) {
let charString = String(char)
let utf16Array = Array(charString.utf16)
-
+
// Create keyboard events for this character
guard let keyDownEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true),
- let keyUpEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false) else {
+ let keyUpEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)
+ else {
log("[TypingService] ERROR: Failed to create CGEvents for character: \(char)")
return
}
-
+
// Set the unicode string for both events
keyDownEvent.keyboardSetUnicodeString(stringLength: utf16Array.count, unicodeString: utf16Array)
keyUpEvent.keyboardSetUnicodeString(stringLength: utf16Array.count, unicodeString: utf16Array)
-
+
// Post the events
keyDownEvent.post(tap: .cghidEventTap)
usleep(2000) // Short delay between key down and up (2ms)
diff --git a/Sources/Fluid/Services/WhisperProvider.swift b/Sources/Fluid/Services/WhisperProvider.swift
index 08c05590..97092a57 100644
--- a/Sources/Fluid/Services/WhisperProvider.swift
+++ b/Sources/Fluid/Services/WhisperProvider.swift
@@ -4,86 +4,93 @@ import SwiftWhisper
/// TranscriptionProvider implementation using SwiftWhisper (whisper.cpp) for Intel Macs.
/// This provides on-device speech recognition that works on Intel x86_64 architecture.
final class WhisperProvider: TranscriptionProvider {
-
let name = "Whisper (Intel/Universal)"
-
+
/// Whether this provider is supported on the current system.
/// SwiftWhisper (whisper.cpp) works on both Intel and Apple Silicon.
var isAvailable: Bool {
true
}
-
+
private var whisper: Whisper?
private(set) var isReady: Bool = false
private var loadedModelName: String?
-
+
/// Model filename to use - reads from the unified SpeechModel setting
/// Models: tiny (~75MB), base (~142MB), small (~466MB), medium (~1.5GB), large (~2.9GB)
private var modelName: String {
SettingsStore.shared.selectedSpeechModel.whisperModelFile ?? "ggml-base.bin"
}
-
+
private var modelURL: URL {
let cacheDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
return cacheDir.appendingPathComponent("WhisperModels").appendingPathComponent(modelName)
}
-
+
private var modelDirectory: URL {
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 {
- DebugLogger.shared.info("WhisperProvider: Model changed from \(loadedModelName ?? "nil") to \(currentModelName), forcing reload", source: "WhisperProvider")
+ if isReady, loadedModelName != currentModelName {
+ DebugLogger.shared
+ .info(
+ "WhisperProvider: Model changed from \(loadedModelName ?? "nil") to \(currentModelName), forcing reload",
+ source: "WhisperProvider"
+ )
isReady = false
whisper = nil
loadedModelName = nil
}
-
+
guard 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)
-
+
// Download model if not present
if !FileManager.default.fileExists(atPath: modelURL.path) {
DebugLogger.shared.info("WhisperProvider: Downloading Whisper model...", source: "WhisperProvider")
try await downloadModel(progressHandler: progressHandler)
}
-
+
// Load the model
DebugLogger.shared.info("WhisperProvider: Loading Whisper model...", source: "WhisperProvider")
whisper = Whisper(fromFileURL: modelURL)
-
+
loadedModelName = currentModelName
isReady = true
DebugLogger.shared.info("WhisperProvider: Model ready (\(currentModelName))", source: "WhisperProvider")
}
-
+
func transcribe(_ samples: [Float]) async throws -> ASRTranscriptionResult {
guard let whisper = whisper else {
- throw NSError(domain: "WhisperProvider", code: -1,
- userInfo: [NSLocalizedDescriptionKey: "Whisper model not loaded"])
+ throw NSError(
+ domain: "WhisperProvider",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Whisper model not loaded"]
+ )
}
-
+
// SwiftWhisper expects 16kHz PCM audio frames (which is what we receive)
let segments = try await whisper.transcribe(audioFrames: samples)
-
+
// Combine all segments into one string
- let fullText = segments.map { $0.text }.joined(separator: " ").trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
-
+ let fullText = segments.map { $0.text }.joined(separator: " ")
+ .trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
+
// SwiftWhisper doesn't provide confidence, so we use 1.0
return ASRTranscriptionResult(text: fullText, confidence: 1.0)
}
-
+
func modelsExistOnDisk() -> Bool {
return FileManager.default.fileExists(atPath: modelURL.path)
}
-
+
func clearCache() async throws {
if FileManager.default.fileExists(atPath: modelDirectory.path) {
try FileManager.default.removeItem(at: modelDirectory)
@@ -92,39 +99,50 @@ final class WhisperProvider: TranscriptionProvider {
whisper = nil
loadedModelName = nil
}
-
+
// MARK: - Model Download
-
+
private func downloadModel(progressHandler: ((Double) -> Void)?) async throws {
// Whisper models are hosted on Hugging Face
let modelURLString = "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/\(modelName)"
-
+
guard let url = URL(string: modelURLString) else {
- throw NSError(domain: "WhisperProvider", code: -1,
- userInfo: [NSLocalizedDescriptionKey: "Invalid model URL"])
+ throw NSError(
+ domain: "WhisperProvider",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Invalid model URL"]
+ )
}
-
+
DebugLogger.shared.info("WhisperProvider: Downloading from \(modelURLString)", source: "WhisperProvider")
-
+
do {
let (tempURL, response) = try await URLSession.shared.download(from: url)
-
+
guard let httpResponse = response as? HTTPURLResponse else {
- throw NSError(domain: "WhisperProvider", code: -1,
- userInfo: [NSLocalizedDescriptionKey: "Invalid server response"])
+ throw NSError(
+ domain: "WhisperProvider",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Invalid server response"]
+ )
}
-
+
guard httpResponse.statusCode == 200 else {
- throw NSError(domain: "WhisperProvider", code: httpResponse.statusCode,
- userInfo: [NSLocalizedDescriptionKey: "Failed to download model (HTTP \(httpResponse.statusCode))"])
+ throw NSError(
+ domain: "WhisperProvider",
+ code: httpResponse.statusCode,
+ userInfo: [
+ NSLocalizedDescriptionKey: "Failed to download model (HTTP \(httpResponse.statusCode))",
+ ]
+ )
}
-
+
// Move to final location
if FileManager.default.fileExists(atPath: modelURL.path) {
try FileManager.default.removeItem(at: modelURL)
}
try FileManager.default.moveItem(at: tempURL, to: modelURL)
-
+
DebugLogger.shared.info("WhisperProvider: Model downloaded successfully", source: "WhisperProvider")
} catch let error as NSError {
// Provide user-friendly error messages
@@ -140,8 +158,11 @@ final class WhisperProvider: TranscriptionProvider {
default:
message = "Network error: \(error.localizedDescription)"
}
- throw NSError(domain: "WhisperProvider", code: error.code,
- userInfo: [NSLocalizedDescriptionKey: message])
+ throw NSError(
+ domain: "WhisperProvider",
+ code: error.code,
+ userInfo: [NSLocalizedDescriptionKey: message]
+ )
}
throw error
}
diff --git a/Sources/Fluid/TalkingAnimations.swift b/Sources/Fluid/TalkingAnimations.swift
index 2043c1ad..78aec8f7 100644
--- a/Sources/Fluid/TalkingAnimations.swift
+++ b/Sources/Fluid/TalkingAnimations.swift
@@ -1,40 +1,34 @@
-//
-// TalkingAnimations.swift
-// fluid
-//
-// Created by Assistant
-//
-
-import SwiftUI
-import Combine
import AppKit
+import Combine
import CoreGraphics
+import SwiftUI
// MARK: - Active App Tracker
+
class ActiveAppTracker: ObservableObject {
@Published var activeAppName: String = "Unknown App"
@Published var activeWindowTitle: String = ""
private var timer: Timer?
-
+
init() {
updateActiveApp()
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.updateActiveApp()
}
}
-
+
private func updateActiveApp() {
if let frontmostApp = NSWorkspace.shared.frontmostApplication {
activeAppName = frontmostApp.localizedName ?? "Unknown App"
activeWindowTitle = fetchFrontmostWindowTitle(for: frontmostApp.processIdentifier) ?? ""
}
}
-
+
private func fetchFrontmostWindowTitle(for ownerPid: pid_t) -> String? {
let options: CGWindowListOption = [.optionOnScreenOnly, .excludeDesktopElements]
guard let windowInfo = CGWindowListCopyWindowInfo(options, kCGNullWindowID) as? [[String: Any]] else {
@@ -55,15 +49,16 @@ class ActiveAppTracker: ObservableObject {
}
// MARK: - Spokenly-Style Talking Animation Configuration
+
struct TalkingAnimationConfig: AudioVisualizationConfig {
let noiseThreshold: CGFloat // Now dynamic - set from user preference
let maxAnimationScale: CGFloat = 2.5
let animationSpring: Animation = .spring(response: 0.3, dampingFraction: 0.7, blendDuration: 0.1)
-
+
init(noiseThreshold: CGFloat = 0.4) {
self.noiseThreshold = max(0.01, min(0.8, noiseThreshold)) // Clamp to valid range
}
-
+
// Bar-specific properties
let barCount: Int = 12
let barSpacing: CGFloat = 3
@@ -73,7 +68,7 @@ struct TalkingAnimationConfig: AudioVisualizationConfig {
let animationSpeed: Double = 0.12 // Optimized animation speed
let containerWidth: CGFloat = 140
let containerHeight: CGFloat = 40
-
+
// Performance optimization settings - much faster and more responsive
let maxFPS: Double = 60.0 // Higher FPS for smoothness
let idleAnimationReduction: Int = 4 // Less aggressive reduction
@@ -83,19 +78,20 @@ struct TalkingAnimationConfig: AudioVisualizationConfig {
}
// MARK: - Spokenly-Style Audio Visualization View
+
struct TalkingAudioVisualizationView: View {
@StateObject private var data: AudioVisualizationData
- @State private var dynamicNoiseThreshold: CGFloat = CGFloat(SettingsStore.shared.visualizerNoiseThreshold)
-
+ @State private var dynamicNoiseThreshold: CGFloat = .init(SettingsStore.shared.visualizerNoiseThreshold)
+
// Dynamic config that updates with settings
private var config: TalkingAnimationConfig {
TalkingAnimationConfig(noiseThreshold: dynamicNoiseThreshold)
}
-
+
init(audioLevelPublisher: AnyPublisher<CGFloat, Never>) {
- self._data = StateObject(wrappedValue: AudioVisualizationData(audioLevelPublisher: audioLevelPublisher))
+ _data = StateObject(wrappedValue: AudioVisualizationData(audioLevelPublisher: audioLevelPublisher))
}
-
+
var body: some View {
SpokenlyWaveform(
config: config,
@@ -105,73 +101,76 @@ struct TalkingAudioVisualizationView: View {
.onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in
// Update threshold when UserDefaults changes
let newThreshold = CGFloat(SettingsStore.shared.visualizerNoiseThreshold)
- if newThreshold != dynamicNoiseThreshold {
- dynamicNoiseThreshold = newThreshold
+ if newThreshold != self.dynamicNoiseThreshold {
+ self.dynamicNoiseThreshold = newThreshold
}
}
}
}
// MARK: - Spokenly-Style Clean Waveform
+
struct SpokenlyWaveform: View {
let config: TalkingAnimationConfig
let audioLevel: CGFloat
let isActive: Bool
-
+
@State private var barHeights: [CGFloat] = []
@State private var barOpacities: [Double] = []
@State private var animationPhases: [Double] = []
@State private var animationTrigger: Int = 0
@State private var lastUpdateTime: TimeInterval = 0
@State private var isViewVisible: Bool = true
-
- private let animationTimer = Timer.publish(every: 0.033, on: .main, in: .common).autoconnect() // 30 FPS base timer - safer for CoreML concurrency
-
+
+ private let animationTimer = Timer.publish(every: 0.033, on: .main, in: .common)
+ .autoconnect() // 30 FPS base timer - safer for CoreML concurrency
+
var body: some View {
HStack(spacing: config.barSpacing) {
- ForEach(0..<config.barCount, id: \.self) { index in
+ ForEach(0..<self.config.barCount, id: \.self) { index in
SpokenlyBar(
- height: index < barHeights.count ? barHeights[index] : config.minBarHeight,
- opacity: index < barOpacities.count ? barOpacities[index] : 0.4,
+ height: index < self.barHeights.count ? self.barHeights[index] : self.config.minBarHeight,
+ opacity: index < self.barOpacities.count ? self.barOpacities[index] : 0.4,
index: index,
- config: config,
- isActive: isActive
+ config: self.config,
+ isActive: self.isActive
)
}
}
.frame(width: config.containerWidth, height: config.containerHeight)
.onAppear {
- initializeBars()
- isViewVisible = true
+ self.initializeBars()
+ self.isViewVisible = true
}
.onDisappear {
- isViewVisible = false
+ self.isViewVisible = false
}
.onReceive(animationTimer) { _ in
- if isViewVisible {
- updateBars()
+ if self.isViewVisible {
+ self.updateBars()
}
}
}
-
+
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) }
}
-
+
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 = isActive ? 30.0 : 20.0 // Lower FPS to reduce state update conflicts
let frameTime = 1.0 / targetFPS
if currentTime - lastUpdateTime < frameTime { return }
lastUpdateTime = currentTime
-
+
// Safety check
- guard barHeights.count == config.barCount && barOpacities.count == config.barCount else { return }
-
+ guard barHeights.count == config.barCount,
+ barOpacities.count == config.barCount else { return }
+
// Direct real-time animation based on current audio level
if audioLevel <= config.noiseThreshold { // USE THE USER-CONTROLLABLE THRESHOLD!
// Complete stillness
@@ -182,37 +181,37 @@ struct SpokenlyWaveform: View {
} else {
// Real-time responsive animation
let audioInfluence = Double(audioLevel) * 2.0
-
+
for i in 0..<min(config.barCount, barHeights.count) {
// Fast frequency for immediate response
let frequency = 3.0 + Double(i) * 0.4
let phase = 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))
-
+
barHeights[i] = newHeight
barOpacities[i] = 0.6 + (audioInfluence * 0.4)
}
}
}
-
}
// MARK: - Premium Talking Animation Configuration
+
struct EnhancedTalkingAnimationConfig: AudioVisualizationConfig {
let noiseThreshold: CGFloat // Now dynamic - set from user preference
let maxAnimationScale: CGFloat = 2.8
let animationSpring: Animation = .interpolatingSpring(stiffness: 400, damping: 20)
-
+
init(noiseThreshold: CGFloat = 0.4) {
self.noiseThreshold = max(0.01, min(0.8, noiseThreshold)) // Clamp to valid range
}
-
+
let particleCount: Int = 9
let particleSpacing: CGFloat = 4
let minParticleSize: CGFloat = 4
@@ -223,33 +222,34 @@ struct EnhancedTalkingAnimationConfig: AudioVisualizationConfig {
struct EnhancedTalkingAudioVisualizationView: View {
@StateObject private var data: AudioVisualizationData
- @State private var dynamicNoiseThreshold: CGFloat = CGFloat(SettingsStore.shared.visualizerNoiseThreshold)
-
+ @State private var dynamicNoiseThreshold: CGFloat = .init(SettingsStore.shared.visualizerNoiseThreshold)
+
// Dynamic config that updates with settings
private var config: EnhancedTalkingAnimationConfig {
EnhancedTalkingAnimationConfig(noiseThreshold: dynamicNoiseThreshold)
}
-
+
init(audioLevelPublisher: AnyPublisher<CGFloat, Never>) {
- self._data = StateObject(wrappedValue: AudioVisualizationData(audioLevelPublisher: audioLevelPublisher))
+ _data = StateObject(wrappedValue: AudioVisualizationData(audioLevelPublisher: audioLevelPublisher))
}
-
+
var body: some View {
HStack(spacing: config.particleSpacing) {
- ForEach(0..<config.particleCount, id: \.self) { index in
+ ForEach(0..<self.config.particleCount, id: \.self) { index in
PremiumTalkingParticle(
- audioLevel: data.audioLevel,
- config: config,
+ audioLevel: self.data.audioLevel,
+ config: self.config,
index: index
)
}
}
- .frame(width: CGFloat(config.particleCount) * (config.maxParticleSize + config.particleSpacing) - config.particleSpacing)
+ .frame(width: CGFloat(config.particleCount) * (config.maxParticleSize + config.particleSpacing) -
+ config.particleSpacing)
.onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in
// Update threshold when UserDefaults changes
let newThreshold = CGFloat(SettingsStore.shared.visualizerNoiseThreshold)
- if newThreshold != dynamicNoiseThreshold {
- dynamicNoiseThreshold = newThreshold
+ if newThreshold != self.dynamicNoiseThreshold {
+ self.dynamicNoiseThreshold = newThreshold
}
}
}
@@ -259,121 +259,113 @@ struct PremiumTalkingParticle: View {
let audioLevel: CGFloat
let config: EnhancedTalkingAnimationConfig
let index: Int
-
+
@State private var animationPhase: Double = 0
@State private var pulseScale: CGFloat = 1.0
@State private var rotationAngle: Double = 0
- @State private var randomOffset: Double = Double.random(in: 0...2 * Double.pi)
+ @State private var randomOffset: Double = .random(in: 0...2 * Double.pi)
@State private var animationTrigger: Int = 0
@State private var lastParticleUpdateTime: TimeInterval = 0
@State private var isParticleVisible: Bool = true
-
+
private let particleTimer = Timer.publish(every: 0.033, on: .main, in: .common).autoconnect() // 30 FPS
-
+
private var isActive: Bool {
audioLevel > config.noiseThreshold
}
-
+
private var particleSize: CGFloat {
if !isActive { return config.minParticleSize }
-
+
let waveValue = sin(animationPhase + Double(index) * 0.8 + randomOffset)
let normalizedWave = (waveValue + 1) / 2
let audioMultiplier = pow(audioLevel, 0.6) * 1.5
let sizeRange = config.maxParticleSize - config.minParticleSize
-
+
return 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))
}
-
+
var body: some View {
ZStack {
// Outer glow ring
Circle()
- .fill(
- RadialGradient(
- gradient: Gradient(colors: [
- Color.clear,
- Color.purple.opacity(0.2),
- Color.indigo.opacity(0.08),
- Color.clear
- ]),
- center: .center,
- startRadius: particleSize * 0.3,
- endRadius: particleSize * 1.8
- )
- )
- .frame(width: particleSize * 2.5, height: particleSize * 2.5)
- .opacity(isActive ? 0.6 : 0.1)
+ .fill(RadialGradient(
+ gradient: Gradient(colors: [
+ Color.clear,
+ Color.purple.opacity(0.2),
+ Color.indigo.opacity(0.08),
+ Color.clear,
+ ]),
+ center: .center,
+ startRadius: self.particleSize * 0.3,
+ endRadius: self.particleSize * 1.8
+ ))
+ .frame(width: self.particleSize * 2.5, height: self.particleSize * 2.5)
+ .opacity(self.isActive ? 0.6 : 0.1)
.blur(radius: 2)
-
+
// Main particle
Circle()
- .fill(
- AngularGradient(
- gradient: Gradient(stops: [
- .init(color: Color.gray.opacity(0.6), location: 0.0),
- .init(color: Color.purple.opacity(0.7), location: 0.25),
- .init(color: Color.indigo.opacity(0.8), location: 0.5),
- .init(color: Color.black.opacity(0.9), location: 0.75),
- .init(color: Color.gray.opacity(0.6), location: 1.0)
+ .fill(AngularGradient(
+ gradient: Gradient(stops: [
+ .init(color: Color.gray.opacity(0.6), location: 0.0),
+ .init(color: Color.purple.opacity(0.7), location: 0.25),
+ .init(color: Color.indigo.opacity(0.8), location: 0.5),
+ .init(color: Color.black.opacity(0.9), location: 0.75),
+ .init(color: Color.gray.opacity(0.6), location: 1.0),
+ ]),
+ center: .center,
+ startAngle: .degrees(self.rotationAngle),
+ endAngle: .degrees(self.rotationAngle + 360)
+ ))
+ .frame(width: self.particleSize, height: self.particleSize)
+ .opacity(self.particleOpacity)
+ .scaleEffect(self.pulseScale)
+ .overlay(Circle()
+ .fill(RadialGradient(
+ gradient: Gradient(colors: [
+ Color.white.opacity(0.3),
+ Color.white.opacity(0.1),
+ Color.clear,
]),
- center: .center,
- startAngle: .degrees(rotationAngle),
- endAngle: .degrees(rotationAngle + 360)
- )
- )
- .frame(width: particleSize, height: particleSize)
- .opacity(particleOpacity)
- .scaleEffect(pulseScale)
- .overlay(
- Circle()
- .fill(
- RadialGradient(
- gradient: Gradient(colors: [
- Color.white.opacity(0.3),
- Color.white.opacity(0.1),
- Color.clear
- ]),
- center: UnitPoint(x: 0.3, y: 0.3),
- startRadius: 0,
- endRadius: particleSize * 0.6
- )
- )
- .frame(width: particleSize, height: particleSize)
- )
+ center: UnitPoint(x: 0.3, y: 0.3),
+ startRadius: 0,
+ endRadius: self.particleSize * 0.6
+ ))
+ .frame(width: self.particleSize, height: self.particleSize))
.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
- if isParticleVisible {
- updateParticleAnimation()
+ if self.isParticleVisible {
+ self.updateParticleAnimation()
}
}
.onAppear {
- isParticleVisible = true
+ self.isParticleVisible = true
}
.onDisappear {
- isParticleVisible = false
+ self.isParticleVisible = false
}
}
-
+
private func updateParticleAnimation() {
let currentTime = Date().timeIntervalSince1970
-
+
// Simple frame limiting for consistent 30 FPS
if currentTime - lastParticleUpdateTime < 0.033 { return }
lastParticleUpdateTime = currentTime
-
+
animationTrigger += 1
-
+
// Real-time responsive animation
if audioLevel <= config.noiseThreshold { // USE THE USER-CONTROLLABLE THRESHOLD!
// Complete stillness during silence
@@ -384,20 +376,21 @@ struct PremiumTalkingParticle: View {
} else {
// Fast, responsive animation
animationPhase += 0.3 // Much faster phase changes
- rotationAngle += 1.5 // Faster rotation
+ rotationAngle += 1.5 // Faster rotation
pulseScale = 1.0 + (audioLevel * 0.15) // More pronounced pulsing
}
}
}
// MARK: - Individual Spokenly Bar
+
struct SpokenlyBar: View {
let height: CGFloat
let opacity: Double
let index: Int
let config: TalkingAnimationConfig
let isActive: Bool
-
+
var body: some View {
RoundedRectangle(cornerRadius: config.barWidth / 2)
.fill(Color.white)
diff --git a/Sources/Fluid/Theme/AppTheme.swift b/Sources/Fluid/Theme/AppTheme.swift
index d333a12d..60761c53 100644
--- a/Sources/Fluid/Theme/AppTheme.swift
+++ b/Sources/Fluid/Theme/AppTheme.swift
@@ -118,4 +118,3 @@ struct AppTheme {
}
// MARK: - Helpers
-
diff --git a/Sources/Fluid/Theme/Components/SetupComponents.swift b/Sources/Fluid/Theme/Components/SetupComponents.swift
index 3f13f399..6f90df55 100644
--- a/Sources/Fluid/Theme/Components/SetupComponents.swift
+++ b/Sources/Fluid/Theme/Components/SetupComponents.swift
@@ -1,12 +1,5 @@
-//
-// SetupComponents.swift
-// fluid
-//
-// Helper components for setup and onboarding UI
-//
-
-import SwiftUI
import AppKit
+import SwiftUI
// MARK: - Setup Step View
@@ -26,42 +19,40 @@ struct SetupStepView: View {
var body: some View {
Button(action: {
- if status != .completed && showActionButton {
- action()
+ if self.status != .completed, self.showActionButton {
+ self.action()
}
}) {
HStack(alignment: .center, spacing: 10) {
// Status indicator
ZStack {
Circle()
- .fill(statusColor.opacity(0.12))
+ .fill(self.statusColor.opacity(0.12))
.frame(width: 28, height: 28)
- .overlay(
- Circle()
- .stroke(statusColor.opacity(0.25), lineWidth: 1)
- )
+ .overlay(Circle()
+ .stroke(self.statusColor.opacity(0.25), lineWidth: 1))
- if status == .completed {
+ if self.status == .completed {
Image(systemName: "checkmark.circle.fill")
- .foregroundStyle(statusColor)
+ .foregroundStyle(self.statusColor)
.font(.body.weight(.semibold))
- } else if status == .inProgress {
+ } else if self.status == .inProgress {
ProgressView()
.controlSize(.small)
- .tint(statusColor)
+ .tint(self.statusColor)
} else {
- Text("\(step)")
+ Text("\(self.step)")
.font(.caption.weight(.bold))
- .foregroundStyle(statusColor)
+ .foregroundStyle(self.statusColor)
}
}
VStack(alignment: .leading, spacing: 2) {
- Text(title)
+ Text(self.title)
.font(.body.weight(.medium))
.foregroundStyle(.primary)
- Text(description)
+ Text(self.description)
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(2)
@@ -70,42 +61,38 @@ struct SetupStepView: View {
Spacer()
// Action button or status badge
- if status == .completed {
+ if self.status == .completed {
Label("Done", systemImage: "checkmark")
.font(.caption.weight(.semibold))
.foregroundStyle(.white)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(Color.green, in: Capsule())
- } else if showActionButton {
+ } else if self.showActionButton {
HStack(spacing: 3) {
- Text(actionButtonTitle)
+ Text(self.actionButtonTitle)
.font(.caption.weight(.medium))
Image(systemName: "arrow.right")
.font(.caption2.weight(.bold))
}
- .foregroundStyle(theme.palette.accent)
+ .foregroundStyle(self.theme.palette.accent)
.padding(.horizontal, 8)
.padding(.vertical, 4)
- .background(theme.palette.accent.opacity(0.12), in: Capsule())
+ .background(self.theme.palette.accent.opacity(0.12), in: Capsule())
}
}
.padding(10)
- .background(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(status == .completed
- ? Color.green.opacity(0.06)
- : theme.palette.cardBackground.opacity(0.5))
- .overlay(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .stroke(
- status == .completed
- ? Color.green.opacity(0.25)
- : theme.palette.cardBorder.opacity(0.2),
- lineWidth: 1
- )
- )
- )
+ .background(RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(self.status == .completed
+ ? Color.green.opacity(0.06)
+ : self.theme.palette.cardBackground.opacity(0.5))
+ .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .stroke(
+ self.status == .completed
+ ? Color.green.opacity(0.25)
+ : self.theme.palette.cardBorder.opacity(0.2),
+ lineWidth: 1
+ )))
}
.buttonStyle(.plain)
.disabled(status == .completed || !showActionButton)
@@ -133,19 +120,19 @@ struct InstructionStep: View {
HStack(alignment: .top, spacing: 8) {
ZStack {
Circle()
- .fill(theme.palette.accent.opacity(0.15))
+ .fill(self.theme.palette.accent.opacity(0.15))
.frame(width: 22, height: 22)
- Text("\(number)")
+ Text("\(self.number)")
.font(.caption.weight(.semibold))
- .foregroundStyle(theme.palette.accent)
+ .foregroundStyle(self.theme.palette.accent)
}
VStack(alignment: .leading, spacing: 1) {
- Text(title)
+ Text(self.title)
.font(.subheadline.weight(.medium))
- Text(description)
+ Text(self.description)
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(2)
@@ -163,7 +150,7 @@ struct ProviderGuide: View {
let description: String?
let baseURL: String
let keyPrefix: String
-
+
init(name: String, url: String, description: String? = nil, baseURL: String, keyPrefix: String) {
self.name = name
self.url = url
@@ -176,12 +163,12 @@ struct ProviderGuide: View {
ThemedCard(hoverEffect: false) {
VStack(alignment: .leading, spacing: 8) {
HStack {
- Text(name)
+ Text(self.name)
.font(.subheadline.weight(.semibold))
Spacer()
- if !url.isEmpty {
+ if !self.url.isEmpty {
Button("Get API Key") {
if let url = URL(string: url) {
NSWorkspace.shared.open(url)
@@ -203,7 +190,7 @@ struct ProviderGuide: View {
Text("Base URL:")
.font(.caption)
.foregroundStyle(.secondary)
- Text(baseURL)
+ Text(self.baseURL)
.font(.caption.weight(.medium))
.textSelection(.enabled)
}
@@ -212,7 +199,7 @@ struct ProviderGuide: View {
Text("Key Format:")
.font(.caption)
.foregroundStyle(.secondary)
- Text(keyPrefix == "not-needed" ? "Not required" : "Starts with: \(keyPrefix)")
+ Text(self.keyPrefix == "not-needed" ? "Not required" : "Starts with: \(self.keyPrefix)")
.font(.caption.weight(.medium))
}
}
@@ -221,8 +208,3 @@ struct ProviderGuide: View {
}
}
}
-
-
-
-
-
diff --git a/Sources/Fluid/Theme/Components/ThemedCard.swift b/Sources/Fluid/Theme/Components/ThemedCard.swift
index f2926d5b..0cb5b298 100644
--- a/Sources/Fluid/Theme/Components/ThemedCard.swift
+++ b/Sources/Fluid/Theme/Components/ThemedCard.swift
@@ -34,36 +34,35 @@ struct ThemedCard<Content: View>: View {
content
.padding(padding ?? 14)
.background(configuration.material, in: shape)
- .background(
- shape
- .fill(configuration.background)
- .overlay(
- shape.stroke(
- configuration.border.opacity(
- isHovered && hoverEffect ? configuration.hoverBorderOpacity : configuration.borderOpacity
- ),
- lineWidth: configuration.borderWidth
- )
- )
- .shadow(
- color: configuration.shadow.color.opacity(
- isHovered && 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
- )
- )
+ .background(shape
+ .fill(configuration.background)
+ .overlay(shape
+ .stroke(
+ configuration.border
+ .opacity(isHovered && hoverEffect ? configuration.hoverBorderOpacity : configuration
+ .borderOpacity),
+ lineWidth: configuration.borderWidth
+ ))
+ .shadow(
+ color: configuration.shadow.color.opacity(isHovered && 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
+ ))
.scaleEffect(isHovered && hoverEffect ? 1.01 : 1.0)
.onHover { hovering in
- guard hoverEffect else { return }
- isHovered = hovering
+ guard self.hoverEffect else { return }
+ self.isHovered = hovering
}
.animation(.easeOut(duration: 0.18), value: isHovered)
}
}
// MARK: - Configuration
+
private extension ThemedCard {
struct CardConfiguration {
let background: Color
@@ -112,4 +111,3 @@ private extension ThemedCard {
}
}
}
-
diff --git a/Sources/Fluid/Theme/Components/ThemedGroupBox.swift b/Sources/Fluid/Theme/Components/ThemedGroupBox.swift
index d047666d..ae4fd6da 100644
--- a/Sources/Fluid/Theme/Components/ThemedGroupBox.swift
+++ b/Sources/Fluid/Theme/Components/ThemedGroupBox.swift
@@ -22,33 +22,23 @@ struct ThemedGroupBox<Label: View, Content: View>: View {
var body: some View {
ThemedCard(style: style, padding: 0, hoverEffect: hoverEffect) {
- VStack(alignment: .leading, spacing: theme.metrics.spacing.md) {
- label
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
+ self.label
.font(.headline)
- .foregroundStyle(theme.palette.secondaryText)
- .padding(.top, theme.metrics.spacing.md)
- .padding(.horizontal, theme.metrics.spacing.md)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .padding(.top, self.theme.metrics.spacing.md)
+ .padding(.horizontal, self.theme.metrics.spacing.md)
Divider()
- .background(theme.palette.separator)
+ .background(self.theme.palette.separator)
.opacity(0.6)
- .padding(.horizontal, theme.metrics.spacing.md)
+ .padding(.horizontal, self.theme.metrics.spacing.md)
- content
- .padding(.bottom, theme.metrics.spacing.md)
- .padding(.horizontal, theme.metrics.spacing.md)
+ self.content
+ .padding(.bottom, self.theme.metrics.spacing.md)
+ .padding(.horizontal, self.theme.metrics.spacing.md)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
-
-
-
-
-
-
-
-
-
-
diff --git a/Sources/Fluid/Theme/NativeButtonStyles.swift b/Sources/Fluid/Theme/NativeButtonStyles.swift
index ee5d35a7..0bf48c31 100644
--- a/Sources/Fluid/Theme/NativeButtonStyles.swift
+++ b/Sources/Fluid/Theme/NativeButtonStyles.swift
@@ -1,6 +1,7 @@
import SwiftUI
// MARK: - Primary (Prominent) Button
+
struct GlassButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
GlassButton(configuration: configuration)
@@ -23,36 +24,35 @@ struct GlassButtonStyle: ButtonStyle {
.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),
- lineWidth: 1
- )
- )
- )
- .overlay(
- shape
- .stroke(theme.palette.accent.opacity(isHovered ? 0.25 : 0.1), lineWidth: 1)
- .blendMode(.plusLighter)
- )
+ .background(shape
+ .fill(theme.palette.cardBackground)
+ .overlay(shape.stroke(
+ theme.palette.cardBorder.opacity(isHovered ? 0.45 : 0.25),
+ lineWidth: 1
+ )))
+ .overlay(shape
+ .stroke(theme.palette.accent.opacity(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.radius : max(theme.metrics.cardShadow.radius - 3, 2),
+ radius: isHovered ? theme.metrics.cardShadow
+ .radius : max(
+ theme.metrics.cardShadow.radius - 3,
+ 2
+ ),
x: 0,
y: isHovered ? theme.metrics.cardShadow.y : 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)
- .onHover { isHovered = $0 }
+ .onHover { self.isHovered = $0 }
}
}
}
// MARK: - Primary Accent Button
+
struct PremiumButtonStyle: ButtonStyle {
var isRecording: Bool = false
var height: CGFloat = 44
@@ -77,7 +77,7 @@ struct PremiumButtonStyle: ButtonStyle {
return LinearGradient(
colors: [
Color(nsColor: .systemRed),
- Color(nsColor: .systemRed).opacity(0.8)
+ Color(nsColor: .systemRed).opacity(0.8),
],
startPoint: .topLeading,
endPoint: .bottomTrailing
@@ -87,7 +87,7 @@ struct PremiumButtonStyle: ButtonStyle {
return LinearGradient(
colors: [
theme.palette.accent.opacity(0.95),
- theme.palette.accent.opacity(0.75)
+ theme.palette.accent.opacity(0.75),
],
startPoint: .topLeading,
endPoint: .bottomTrailing
@@ -100,32 +100,33 @@ struct PremiumButtonStyle: ButtonStyle {
.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),
- lineWidth: 1
- )
- )
- )
+ .background(shape
+ .fill(baseGradient)
+ .overlay(shape.stroke(
+ Color.white.opacity(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.radius : max(theme.metrics.cardShadow.radius - 2, 2),
+ radius: isHovered ? theme.metrics.elevatedCardShadow
+ .radius : max(
+ theme.metrics.cardShadow.radius - 2,
+ 2
+ ),
x: 0,
y: isHovered ? theme.metrics.elevatedCardShadow.y : 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)
- .onHover { isHovered = $0 }
+ .onHover { self.isHovered = $0 }
}
}
}
// MARK: - Secondary Button
+
struct SecondaryButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
SecondaryButton(configuration: configuration)
@@ -147,31 +148,32 @@ struct SecondaryButtonStyle: ButtonStyle {
.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),
- lineWidth: 1
- )
- )
- )
+ .background(shape
+ .fill(theme.palette.cardBackground)
+ .overlay(shape.stroke(
+ theme.palette.cardBorder.opacity(isHovered ? 0.45 : 0.25),
+ lineWidth: 1
+ )))
.shadow(
color: theme.palette.cardBorder.opacity(isHovered ? 0.35 : 0.15),
- radius: isHovered ? theme.metrics.cardShadow.radius : max(theme.metrics.cardShadow.radius - 4, 1),
+ radius: isHovered ? theme.metrics.cardShadow
+ .radius : max(
+ theme.metrics.cardShadow.radius - 4,
+ 1
+ ),
x: 0,
y: isHovered ? theme.metrics.cardShadow.y : 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)
- .onHover { isHovered = $0 }
+ .onHover { self.isHovered = $0 }
}
}
}
// MARK: - Compact Button
+
struct CompactButtonStyle: ButtonStyle {
var isReady: Bool = false
@@ -196,17 +198,14 @@ struct CompactButtonStyle: ButtonStyle {
.frame(height: 34)
.foregroundStyle(theme.palette.primaryText)
.background(theme.materials.card, in: shape)
- .background(
- shape
- .fill(theme.palette.cardBackground)
- .overlay(
- shape.stroke(
- (isReady ? theme.palette.accent : theme.palette.cardBorder)
- .opacity(isHovered ? 0.45 : 0.25),
- lineWidth: 1
- )
- )
- )
+ .background(shape
+ .fill(theme.palette.cardBackground)
+ .overlay(shape
+ .stroke(
+ (isReady ? theme.palette.accent : theme.palette.cardBorder)
+ .opacity(isHovered ? 0.45 : 0.25),
+ lineWidth: 1
+ )))
.shadow(
color: (isReady ? theme.palette.accent : theme.palette.cardBorder)
.opacity(isHovered ? 0.3 : 0.12),
@@ -217,12 +216,13 @@ struct CompactButtonStyle: ButtonStyle {
.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)
- .onHover { isHovered = $0 }
+ .onHover { self.isHovered = $0 }
}
}
}
// MARK: - Inline Button
+
struct InlineButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
InlineButton(configuration: configuration)
@@ -244,10 +244,8 @@ struct InlineButtonStyle: ButtonStyle {
.padding(.horizontal, theme.metrics.spacing.md)
.padding(.vertical, theme.metrics.spacing.xs)
.foregroundStyle(Color.white)
- .background(
- shape
- .fill(theme.palette.accent.opacity(isHovered ? 0.9 : 0.8))
- )
+ .background(shape
+ .fill(theme.palette.accent.opacity(isHovered ? 0.9 : 0.8)))
.shadow(
color: theme.palette.accent.opacity(isHovered ? 0.45 : 0.25),
radius: isHovered ? 6 : 3,
@@ -257,12 +255,13 @@ struct InlineButtonStyle: ButtonStyle {
.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)
- .onHover { isHovered = $0 }
+ .onHover { self.isHovered = $0 }
}
}
}
// MARK: - Glass Toggle Style (now uses native switch for consistency)
+
struct GlassToggleStyle: ToggleStyle {
func makeBody(configuration: Configuration) -> some View {
ToggleBody(configuration: configuration)
@@ -274,14 +273,14 @@ struct GlassToggleStyle: ToggleStyle {
var body: some View {
HStack {
- configuration.label
- .foregroundStyle(theme.palette.primaryText)
+ self.configuration.label
+ .foregroundStyle(self.theme.palette.primaryText)
Spacer()
- Toggle("", isOn: configuration.$isOn)
+ Toggle("", isOn: self.configuration.$isOn)
.toggleStyle(.switch)
- .tint(theme.palette.accent)
+ .tint(self.theme.palette.accent)
.labelsHidden()
}
}
@@ -289,19 +288,16 @@ struct GlassToggleStyle: ToggleStyle {
}
// MARK: - Native Form Row Style
+
struct FormRowStyle: ViewModifier {
func body(content: Content) -> some View {
content
.padding(.horizontal, 12)
.padding(.vertical, 10)
- .background(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(.ultraThinMaterial.opacity(0.5))
- .overlay(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .stroke(.white.opacity(0.08), lineWidth: 1)
- )
- )
+ .background(RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(.ultraThinMaterial.opacity(0.5))
+ .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .stroke(.white.opacity(0.08), lineWidth: 1)))
}
}
@@ -310,13 +306,3 @@ extension View {
modifier(FormRowStyle())
}
}
-
-
-
-
-
-
-
-
-
-
diff --git a/Sources/Fluid/Theme/ThemeEnvironment.swift b/Sources/Fluid/Theme/ThemeEnvironment.swift
index a859618a..9c63fafe 100644
--- a/Sources/Fluid/Theme/ThemeEnvironment.swift
+++ b/Sources/Fluid/Theme/ThemeEnvironment.swift
@@ -17,13 +17,3 @@ extension View {
environment(\.theme, theme)
}
}
-
-
-
-
-
-
-
-
-
-
diff --git a/Sources/Fluid/UI/AISettingsView.swift b/Sources/Fluid/UI/AISettingsView.swift
index bd028663..a8f51acf 100644
--- a/Sources/Fluid/UI/AISettingsView.swift
+++ b/Sources/Fluid/UI/AISettingsView.swift
@@ -6,11 +6,12 @@
// Created: 2025-12-14
//
-import SwiftUI
import AppKit
import Security
+import SwiftUI
// MARK: - Connection Status Enum
+
enum AIConnectionStatus {
case unknown, testing, success, failed
}
@@ -19,14 +20,15 @@ struct AISettingsView: View {
@EnvironmentObject private var appServices: AppServices
@EnvironmentObject private var menuBarManager: MenuBarManager
@Environment(\.theme) private var theme
-
+
private var asr: ASRService { appServices.asr }
-
+
// MARK: - State Variables (moved from ContentView)
+
@State private var appear = false
@State private var openAIBaseURL: String = "https://api.openai.com/v1"
@State private var enableAIProcessing: Bool = false
-
+
// Model Management
@State private var availableModelsByProvider: [String: [String]] = [:]
@State private var selectedModelByProvider: [String: String] = [:]
@@ -34,31 +36,31 @@ struct AISettingsView: View {
@State private var selectedModel: String = "gpt-4.1"
@State private var showingAddModel: Bool = false
@State private var newModelName: String = ""
-
+
// Reasoning Configuration
@State private var showingReasoningConfig: Bool = false
@State private var editingReasoningParamName: String = "reasoning_effort"
@State private var editingReasoningParamValue: String = "low"
@State private var editingReasoningEnabled: Bool = false
-
+
// Provider Management
@State private var providerAPIKeys: [String: String] = [:]
@State private var currentProvider: String = "openai"
@State private var savedProviders: [SettingsStore.SavedProvider] = []
@State private var selectedProviderID: String = SettingsStore.shared.selectedProviderID
-
+
// Connection Testing
@State private var isTestingConnection: Bool = false
@State private var connectionStatus: AIConnectionStatus = .unknown
@State private var connectionErrorMessage: String = ""
-
+
// UI State
@State private var showHelp: Bool = false
@State private var showingSaveProvider: Bool = false
@State private var showAPIKeyEditor: Bool = false
@State private var showAPIKeysGuide: Bool = false
@State private var showingEditProvider: Bool = false
-
+
// Provider Form State
@State private var newProviderName: String = ""
@State private var newProviderBaseURL: String = ""
@@ -66,39 +68,39 @@ struct AISettingsView: View {
@State private var newProviderModels: String = ""
@State private var editProviderName: String = ""
@State private var editProviderBaseURL: String = ""
-
+
// Keychain State
@State private var showKeychainPermissionAlert: Bool = false
@State private var keychainPermissionMessage: String = ""
-
+
// Filler Words State - local state to ensure UI reactivity
@State private var removeFillerWordsEnabled: Bool = SettingsStore.shared.removeFillerWordsEnabled
-
+
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
VStack(alignment: .leading, spacing: 14) {
- speechRecognitionCard
- aiConfigurationCard
+ self.speechRecognitionCard
+ self.aiConfigurationCard
}
.padding(14)
}
.onAppear {
- appear = true
- loadSettings()
-
+ self.appear = true
+ self.loadSettings()
+
// CRITICAL FIX: Refresh model status immediately on appear
// This ensures the speech recognition card shows current download status
- asr.checkIfModelsExist()
+ self.asr.checkIfModelsExist()
}
.onChange(of: enableAIProcessing) { _, newValue in
SettingsStore.shared.enableAIProcessing = newValue
// Keep menu bar UI in sync when toggled from this screen
- menuBarManager.aiProcessingEnabled = newValue
+ self.menuBarManager.aiProcessingEnabled = newValue
}
.onChange(of: selectedModel) { _, newValue in
if newValue != "__ADD_MODEL__" {
- selectedModelByProvider[currentProvider] = newValue
- SettingsStore.shared.selectedModelByProvider = selectedModelByProvider
+ self.selectedModelByProvider[self.currentProvider] = newValue
+ SettingsStore.shared.selectedModelByProvider = self.selectedModelByProvider
}
}
.onChange(of: selectedProviderID) { _, newValue in
@@ -106,22 +108,23 @@ struct AISettingsView: View {
}
.onChange(of: showKeychainPermissionAlert) { _, isPresented in
guard isPresented else { return }
- presentKeychainAccessAlert(message: keychainPermissionMessage)
- showKeychainPermissionAlert = false
+ self.presentKeychainAccessAlert(message: self.keychainPermissionMessage)
+ self.showKeychainPermissionAlert = false
}
}
-
+
// MARK: - Load Settings
+
private func loadSettings() {
selectedProviderID = SettingsStore.shared.selectedProviderID
updateCurrentProvider()
-
+
enableAIProcessing = SettingsStore.shared.enableAIProcessing
availableModelsByProvider = SettingsStore.shared.availableModelsByProvider
selectedModelByProvider = SettingsStore.shared.selectedModelByProvider
providerAPIKeys = SettingsStore.shared.providerAPIKeys
savedProviders = SettingsStore.shared.savedProviders
-
+
// Normalize provider keys
var normalized: [String: [String]] = [:]
for (key, models) in availableModelsByProvider {
@@ -134,17 +137,18 @@ struct AISettingsView: View {
}
availableModelsByProvider = normalized
SettingsStore.shared.availableModelsByProvider = normalized
-
+
// Normalize selected model by provider
var normalizedSel: [String: String] = [:]
for (key, model) in selectedModelByProvider {
let lower = key.lowercased()
- let newKey: String = (lower == "openai" || lower == "groq") ? lower : (key.hasPrefix("custom:") ? key : "custom:\(key)")
+ 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
SettingsStore.shared.selectedModelByProvider = normalizedSel
-
+
// Determine initial model list
if let saved = savedProviders.first(where: { $0.id == selectedProviderID }) {
availableModels = saved.models
@@ -154,7 +158,7 @@ struct AISettingsView: View {
} else {
availableModels = defaultModels(for: providerKey(for: selectedProviderID))
}
-
+
// Restore selected model
if let sel = selectedModelByProvider[currentProvider], availableModels.contains(sel) {
selectedModel = sel
@@ -162,8 +166,9 @@ struct AISettingsView: View {
selectedModel = first
}
}
-
+
// MARK: - Speech Recognition Card
+
private var speechRecognitionCard: some View {
ThemedCard(hoverEffect: false) {
VStack(alignment: .leading, spacing: 10) {
@@ -175,7 +180,7 @@ struct AISettingsView: View {
.font(.title3)
.fontWeight(.semibold)
}
-
+
VStack(alignment: .leading, spacing: 10) {
// Single unified model picker
HStack(spacing: 12) {
@@ -186,7 +191,7 @@ struct AISettingsView: View {
ForEach(SettingsStore.SpeechModel.availableModels) { model in
Button {
SettingsStore.shared.selectedSpeechModel = model
- asr.resetTranscriptionProvider()
+ self.asr.resetTranscriptionProvider()
} label: {
HStack {
Text(model.displayName)
@@ -197,9 +202,9 @@ struct AISettingsView: View {
}
}
}
- .disabled(asr.isRunning)
+ .disabled(self.asr.isRunning)
}
-
+
// Model info badges
HStack(spacing: 8) {
Label(SettingsStore.shared.selectedSpeechModel.languageSupport, systemImage: "globe")
@@ -207,65 +212,67 @@ struct AISettingsView: View {
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(RoundedRectangle(cornerRadius: 5).fill(.quaternary))
-
+
Label(SettingsStore.shared.selectedSpeechModel.downloadSize, systemImage: "arrow.down.circle")
.font(.caption)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(RoundedRectangle(cornerRadius: 5).fill(.quaternary))
-
+
Spacer()
-
+
if !SettingsStore.shared.selectedSpeechModel.isWhisperModel {
Text("Apple Silicon")
.font(.caption)
.padding(.horizontal, 8)
.padding(.vertical, 4)
- .background(RoundedRectangle(cornerRadius: 5, style: .continuous).fill(theme.palette.accent.opacity(0.2)))
+ .background(RoundedRectangle(cornerRadius: 5, style: .continuous)
+ .fill(self.theme.palette.accent.opacity(0.2)))
}
}
-
+
// Model status indicator
- modelStatusView
-
+ self.modelStatusView
+
// Performance note
HStack(alignment: .top, spacing: 8) {
Image(systemName: "info.circle.fill")
- .foregroundStyle(theme.palette.accent)
+ .foregroundStyle(self.theme.palette.accent)
.font(.caption)
Text(SettingsStore.shared.selectedSpeechModel.isWhisperModel
- ? "Whisper models support 99 languages and work on any Mac."
- : "Parakeet TDT uses CoreML and Neural Engine for fastest transcription (25 languages) on Apple Silicon.")
+ ? "Whisper models support 99 languages and work on any Mac."
+ :
+ "Parakeet TDT uses CoreML and Neural Engine for fastest transcription (25 languages) on Apple Silicon.")
.font(.caption)
.foregroundStyle(.secondary)
}
.padding(10)
.background(RoundedRectangle(cornerRadius: 8).fill(.ultraThinMaterial.opacity(0.3)))
-
+
Divider().padding(.vertical, 4)
-
+
// Filler Words Section
- fillerWordsSection
+ self.fillerWordsSection
}
}
.padding(14)
}
}
-
+
private var modelStatusView: some View {
HStack(spacing: 12) {
- if asr.isDownloadingModel || asr.isLoadingModel {
+ if self.asr.isDownloadingModel || self.asr.isLoadingModel {
HStack(spacing: 8) {
ProgressView().controlSize(.small)
- Text(asr.isLoadingModel ? "Loading model…" : "Downloading…")
+ Text(self.asr.isLoadingModel ? "Loading model…" : "Downloading…")
.font(.caption)
.foregroundStyle(.secondary)
}
- } else if asr.isAsrReady {
+ } else if self.asr.isAsrReady {
Image(systemName: "checkmark.circle.fill").foregroundStyle(.green).font(.caption)
Text("Ready").font(.caption).foregroundStyle(.secondary)
-
- Button(action: { Task { await deleteModels() } }) {
+
+ Button(action: { Task { await self.deleteModels() } }) {
HStack(spacing: 4) {
Image(systemName: "trash")
Text("Delete")
@@ -274,11 +281,11 @@ struct AISettingsView: View {
.foregroundStyle(.red)
}
.buttonStyle(.plain)
- } else if asr.modelsExistOnDisk {
- Image(systemName: "doc.fill").foregroundStyle(theme.palette.accent).font(.caption)
+ } else if self.asr.modelsExistOnDisk {
+ Image(systemName: "doc.fill").foregroundStyle(self.theme.palette.accent).font(.caption)
Text("Cached").font(.caption).foregroundStyle(.secondary)
-
- Button(action: { Task { await deleteModels() } }) {
+
+ Button(action: { Task { await self.deleteModels() } }) {
HStack(spacing: 4) {
Image(systemName: "trash")
Text("Delete")
@@ -289,27 +296,25 @@ struct AISettingsView: View {
.buttonStyle(.plain)
} else {
Image(systemName: "arrow.down.circle").foregroundStyle(.orange).font(.caption)
-
- Button(action: { Task { await downloadModels() } }) {
+
+ Button(action: { Task { await self.downloadModels() } }) {
HStack(spacing: 4) {
Image(systemName: "arrow.down.circle.fill")
Text("Download")
}
.font(.caption)
- .foregroundStyle(theme.palette.accent)
+ .foregroundStyle(self.theme.palette.accent)
}
.buttonStyle(.plain)
}
}
.padding(.horizontal, 12)
.padding(.vertical, 8)
- .background(
- RoundedRectangle(cornerRadius: 8)
- .fill(.ultraThinMaterial.opacity(0.3))
- .overlay(RoundedRectangle(cornerRadius: 8).stroke(.white.opacity(0.1), lineWidth: 1))
- )
+ .background(RoundedRectangle(cornerRadius: 8)
+ .fill(.ultraThinMaterial.opacity(0.3))
+ .overlay(RoundedRectangle(cornerRadius: 8).stroke(.white.opacity(0.1), lineWidth: 1)))
}
-
+
private var fillerWordsSection: some View {
VStack(alignment: .leading, spacing: 8) {
HStack(alignment: .center) {
@@ -320,21 +325,22 @@ struct AISettingsView: View {
.foregroundStyle(.secondary)
}
Spacer()
- Toggle("", isOn: $removeFillerWordsEnabled)
+ Toggle("", isOn: self.$removeFillerWordsEnabled)
.toggleStyle(.switch)
.labelsHidden()
- .onChange(of: removeFillerWordsEnabled) { _, newValue in
+ .onChange(of: self.removeFillerWordsEnabled) { _, newValue in
SettingsStore.shared.removeFillerWordsEnabled = newValue
}
}
-
- if removeFillerWordsEnabled {
+
+ if self.removeFillerWordsEnabled {
FillerWordsEditor()
}
}
}
-
+
// MARK: - Model Download/Delete
+
private func downloadModels() async {
do {
try await asr.ensureAsrReady()
@@ -342,7 +348,7 @@ struct AISettingsView: View {
DebugLogger.shared.error("Failed to download models: \(error)", source: "AISettingsView")
}
}
-
+
private func deleteModels() async {
do {
try await asr.clearModelCache()
@@ -350,13 +356,14 @@ struct AISettingsView: View {
DebugLogger.shared.error("Failed to delete models: \(error)", source: "AISettingsView")
}
}
-
+
// MARK: - Helper Functions
+
private func providerKey(for providerID: String) -> String {
if providerID == "openai" || providerID == "groq" { return providerID }
return providerID.isEmpty ? currentProvider : "custom:\(providerID)"
}
-
+
private func providerDisplayName(for providerID: String) -> String {
switch providerID {
case "openai": return "OpenAI"
@@ -366,7 +373,7 @@ struct AISettingsView: View {
return savedProviders.first(where: { $0.id == providerID })?.name ?? providerID.capitalized
}
}
-
+
private func defaultModels(for providerKey: String) -> [String] {
switch providerKey {
case "openai": return ["gpt-4.1"]
@@ -374,22 +381,22 @@ struct AISettingsView: View {
default: return []
}
}
-
+
private func saveProviderAPIKeys() {
SettingsStore.shared.providerAPIKeys = 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)
}
-
+
private func saveSavedProviders() {
SettingsStore.shared.savedProviders = savedProviders
}
-
+
private func isLocalEndpoint(_ urlString: String) -> Bool {
guard let url = URL(string: urlString), let host = url.host else { return false }
let hostLower = host.lowercased()
@@ -403,7 +410,7 @@ struct AISettingsView: View {
}
return false
}
-
+
private func hasReasoningConfigForCurrentModel() -> Bool {
let pKey = providerKey(for: selectedProviderID)
if SettingsStore.shared.hasCustomReasoningConfig(forModel: selectedModel, provider: pKey) {
@@ -413,22 +420,22 @@ struct AISettingsView: View {
}
let modelLower = selectedModel.lowercased()
return modelLower.hasPrefix("gpt-5") || modelLower.contains("gpt-5.") ||
- modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3") ||
- modelLower.contains("gpt-oss") || modelLower.hasPrefix("openai/") ||
- (modelLower.contains("deepseek") && modelLower.contains("reasoner"))
+ modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3") ||
+ modelLower.contains("gpt-oss") || modelLower.hasPrefix("openai/") ||
+ (modelLower.contains("deepseek") && modelLower.contains("reasoner"))
}
-
+
private func addNewModel() {
guard !newModelName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
let modelName = newModelName.trimmingCharacters(in: .whitespacesAndNewlines)
let key = providerKey(for: selectedProviderID)
-
+
var list = availableModelsByProvider[key] ?? availableModels
if !list.contains(modelName) {
list.append(modelName)
availableModelsByProvider[key] = list
SettingsStore.shared.availableModelsByProvider = availableModelsByProvider
-
+
if let providerIndex = savedProviders.firstIndex(where: { $0.id == selectedProviderID }) {
let updatedProvider = SettingsStore.SavedProvider(
id: savedProviders[providerIndex].id,
@@ -439,48 +446,49 @@ struct AISettingsView: View {
savedProviders[providerIndex] = updatedProvider
saveSavedProviders()
}
-
+
availableModels = list
selectedModel = modelName
selectedModelByProvider[key] = modelName
SettingsStore.shared.selectedModelByProvider = selectedModelByProvider
}
-
+
showingAddModel = false
newModelName = ""
}
-
+
// MARK: - Keychain Access Helpers
+
private enum KeychainAccessCheckResult {
case granted
case denied(OSStatus)
}
-
+
private func handleAPIKeyButtonTapped() {
switch probeKeychainAccess() {
case .granted:
newProviderApiKey = providerAPIKeys[currentProvider] ?? ""
showAPIKeyEditor = true
- case .denied(let status):
+ case let .denied(status):
keychainPermissionMessage = keychainPermissionExplanation(for: status)
showKeychainPermissionAlert = true
}
}
-
+
private func probeKeychainAccess() -> KeychainAccessCheckResult {
let service = "com.fluidvoice.provider-api-keys"
let account = "fluidApiKeys"
-
+
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
- kSecAttrAccount as String: account
+ kSecAttrAccount as String: account,
]
-
+
var readQuery = query
readQuery[kSecReturnData as String] = kCFBooleanTrue
readQuery[kSecMatchLimit as String] = kSecMatchLimitOne
-
+
let readStatus = SecItemCopyMatching(readQuery as CFDictionary, nil)
switch readStatus {
case errSecSuccess:
@@ -489,12 +497,12 @@ struct AISettingsView: View {
var addQuery = query
addQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
addQuery[kSecValueData as String] = (try? JSONEncoder().encode([String: String]())) ?? Data()
-
+
let addStatus = SecItemAdd(addQuery as CFDictionary, nil)
if addStatus == errSecSuccess {
SecItemDelete(query as CFDictionary)
}
-
+
switch addStatus {
case errSecSuccess, errSecDuplicateItem:
return .granted
@@ -509,7 +517,7 @@ struct AISettingsView: View {
return .denied(readStatus)
}
}
-
+
private func keychainPermissionExplanation(for status: OSStatus) -> String {
var message = "FluidVoice stores provider API keys securely in your macOS Keychain but does not currently have permission to access it."
if let detail = SecCopyErrorMessageString(status, nil) as String? {
@@ -518,95 +526,105 @@ struct AISettingsView: View {
message += "\n\nClick \"Always Allow\" when the Keychain prompt appears, or open Keychain Access > login > Passwords, locate the FluidVoice entry, and grant access."
return message
}
-
+
@MainActor
private func presentKeychainAccessAlert(message: String) {
let msg = message.isEmpty
? "FluidVoice stores provider API keys securely in your macOS Keychain. Please grant access by choosing \"Always Allow\" when prompted."
: message
-
+
let alert = NSAlert()
alert.messageText = "Keychain Access Required"
alert.informativeText = msg
alert.alertStyle = .warning
alert.addButton(withTitle: "Open Keychain Access")
alert.addButton(withTitle: "OK")
-
+
let response = alert.runModal()
if response == .alertFirstButtonReturn {
if let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.keychainaccess") {
- NSWorkspace.shared.openApplication(at: appURL, configuration: NSWorkspace.OpenConfiguration(), completionHandler: nil)
+ NSWorkspace.shared.openApplication(
+ at: appURL,
+ configuration: NSWorkspace.OpenConfiguration(),
+ completionHandler: nil
+ )
}
}
}
-
+
// MARK: - API Connection Testing
+
private func testAPIConnection() async {
guard !isTestingConnection else { return }
-
+
let apiKey = providerAPIKeys[currentProvider] ?? ""
let baseURL = openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)
let isLocal = isLocalEndpoint(baseURL)
-
+
if isLocal {
guard !baseURL.isEmpty else {
await MainActor.run {
- connectionStatus = .failed
- connectionErrorMessage = "Base URL is required"
+ self.connectionStatus = .failed
+ self.connectionErrorMessage = "Base URL is required"
}
return
}
} else {
- guard !apiKey.isEmpty && !baseURL.isEmpty else {
+ guard !apiKey.isEmpty, !baseURL.isEmpty else {
await MainActor.run {
- connectionStatus = .failed
- connectionErrorMessage = "API key and base URL are required"
+ self.connectionStatus = .failed
+ self.connectionErrorMessage = "API key and base URL are required"
}
return
}
}
-
+
await MainActor.run {
- isTestingConnection = true
- connectionStatus = .testing
- connectionErrorMessage = ""
+ self.isTestingConnection = true
+ self.connectionStatus = .testing
+ self.connectionErrorMessage = ""
}
-
+
do {
let endpoint = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
let fullURL: String
- if endpoint.contains("/chat/completions") || endpoint.contains("/api/chat") || endpoint.contains("/api/generate") {
+ if endpoint.contains("/chat/completions") || endpoint.contains("/api/chat") || endpoint
+ .contains("/api/generate")
+ {
fullURL = endpoint
} else {
fullURL = endpoint + "/chat/completions"
}
-
+
guard let url = URL(string: fullURL) else {
await MainActor.run {
- connectionStatus = .failed
- connectionErrorMessage = "Invalid Base URL format"
+ self.connectionStatus = .failed
+ self.connectionErrorMessage = "Invalid Base URL format"
}
return
}
-
+
let provKey = providerKey(for: selectedProviderID)
- let reasoningConfig = SettingsStore.shared.getReasoningConfig(forModel: selectedModel, provider: provKey)
-
+ let reasoningConfig = SettingsStore.shared.getReasoningConfig(
+ forModel: selectedModel,
+ provider: provKey
+ )
+
let modelLower = selectedModel.lowercased()
let usesMaxCompletionTokens = modelLower.hasPrefix("gpt-5") || modelLower.contains("gpt-5.") ||
- modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3")
-
+ modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3")
+
var requestDict: [String: Any] = [
"model": selectedModel,
- "messages": [["role": "user", "content": "test"]]
+ "messages": [["role": "user", "content": "test"]],
]
-
+
if usesMaxCompletionTokens {
requestDict["max_completion_tokens"] = 50
} else {
requestDict["max_tokens"] = 50
}
-
+
if let config = reasoningConfig, config.isEnabled {
if config.parameterName == "enable_thinking" {
requestDict[config.parameterName] = config.parameterValue == "true"
@@ -614,50 +632,51 @@ struct AISettingsView: View {
requestDict[config.parameterName] = config.parameterValue
}
}
-
+
guard let jsonData = try? JSONSerialization.data(withJSONObject: requestDict, options: []) else {
await MainActor.run {
- connectionStatus = .failed
- connectionErrorMessage = "Failed to encode test request"
+ self.connectionStatus = .failed
+ self.connectionErrorMessage = "Failed to encode test request"
}
return
}
-
+
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.timeoutInterval = 30
-
+
if !isLocal {
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
}
-
+
request.httpBody = jsonData
-
+
let (data, response) = try await URLSession.shared.data(for: request)
-
+
if let httpResponse = response as? HTTPURLResponse {
if (200...299).contains(httpResponse.statusCode) {
await MainActor.run {
- connectionStatus = .success
- connectionErrorMessage = ""
+ self.connectionStatus = .success
+ self.connectionErrorMessage = ""
}
} else {
var errorMessage = "HTTP \(httpResponse.statusCode)"
-
+
if let responseBody = String(data: data, encoding: .utf8),
let jsonData = responseBody.data(using: .utf8),
- let json = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any] {
+ let json = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any]
+ {
if let error = json["error"] as? [String: Any], let message = error["message"] as? String {
errorMessage = message
} else if let message = json["message"] as? String {
errorMessage = message
}
}
-
+
await MainActor.run {
- connectionStatus = .failed
- connectionErrorMessage = errorMessage
+ self.connectionStatus = .failed
+ self.connectionErrorMessage = errorMessage
}
}
}
@@ -669,24 +688,25 @@ struct AISettingsView: View {
case .notConnectedToInternet: errorMessage = "No internet connection"
default: errorMessage = urlError.localizedDescription
}
-
+
await MainActor.run {
connectionStatus = .failed
connectionErrorMessage = errorMessage
}
} catch {
await MainActor.run {
- connectionStatus = .failed
- connectionErrorMessage = error.localizedDescription
+ self.connectionStatus = .failed
+ self.connectionErrorMessage = error.localizedDescription
}
}
-
+
await MainActor.run {
- isTestingConnection = false
+ self.isTestingConnection = false
}
}
-
+
// MARK: - AI Configuration Card
+
private var aiConfigurationCard: some View {
VStack(spacing: 14) {
ThemedCard(style: .prominent, hoverEffect: false) {
@@ -695,71 +715,73 @@ struct AISettingsView: View {
HStack {
Image(systemName: "key.fill")
.font(.title3)
- .foregroundStyle(theme.palette.accent)
+ .foregroundStyle(self.theme.palette.accent)
Text("API Configuration")
.font(.headline)
.fontWeight(.semibold)
Spacer()
- Button(action: { showHelp.toggle() }) {
- Image(systemName: showHelp ? "questionmark.circle.fill" : "questionmark.circle")
+ Button(action: { self.showHelp.toggle() }) {
+ Image(systemName: self.showHelp ? "questionmark.circle.fill" : "questionmark.circle")
.font(.system(size: 20))
- .foregroundStyle(theme.palette.accent.opacity(0.8))
+ .foregroundStyle(self.theme.palette.accent.opacity(0.8))
}
.buttonStyle(.plain)
}
-
+
Divider().padding(.vertical, 3)
-
+
// AI Enhancement Toggle
- aiEnhancementToggle
-
+ self.aiEnhancementToggle
+
// Streaming Toggle
- if enableAIProcessing && selectedProviderID != "apple-intelligence" {
- streamingToggle
+ if self.enableAIProcessing && self.selectedProviderID != "apple-intelligence" {
+ self.streamingToggle
}
-
+
// API Key Warning
- if enableAIProcessing && selectedProviderID != "apple-intelligence" &&
- !isLocalEndpoint(openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)) &&
- (providerAPIKeys[currentProvider] ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
- apiKeyWarningView
+ if self.enableAIProcessing && self.selectedProviderID != "apple-intelligence" &&
+ !self.isLocalEndpoint(self.openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)) &&
+ (self.providerAPIKeys[self.currentProvider] ?? "")
+ .trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ {
+ self.apiKeyWarningView
}
-
+
// Help Section
- if showHelp { helpSectionView }
-
+ if self.showHelp { self.helpSectionView }
+
Divider().padding(.vertical, 3)
-
+
// Provider/Model Configuration
- providerConfigurationSection
+ self.providerConfigurationSection
}
.padding(14)
}
- .modifier(CardAppearAnimation(delay: 0.1, appear: $appear))
-
+ .modifier(CardAppearAnimation(delay: 0.1, appear: self.$appear))
+
// API Keys Guide
- apiKeysGuideCard
+ self.apiKeysGuideCard
}
}
-
+
private var aiEnhancementToggle: some View {
HStack(alignment: .top, spacing: 16) {
VStack(alignment: .leading, spacing: 4) {
Text("Enable AI Enhancement")
.font(.system(size: 15, weight: .semibold))
- .foregroundStyle(theme.palette.primaryText)
+ .foregroundStyle(self.theme.palette.primaryText)
Text("Automatically enhance transcriptions with AI")
.font(.system(size: 13))
- .foregroundStyle(theme.palette.secondaryText)
+ .foregroundStyle(self.theme.palette.secondaryText)
}
Spacer()
- Toggle("", isOn: $enableAIProcessing)
+ Toggle("", isOn: self.$enableAIProcessing)
.toggleStyle(.switch)
.labelsHidden()
}
.padding(.horizontal, 4)
}
-
+
private var streamingToggle: some View {
Group {
Divider().padding(.vertical, 3)
@@ -767,10 +789,10 @@ struct AISettingsView: View {
VStack(alignment: .leading, spacing: 4) {
Text("Enable Streaming")
.font(.system(size: 15, weight: .semibold))
- .foregroundStyle(theme.palette.primaryText)
+ .foregroundStyle(self.theme.palette.primaryText)
Text("Currently only Command Mode shows real-time streaming")
.font(.system(size: 13))
- .foregroundStyle(theme.palette.secondaryText)
+ .foregroundStyle(self.theme.palette.secondaryText)
}
Spacer()
Toggle("", isOn: Binding(
@@ -783,7 +805,7 @@ struct AISettingsView: View {
.padding(.horizontal, 4)
}
}
-
+
private var apiKeyWarningView: some View {
HStack(spacing: 10) {
Image(systemName: "exclamationmark.triangle.fill")
@@ -800,7 +822,7 @@ struct AISettingsView: View {
.overlay(RoundedRectangle(cornerRadius: 8).stroke(.orange.opacity(0.3), lineWidth: 1))
.padding(.horizontal, 4)
}
-
+
private var helpSectionView: some View {
VStack(alignment: .leading, spacing: 10) {
HStack {
@@ -808,11 +830,11 @@ struct AISettingsView: View {
Text("Quick Start Guide").font(.subheadline).fontWeight(.semibold)
}
VStack(alignment: .leading, spacing: 6) {
- helpStep("1", "Enable AI enhancement if needed")
- helpStep("2", "Add/choose any provider of your choice along with its API key")
- helpStep("3", "Add/choose any good model of your liking")
- helpStep("4", "If it's OpenAI compatible endpoint, then update the base URL")
- helpStep("5", "Once everything is set, click verify to check if the connection works")
+ self.helpStep("1", "Enable AI enhancement if needed")
+ self.helpStep("2", "Add/choose any provider of your choice along with its API key")
+ self.helpStep("3", "Add/choose any good model of your liking")
+ self.helpStep("4", "If it's OpenAI compatible endpoint, then update the base URL")
+ self.helpStep("5", "Once everything is set, click verify to check if the connection works")
}
}
.padding(14)
@@ -822,7 +844,7 @@ struct AISettingsView: View {
.padding(.horizontal, 4)
.transition(.opacity)
}
-
+
private func helpStep(_ number: String, _ text: String) -> some View {
HStack(alignment: .top, spacing: 8) {
Text("\(number).")
@@ -830,64 +852,64 @@ struct AISettingsView: View {
Text(text).font(.caption).foregroundStyle(.secondary)
}
}
-
+
private var providerConfigurationSection: some View {
VStack(alignment: .leading, spacing: 10) {
// Compatibility note
- if selectedProviderID == "apple-intelligence" {
+ if self.selectedProviderID == "apple-intelligence" {
HStack(spacing: 6) {
- Image(systemName: "apple.logo").font(.caption2).foregroundStyle(theme.palette.accent)
+ Image(systemName: "apple.logo").font(.caption2).foregroundStyle(self.theme.palette.accent)
Text("Powered by on-device Apple Intelligence").font(.caption).foregroundStyle(.secondary)
}
.padding(.horizontal, 4)
} else {
HStack(spacing: 6) {
- Image(systemName: "checkmark.seal.fill").font(.caption2).foregroundStyle(theme.palette.accent)
+ Image(systemName: "checkmark.seal.fill").font(.caption2).foregroundStyle(self.theme.palette.accent)
Text("Supports any OpenAI compatible API endpoints").font(.caption).foregroundStyle(.secondary)
}
.padding(.horizontal, 4)
}
-
+
Divider()
-
- providerPickerRow
-
- if showingEditProvider { editProviderSection }
-
- if selectedProviderID == "apple-intelligence" { appleIntelligenceBadge }
-
+
+ self.providerPickerRow
+
+ if self.showingEditProvider { self.editProviderSection }
+
+ if self.selectedProviderID == "apple-intelligence" { self.appleIntelligenceBadge }
+
// API Key Management
- if selectedProviderID != "apple-intelligence" {
+ if self.selectedProviderID != "apple-intelligence" {
Divider()
- Button(action: { handleAPIKeyButtonTapped() }) {
+ Button(action: { self.handleAPIKeyButtonTapped() }) {
Label("Add or Modify API Key", systemImage: "key.fill")
.labelStyle(.titleAndIcon).font(.caption)
}
.buttonStyle(GlassButtonStyle())
}
-
+
Divider()
-
+
// Model Row
- if selectedProviderID == "apple-intelligence" {
- appleIntelligenceModelRow
+ if self.selectedProviderID == "apple-intelligence" {
+ self.appleIntelligenceModelRow
} else {
- standardModelRow
- if showingAddModel { addModelSection }
- if showingReasoningConfig { reasoningConfigSection }
+ self.standardModelRow
+ if self.showingAddModel { self.addModelSection }
+ if self.showingReasoningConfig { self.reasoningConfigSection }
}
-
+
Divider()
-
+
// Connection Test
- if selectedProviderID != "apple-intelligence" {
- connectionTestSection
- if showingSaveProvider { addProviderSection }
+ if self.selectedProviderID != "apple-intelligence" {
+ self.connectionTestSection
+ if self.showingSaveProvider { self.addProviderSection }
}
}
.padding(.horizontal, 4)
}
-
+
private var providerPickerRow: some View {
HStack(spacing: 12) {
HStack {
@@ -895,48 +917,57 @@ struct AISettingsView: View {
}
.frame(width: 90, alignment: .leading)
.padding(.horizontal, 10).padding(.vertical, 4)
- .background(LinearGradient(colors: [theme.palette.accent.opacity(0.15), theme.palette.accent.opacity(0.05)], startPoint: .leading, endPoint: .trailing))
+ .background(LinearGradient(
+ colors: [
+ self.theme.palette.accent.opacity(0.15),
+ self.theme.palette.accent.opacity(0.05),
+ ],
+ startPoint: .leading,
+ endPoint: .trailing
+ ))
.cornerRadius(6)
-
- Picker("", selection: $selectedProviderID) {
+
+ Picker("", selection: self.$selectedProviderID) {
Text("OpenAI").tag("openai")
Text("Groq").tag("groq")
if AppleIntelligenceService.isAvailable {
Text("Apple Intelligence").tag("apple-intelligence")
}
- if !savedProviders.isEmpty {
+ if !self.savedProviders.isEmpty {
Divider()
- ForEach(savedProviders) { provider in
+ ForEach(self.savedProviders) { provider in
Text(provider.name).tag(provider.id)
}
}
}
.pickerStyle(.menu).labelsHidden().frame(width: 200)
- .onChange(of: selectedProviderID) { _, newValue in
- handleProviderChange(newValue)
+ .onChange(of: self.selectedProviderID) { _, newValue in
+ self.handleProviderChange(newValue)
}
-
+
// Edit/Delete buttons for custom providers
- if !["openai", "groq", "apple-intelligence"].contains(selectedProviderID) {
- Button(action: { startEditingProvider() }) {
+ if !["openai", "groq", "apple-intelligence"].contains(self.selectedProviderID) {
+ Button(action: { self.startEditingProvider() }) {
HStack(spacing: 4) { Image(systemName: "pencil"); Text("Edit") }.font(.caption)
}
.buttonStyle(CompactButtonStyle())
-
- Button(action: { deleteCurrentProvider() }) {
- HStack(spacing: 4) { Image(systemName: "trash"); Text("Delete") }.font(.caption).foregroundStyle(.red)
+
+ Button(action: { self.deleteCurrentProvider() }) {
+ HStack(spacing: 4) { Image(systemName: "trash"); Text("Delete") }.font(.caption)
+ .foregroundStyle(.red)
}
.buttonStyle(CompactButtonStyle())
}
-
+
Button("+ Add Provider") {
- showingSaveProvider = true
- newProviderName = ""; newProviderBaseURL = ""; newProviderApiKey = ""; newProviderModels = ""
+ self.showingSaveProvider = true
+ self.newProviderName = ""; self.newProviderBaseURL = ""; self.newProviderApiKey = ""; self
+ .newProviderModels = ""
}
.buttonStyle(CompactButtonStyle())
}
}
-
+
private func handleProviderChange(_ newValue: String) {
switch newValue {
case "openai":
@@ -961,12 +992,13 @@ struct AISettingsView: View {
openAIBaseURL = provider.baseURL
updateCurrentProvider()
let key = providerKey(for: newValue)
- availableModels = provider.models.isEmpty ? (availableModelsByProvider[key] ?? []) : provider.models
+ availableModels = provider.models.isEmpty ? (availableModelsByProvider[key] ?? []) : provider
+ .models
selectedModel = selectedModelByProvider[key] ?? availableModels.first ?? selectedModel
}
}
}
-
+
private func startEditingProvider() {
if let provider = savedProviders.first(where: { $0.id == selectedProviderID }) {
editProviderName = provider.name
@@ -974,9 +1006,9 @@ struct AISettingsView: View {
showingEditProvider = true
}
}
-
+
private func deleteCurrentProvider() {
- savedProviders.removeAll { $0.id == selectedProviderID }
+ savedProviders.removeAll { $0.id == self.selectedProviderID }
saveSavedProviders()
let key = providerKey(for: selectedProviderID)
availableModelsByProvider.removeValue(forKey: key)
@@ -991,24 +1023,33 @@ struct AISettingsView: View {
availableModels = defaultModels(for: "openai")
selectedModel = availableModels.first ?? selectedModel
}
-
+
private var editProviderSection: some View {
VStack(spacing: 12) {
HStack { Text("Edit Provider").font(.headline).fontWeight(.semibold); Spacer() }
HStack(spacing: 8) {
VStack(alignment: .leading, spacing: 4) {
Text("Name").font(.caption).foregroundStyle(.secondary)
- TextField("Provider name", text: $editProviderName).textFieldStyle(.roundedBorder).frame(width: 200)
+ TextField("Provider name", text: self.$editProviderName).textFieldStyle(.roundedBorder)
+ .frame(width: 200)
}
VStack(alignment: .leading, spacing: 4) {
Text("Base URL").font(.caption).foregroundStyle(.secondary)
- TextField("e.g., http://localhost:11434/v1", text: $editProviderBaseURL).textFieldStyle(.roundedBorder).font(.system(.body, design: .monospaced))
+ TextField("e.g., http://localhost:11434/v1", text: self.$editProviderBaseURL)
+ .textFieldStyle(.roundedBorder).font(.system(
+ .body,
+ design: .monospaced
+ ))
}
}
HStack(spacing: 8) {
- Button("Save") { saveEditedProvider() }.buttonStyle(GlassButtonStyle())
- .disabled(editProviderName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || editProviderBaseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
- Button("Cancel") { showingEditProvider = false; editProviderName = ""; editProviderBaseURL = "" }.buttonStyle(GlassButtonStyle())
+ Button("Save") { self.saveEditedProvider() }.buttonStyle(GlassButtonStyle())
+ .disabled(self.editProviderName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || self
+ .editProviderBaseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ Button("Cancel") {
+ self.showingEditProvider = false; self.editProviderName = ""; self.editProviderBaseURL = ""
+ }
+ .buttonStyle(GlassButtonStyle())
}
}
.padding(12)
@@ -1018,15 +1059,20 @@ struct AISettingsView: View {
.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)
guard !name.isEmpty, !base.isEmpty else { return }
-
+
if let providerIndex = savedProviders.firstIndex(where: { $0.id == selectedProviderID }) {
let oldProvider = savedProviders[providerIndex]
- let updatedProvider = SettingsStore.SavedProvider(id: oldProvider.id, name: name, baseURL: base, models: oldProvider.models)
+ let updatedProvider = SettingsStore.SavedProvider(
+ id: oldProvider.id,
+ name: name,
+ baseURL: base,
+ models: oldProvider.models
+ )
savedProviders[providerIndex] = updatedProvider
saveSavedProviders()
openAIBaseURL = base
@@ -1035,7 +1081,7 @@ struct AISettingsView: View {
showingEditProvider = false
editProviderName = ""; editProviderBaseURL = ""
}
-
+
private var appleIntelligenceBadge: some View {
HStack(spacing: 8) {
Image(systemName: "apple.logo").font(.system(size: 14))
@@ -1046,77 +1092,102 @@ struct AISettingsView: View {
}
.font(.caption).foregroundStyle(.green)
.padding(.horizontal, 12).padding(.vertical, 8)
- .background(RoundedRectangle(cornerRadius: 8).fill(.green.opacity(0.15)).overlay(RoundedRectangle(cornerRadius: 8).stroke(.green.opacity(0.3), lineWidth: 1)))
+ .background(RoundedRectangle(cornerRadius: 8).fill(.green.opacity(0.15))
+ .overlay(RoundedRectangle(cornerRadius: 8).stroke(
+ .green.opacity(0.3),
+ lineWidth: 1
+ )))
}
-
+
private var appleIntelligenceModelRow: some View {
HStack(spacing: 12) {
HStack { Text("Model:").fontWeight(.medium) }
.frame(width: 90, alignment: .leading)
.padding(.horizontal, 10).padding(.vertical, 4)
- .background(LinearGradient(colors: [theme.palette.accent.opacity(0.15), theme.palette.accent.opacity(0.05)], startPoint: .leading, endPoint: .trailing))
+ .background(LinearGradient(
+ colors: [
+ self.theme.palette.accent.opacity(0.15),
+ self.theme.palette.accent.opacity(0.05),
+ ],
+ startPoint: .leading,
+ endPoint: .trailing
+ ))
.cornerRadius(6)
Text("System Language Model").foregroundStyle(.secondary).font(.system(.body))
Spacer()
}
}
-
+
private var standardModelRow: some View {
HStack(spacing: 12) {
HStack { Text("Model:").fontWeight(.medium) }
.frame(width: 90, alignment: .leading)
.padding(.horizontal, 10).padding(.vertical, 4)
- .background(LinearGradient(colors: [theme.palette.accent.opacity(0.15), theme.palette.accent.opacity(0.05)], startPoint: .leading, endPoint: .trailing))
+ .background(LinearGradient(
+ colors: [
+ self.theme.palette.accent.opacity(0.15),
+ self.theme.palette.accent.opacity(0.05),
+ ],
+ startPoint: .leading,
+ endPoint: .trailing
+ ))
.cornerRadius(6)
-
- Picker("", selection: $selectedModel) {
- ForEach(availableModels, id: \.self) { model in Text(model).tag(model) }
+
+ Picker("", selection: self.$selectedModel) {
+ ForEach(self.availableModels, id: \.self) { model in Text(model).tag(model) }
}
.pickerStyle(.menu).labelsHidden().frame(width: 200)
-
- if !["openai", "groq"].contains(selectedProviderID) {
- Button(action: { deleteSelectedModel() }) {
- HStack(spacing: 4) { Image(systemName: "trash"); Text("Delete") }.font(.caption).foregroundStyle(.red)
+
+ if !["openai", "groq"].contains(self.selectedProviderID) {
+ Button(action: { self.deleteSelectedModel() }) {
+ HStack(spacing: 4) { Image(systemName: "trash"); Text("Delete") }.font(.caption)
+ .foregroundStyle(.red)
}
.buttonStyle(CompactButtonStyle())
}
-
- if !showingAddModel {
- Button("+ Add Model") { showingAddModel = true; newModelName = "" }.buttonStyle(CompactButtonStyle())
+
+ if !self.showingAddModel {
+ Button("+ Add Model") { self.showingAddModel = true; self.newModelName = "" }
+ .buttonStyle(CompactButtonStyle())
}
-
- Button(action: { openReasoningConfig() }) {
+
+ Button(action: { self.openReasoningConfig() }) {
HStack(spacing: 4) {
- Image(systemName: hasReasoningConfigForCurrentModel() ? "brain.fill" : "brain")
+ Image(systemName: self.hasReasoningConfigForCurrentModel() ? "brain.fill" : "brain")
Text("Reasoning")
}
.font(.caption)
- .foregroundStyle(hasReasoningConfigForCurrentModel() ? theme.palette.accent : .secondary)
+ .foregroundStyle(self.hasReasoningConfigForCurrentModel() ? self.theme.palette.accent : .secondary)
}
.buttonStyle(CompactButtonStyle())
}
}
-
+
private func deleteSelectedModel() {
let key = providerKey(for: selectedProviderID)
var list = availableModelsByProvider[key] ?? availableModels
- list.removeAll { $0 == selectedModel }
+ list.removeAll { $0 == self.selectedModel }
if list.isEmpty { list = defaultModels(for: key) }
availableModelsByProvider[key] = list
SettingsStore.shared.availableModelsByProvider = 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, models: list)
+ let updatedProvider = SettingsStore.SavedProvider(
+ id: savedProviders[providerIndex].id,
+ name: savedProviders[providerIndex].name,
+ baseURL: savedProviders[providerIndex].baseURL,
+ models: list
+ )
savedProviders[providerIndex] = updatedProvider
saveSavedProviders()
}
-
+
availableModels = list
selectedModel = list.first ?? ""
selectedModelByProvider[key] = selectedModel
SettingsStore.shared.selectedModelByProvider = selectedModelByProvider
}
-
+
private func openReasoningConfig() {
let pKey = providerKey(for: selectedProviderID)
if let config = SettingsStore.shared.getReasoningConfig(forModel: selectedModel, provider: pKey) {
@@ -1125,9 +1196,11 @@ struct AISettingsView: View {
editingReasoningEnabled = config.isEnabled
} else {
let modelLower = selectedModel.lowercased()
- if modelLower.hasPrefix("gpt-5") || modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3") || modelLower.contains("gpt-oss") {
+ if modelLower.hasPrefix("gpt-5") || modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3") || modelLower
+ .contains("gpt-oss")
+ {
editingReasoningParamName = "reasoning_effort"; editingReasoningParamValue = "low"; editingReasoningEnabled = true
- } else if modelLower.contains("deepseek") && modelLower.contains("reasoner") {
+ } else if modelLower.contains("deepseek"), modelLower.contains("reasoner") {
editingReasoningParamName = "enable_thinking"; editingReasoningParamValue = "true"; editingReasoningEnabled = true
} else {
editingReasoningParamName = "reasoning_effort"; editingReasoningParamValue = "low"; editingReasoningEnabled = false
@@ -1135,34 +1208,38 @@ struct AISettingsView: View {
}
showingReasoningConfig = true
}
-
+
private var addModelSection: some View {
HStack(spacing: 8) {
- TextField("Enter model name", text: $newModelName)
+ TextField("Enter model name", text: self.$newModelName)
.textFieldStyle(.roundedBorder)
- .onSubmit { if !newModelName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { addNewModel() } }
- Button("Add") { addNewModel() }.buttonStyle(CompactButtonStyle())
- .disabled(newModelName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
- Button("Cancel") { showingAddModel = false; newModelName = "" }.buttonStyle(CompactButtonStyle())
+ .onSubmit {
+ if !self.newModelName.trimmingCharacters(in: .whitespacesAndNewlines)
+ .isEmpty { self.addNewModel() }
+ }
+ Button("Add") { self.addNewModel() }.buttonStyle(CompactButtonStyle())
+ .disabled(self.newModelName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ Button("Cancel") { self.showingAddModel = false; self.newModelName = "" }.buttonStyle(CompactButtonStyle())
}
.padding(.leading, 122)
}
-
+
private var reasoningConfigSection: some View {
VStack(alignment: .leading, spacing: 10) {
HStack {
- Image(systemName: "brain.head.profile").foregroundStyle(theme.palette.accent)
- Text("Reasoning Config for \(selectedModel)").font(.caption).fontWeight(.semibold)
+ Image(systemName: "brain.head.profile").foregroundStyle(self.theme.palette.accent)
+ Text("Reasoning Config for \(self.selectedModel)").font(.caption).fontWeight(.semibold)
Spacer()
}
-
- Toggle("Enable reasoning parameter", isOn: $editingReasoningEnabled).toggleStyle(.switch).font(.caption)
-
- if editingReasoningEnabled {
+
+ Toggle("Enable reasoning parameter", isOn: self.$editingReasoningEnabled).toggleStyle(.switch)
+ .font(.caption)
+
+ if self.editingReasoningEnabled {
HStack(spacing: 12) {
VStack(alignment: .leading, spacing: 4) {
Text("Parameter Name").font(.caption2).foregroundStyle(.secondary)
- Picker("", selection: $editingReasoningParamName) {
+ Picker("", selection: self.$editingReasoningParamName) {
Text("reasoning_effort").tag("reasoning_effort")
Text("enable_thinking").tag("enable_thinking")
}
@@ -1170,13 +1247,14 @@ struct AISettingsView: View {
}
VStack(alignment: .leading, spacing: 4) {
Text("Value").font(.caption2).foregroundStyle(.secondary)
- if editingReasoningParamName == "reasoning_effort" {
- Picker("", selection: $editingReasoningParamValue) {
- Text("minimal").tag("minimal"); Text("low").tag("low"); Text("medium").tag("medium"); Text("high").tag("high")
+ if self.editingReasoningParamName == "reasoning_effort" {
+ Picker("", selection: self.$editingReasoningParamValue) {
+ Text("minimal").tag("minimal"); Text("low").tag("low"); Text("medium")
+ .tag("medium"); Text("high").tag("high")
}
.pickerStyle(.menu).labelsHidden().frame(width: 100)
} else {
- Picker("", selection: $editingReasoningParamValue) {
+ Picker("", selection: self.$editingReasoningParamValue) {
Text("true").tag("true"); Text("false").tag("false")
}
.pickerStyle(.menu).labelsHidden().frame(width: 100)
@@ -1184,22 +1262,30 @@ struct AISettingsView: View {
}
}
}
-
+
HStack(spacing: 8) {
- Button("Save") { saveReasoningConfig() }.buttonStyle(GlassButtonStyle())
- Button("Cancel") { showingReasoningConfig = false }.buttonStyle(CompactButtonStyle())
+ Button("Save") { self.saveReasoningConfig() }.buttonStyle(GlassButtonStyle())
+ Button("Cancel") { self.showingReasoningConfig = false }.buttonStyle(CompactButtonStyle())
}
}
.padding(12)
- .background(RoundedRectangle(cornerRadius: 8).fill(theme.palette.accent.opacity(0.08)).overlay(RoundedRectangle(cornerRadius: 8).stroke(theme.palette.accent.opacity(0.2), lineWidth: 1)))
+ .background(RoundedRectangle(cornerRadius: 8).fill(theme.palette.accent.opacity(0.08))
+ .overlay(RoundedRectangle(cornerRadius: 8).stroke(
+ theme.palette.accent.opacity(0.2),
+ lineWidth: 1
+ )))
.padding(.leading, 122)
.transition(.opacity)
}
-
+
private func saveReasoningConfig() {
let pKey = providerKey(for: selectedProviderID)
if editingReasoningEnabled {
- let config = SettingsStore.ModelReasoningConfig(parameterName: editingReasoningParamName, parameterValue: editingReasoningParamValue, isEnabled: true)
+ let config = SettingsStore.ModelReasoningConfig(
+ parameterName: editingReasoningParamName,
+ parameterValue: editingReasoningParamValue,
+ isEnabled: true
+ )
SettingsStore.shared.setReasoningConfig(config, forModel: selectedModel, provider: pKey)
} else {
let config = SettingsStore.ModelReasoningConfig(parameterName: "", parameterValue: "", isEnabled: false)
@@ -1207,105 +1293,122 @@ struct AISettingsView: View {
}
showingReasoningConfig = false
}
-
+
private var connectionTestSection: some View {
VStack(alignment: .leading, spacing: 8) {
HStack(spacing: 12) {
- Button(action: { Task { await testAPIConnection() } }) {
- Text(isTestingConnection ? "Verifying..." : "Verify Connection").font(.caption).fontWeight(.semibold)
+ Button(action: { Task { await self.testAPIConnection() } }) {
+ Text(self.isTestingConnection ? "Verifying..." : "Verify Connection").font(.caption)
+ .fontWeight(.semibold)
}
.buttonStyle(GlassButtonStyle())
- .disabled(isTestingConnection || (!isLocalEndpoint(openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)) && (providerAPIKeys[currentProvider] ?? "").isEmpty))
+ .disabled(self
+ .isTestingConnection ||
+ (!self
+ .isLocalEndpoint(self.openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)) &&
+ (self.providerAPIKeys[self.currentProvider] ?? "").isEmpty))
}
-
+
// Connection Status Display
- if connectionStatus == .success {
+ if self.connectionStatus == .success {
HStack(spacing: 8) {
Image(systemName: "checkmark.circle.fill").foregroundStyle(.green).font(.caption)
Text("Connection verified").font(.caption).foregroundStyle(.green)
}
- } else if connectionStatus == .failed {
+ } else if self.connectionStatus == .failed {
HStack(spacing: 8) {
Image(systemName: "exclamationmark.circle.fill").foregroundStyle(.red).font(.caption)
VStack(alignment: .leading, spacing: 2) {
Text("Connection failed").font(.caption).foregroundStyle(.red)
- if !connectionErrorMessage.isEmpty {
- Text(connectionErrorMessage).font(.caption2).foregroundStyle(.red.opacity(0.8)).lineLimit(1)
+ if !self.connectionErrorMessage.isEmpty {
+ Text(self.connectionErrorMessage).font(.caption2).foregroundStyle(.red.opacity(0.8))
+ .lineLimit(1)
}
}
}
- } else if connectionStatus == .testing {
+ } else if self.connectionStatus == .testing {
HStack(spacing: 8) {
ProgressView().frame(width: 16, height: 16)
- Text("Verifying...").font(.caption).foregroundStyle(theme.palette.accent)
+ Text("Verifying...").font(.caption).foregroundStyle(self.theme.palette.accent)
}
}
-
+
// API Key Editor Sheet
Color.clear.frame(height: 0)
- .sheet(isPresented: $showAPIKeyEditor) {
- apiKeyEditorSheet
+ .sheet(isPresented: self.$showAPIKeyEditor) {
+ self.apiKeyEditorSheet
}
}
}
-
+
private var apiKeyEditorSheet: some View {
VStack(spacing: 14) {
- Text("Enter \(providerDisplayName(for: selectedProviderID)) API Key").font(.headline)
- SecureField("API Key (optional for local endpoints)", text: $newProviderApiKey)
+ Text("Enter \(self.providerDisplayName(for: self.selectedProviderID)) API Key").font(.headline)
+ SecureField("API Key (optional for local endpoints)", text: self.$newProviderApiKey)
.textFieldStyle(.roundedBorder).frame(width: 300)
HStack(spacing: 12) {
- Button("Cancel") { showAPIKeyEditor = false }.buttonStyle(.bordered)
+ Button("Cancel") { self.showAPIKeyEditor = false }.buttonStyle(.bordered)
Button("OK") {
- let trimmedKey = newProviderApiKey.trimmingCharacters(in: .whitespacesAndNewlines)
- providerAPIKeys[currentProvider] = trimmedKey
- saveProviderAPIKeys()
- if connectionStatus != .unknown { connectionStatus = .unknown; connectionErrorMessage = "" }
- showAPIKeyEditor = false
+ let trimmedKey = self.newProviderApiKey.trimmingCharacters(in: .whitespacesAndNewlines)
+ self.providerAPIKeys[self.currentProvider] = trimmedKey
+ self.saveProviderAPIKeys()
+ if self
+ .connectionStatus !=
+ .unknown { self.connectionStatus = .unknown; self.connectionErrorMessage = "" }
+ self.showAPIKeyEditor = false
}
.buttonStyle(.borderedProminent)
- .disabled(!isLocalEndpoint(openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)) && newProviderApiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ .disabled(!self
+ .isLocalEndpoint(self.openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)) && self
+ .newProviderApiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
}
.padding()
.frame(minWidth: 350, minHeight: 150)
}
-
+
private var addProviderSection: some View {
VStack(spacing: 12) {
HStack(spacing: 8) {
- TextField("Provider name", text: $newProviderName).textFieldStyle(.roundedBorder).frame(width: 200)
- TextField("Base URL", text: $newProviderBaseURL).textFieldStyle(.roundedBorder).frame(width: 250)
+ TextField("Provider name", text: self.$newProviderName).textFieldStyle(.roundedBorder).frame(width: 200)
+ TextField("Base URL", text: self.$newProviderBaseURL).textFieldStyle(.roundedBorder).frame(width: 250)
}
HStack(spacing: 8) {
- SecureField("API Key (optional for local)", text: $newProviderApiKey).textFieldStyle(.roundedBorder).frame(width: 200)
- TextField("Models (comma-separated)", text: $newProviderModels).textFieldStyle(.roundedBorder).frame(width: 250)
+ SecureField("API Key (optional for local)", text: self.$newProviderApiKey)
+ .textFieldStyle(.roundedBorder).frame(width: 200)
+ TextField("Models (comma-separated)", text: self.$newProviderModels).textFieldStyle(.roundedBorder)
+ .frame(width: 250)
}
HStack(spacing: 8) {
- Button("Save Provider") { saveNewProvider() }
- .buttonStyle(GlassButtonStyle())
- .disabled(newProviderName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || newProviderBaseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
- Button("Cancel") { showingSaveProvider = false; newProviderName = ""; newProviderBaseURL = ""; newProviderApiKey = ""; newProviderModels = "" }
+ Button("Save Provider") { self.saveNewProvider() }
.buttonStyle(GlassButtonStyle())
+ .disabled(self.newProviderName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || self
+ .newProviderBaseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ Button("Cancel") {
+ self.showingSaveProvider = false; self.newProviderName = ""; self.newProviderBaseURL = ""; self
+ .newProviderApiKey = ""; self.newProviderModels = ""
+ }
+ .buttonStyle(GlassButtonStyle())
}
}
.transition(.opacity)
}
-
+
private func saveNewProvider() {
let name = newProviderName.trimmingCharacters(in: .whitespacesAndNewlines)
let base = newProviderBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)
let api = newProviderApiKey.trimmingCharacters(in: .whitespacesAndNewlines)
guard !name.isEmpty, !base.isEmpty else { return }
-
- let modelsList = newProviderModels.split(separator: ",").map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }
+
+ let modelsList = newProviderModels.split(separator: ",")
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }
let models = modelsList.isEmpty ? 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
@@ -1313,48 +1416,67 @@ struct AISettingsView: View {
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 = ""
}
-
+
private var apiKeysGuideCard: some View {
ThemedCard(style: .prominent, hoverEffect: false) {
VStack(alignment: .leading, spacing: 12) {
- Button(action: { showAPIKeysGuide.toggle() }) {
+ Button(action: { self.showAPIKeysGuide.toggle() }) {
HStack {
Image(systemName: "key.fill").font(.title3).foregroundStyle(.purple)
Text("Get API Keys").font(.headline).fontWeight(.semibold).foregroundStyle(.primary)
Spacer()
- Image(systemName: showAPIKeysGuide ? "chevron.up" : "chevron.down").font(.caption).foregroundStyle(.secondary)
+ Image(systemName: self.showAPIKeysGuide ? "chevron.up" : "chevron.down").font(.caption)
+ .foregroundStyle(.secondary)
}
.contentShape(Rectangle())
}
.buttonStyle(.plain)
-
- if showAPIKeysGuide {
+
+ if self.showAPIKeysGuide {
VStack(alignment: .leading, spacing: 12) {
- ProviderGuide(name: "OpenAI", url: "https://platform.openai.com/api-keys", baseURL: "https://api.openai.com/v1", keyPrefix: "sk-")
- ProviderGuide(name: "Groq", url: "https://console.groq.com/keys", baseURL: "https://api.groq.com/openai/v1", keyPrefix: "gsk_")
- ProviderGuide(name: "OpenRouter", url: "https://openrouter.ai/keys", baseURL: "https://openrouter.ai/api/v1", keyPrefix: "sk-or-")
-
+ ProviderGuide(
+ name: "OpenAI",
+ url: "https://platform.openai.com/api-keys",
+ baseURL: "https://api.openai.com/v1",
+ keyPrefix: "sk-"
+ )
+ ProviderGuide(
+ name: "Groq",
+ url: "https://console.groq.com/keys",
+ baseURL: "https://api.groq.com/openai/v1",
+ keyPrefix: "gsk_"
+ )
+ ProviderGuide(
+ name: "OpenRouter",
+ url: "https://openrouter.ai/keys",
+ baseURL: "https://openrouter.ai/api/v1",
+ keyPrefix: "sk-or-"
+ )
+
Divider()
-
+
HStack(spacing: 8) {
- Image(systemName: "info.circle.fill").font(.caption).foregroundStyle(theme.palette.accent)
+ Image(systemName: "info.circle.fill").font(.caption)
+ .foregroundStyle(self.theme.palette.accent)
VStack(alignment: .leading, spacing: 4) {
- Text("Any OpenAI compatible API endpoint is supported").font(.caption).fontWeight(.semibold)
- Text("Use '+ Add Provider' to add custom providers like Ollama, LM Studio, etc.").font(.caption2).foregroundStyle(.secondary)
+ Text("Any OpenAI compatible API endpoint is supported").font(.caption)
+ .fontWeight(.semibold)
+ Text("Use '+ Add Provider' to add custom providers like Ollama, LM Studio, etc.")
+ .font(.caption2).foregroundStyle(.secondary)
}
}
.padding(12)
- .background(theme.palette.accent.opacity(0.08))
+ .background(self.theme.palette.accent.opacity(0.08))
.cornerRadius(8)
}
.transition(.opacity)
diff --git a/Sources/Fluid/UI/FeedbackView.swift b/Sources/Fluid/UI/FeedbackView.swift
index 31bb787a..b704bb3e 100644
--- a/Sources/Fluid/UI/FeedbackView.swift
+++ b/Sources/Fluid/UI/FeedbackView.swift
@@ -6,13 +6,14 @@
// Created: 2025-12-14
//
-import SwiftUI
import AppKit
+import SwiftUI
struct FeedbackView: View {
@Environment(\.theme) private var theme
-
+
// MARK: - State Variables (moved from ContentView)
+
@State private var feedbackText: String = ""
@State private var feedbackEmail: String = ""
@State private var includeDebugLogs: Bool = false
@@ -21,7 +22,7 @@ struct FeedbackView: View {
@State private var showFeedbackError: Bool = false
@State private var feedbackErrorMessage: String = ""
@State private var appear: Bool = false
-
+
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
@@ -30,7 +31,7 @@ struct FeedbackView: View {
HStack {
Image(systemName: "envelope.fill")
.font(.system(size: 32))
- .foregroundStyle(theme.palette.accent)
+ .foregroundStyle(self.theme.palette.accent)
VStack(alignment: .leading) {
Text("Send Feedback")
.font(.system(size: 28, weight: .bold))
@@ -49,39 +50,39 @@ struct FeedbackView: View {
Image(systemName: "heart.fill")
.font(.system(size: 28))
.foregroundStyle(.pink)
-
+
VStack(alignment: .leading, spacing: 4) {
Text("We'd love to hear from you!")
.font(.system(size: 18, weight: .semibold))
- .foregroundStyle(theme.palette.primaryText)
-
+ .foregroundStyle(self.theme.palette.primaryText)
+
Text("Your feedback helps us make FluidVoice even better")
.font(.system(size: 14))
- .foregroundStyle(theme.palette.secondaryText)
+ .foregroundStyle(self.theme.palette.secondaryText)
}
}
-
+
Divider()
.padding(.vertical, 4)
-
+
HStack(spacing: 12) {
Image(systemName: "star.fill")
.font(.system(size: 24))
.foregroundStyle(.yellow)
-
+
VStack(alignment: .leading, spacing: 6) {
Text("Loving FluidVoice?")
.font(.system(size: 16, weight: .semibold))
- .foregroundStyle(theme.palette.primaryText)
-
+ .foregroundStyle(self.theme.palette.primaryText)
+
Text("Give us a star on GitHub! It helps others discover the project and motivates us to keep improving.")
.font(.system(size: 13))
- .foregroundStyle(theme.palette.secondaryText)
+ .foregroundStyle(self.theme.palette.secondaryText)
.fixedSize(horizontal: false, vertical: true)
}
-
+
Spacer()
-
+
Link(destination: URL(string: "https://github.com/altic-dev/Fluid-oss")!) {
HStack(spacing: 8) {
Image(systemName: "star.fill")
@@ -92,13 +93,11 @@ struct FeedbackView: View {
.foregroundStyle(.white)
.padding(.horizontal, 16)
.padding(.vertical, 10)
- .background(
- LinearGradient(
- colors: [.purple, .blue],
- startPoint: .leading,
- endPoint: .trailing
- )
- )
+ .background(LinearGradient(
+ colors: [.purple, .blue],
+ startPoint: .leading,
+ endPoint: .trailing
+ ))
.cornerRadius(8)
}
.buttonStyle(.plain)
@@ -116,7 +115,7 @@ struct FeedbackView: View {
.font(.headline)
.fontWeight(.semibold)
- TextField("[email protected]", text: $feedbackEmail)
+ TextField("[email protected]", text: self.$feedbackEmail)
.textFieldStyle(.roundedBorder)
.font(.system(size: 14))
@@ -125,131 +124,126 @@ struct FeedbackView: View {
.fontWeight(.semibold)
.padding(.top, 8)
- TextEditor(text: $feedbackText)
+ TextEditor(text: self.$feedbackText)
.font(.system(size: 14))
.frame(height: 120)
.padding(12)
- .background(
- RoundedRectangle(cornerRadius: 8)
- .fill(Color(nsColor: NSColor.textBackgroundColor))
- .overlay(
- RoundedRectangle(cornerRadius: 8)
- .strokeBorder(Color(nsColor: NSColor.separatorColor), lineWidth: 1.5)
- )
- )
+ .background(RoundedRectangle(cornerRadius: 8)
+ .fill(Color(nsColor: NSColor.textBackgroundColor))
+ .overlay(RoundedRectangle(cornerRadius: 8)
+ .strokeBorder(Color(nsColor: NSColor.separatorColor), lineWidth: 1.5)))
.scrollContentBackground(.hidden)
- .overlay(
- VStack {
- if feedbackText.isEmpty {
- Text("Share your thoughts, report bugs, or suggest features...")
- .font(.subheadline)
- .foregroundStyle(.secondary)
- }
+ .overlay(VStack {
+ if self.feedbackText.isEmpty {
+ Text("Share your thoughts, report bugs, or suggest features...")
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
}
- .allowsHitTesting(false)
- )
+ }
+ .allowsHitTesting(false))
// Debug logs option
- Toggle("Include debug logs", isOn: $includeDebugLogs)
+ Toggle("Include debug logs", isOn: self.$includeDebugLogs)
.toggleStyle(GlassToggleStyle())
// Send Button
HStack {
Spacer()
-
+
Button(action: {
Task {
- await sendFeedback()
+ await self.sendFeedback()
}
}) {
HStack(spacing: 8) {
- if isSendingFeedback {
+ if self.isSendingFeedback {
ProgressView()
.scaleEffect(0.8)
} else {
Image(systemName: "paperplane.fill")
}
- Text(isSendingFeedback ? "Sending..." : "Send Feedback")
+ Text(self.isSendingFeedback ? "Sending..." : "Send Feedback")
.fontWeight(.semibold)
}
.padding(.horizontal, 20)
.padding(.vertical, 10)
}
.buttonStyle(GlassButtonStyle())
- .disabled(feedbackText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||
- feedbackEmail.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||
- isSendingFeedback)
+ .disabled(self.feedbackText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||
+ self.feedbackEmail.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||
+ self.isSendingFeedback)
.buttonHoverEffect()
}
}
}
.padding(20)
}
- .modifier(CardAppearAnimation(delay: 0.1, appear: $appear))
+ .modifier(CardAppearAnimation(delay: 0.1, appear: self.$appear))
}
.padding(24)
}
.onAppear {
- appear = true
+ self.appear = true
}
.alert("Feedback Sent", isPresented: $showFeedbackConfirmation) {
- Button("OK") { }
+ Button("OK") {}
} message: {
Text("Thank you for helping us improve FluidVoice.")
}
.alert("Feedback Failed", isPresented: $showFeedbackError) {
Button("Try Again") {
Task {
- await sendFeedback()
+ await self.sendFeedback()
}
}
- Button("Cancel", role: .cancel) { }
+ Button("Cancel", role: .cancel) {}
} message: {
- Text(feedbackErrorMessage)
+ Text(self.feedbackErrorMessage)
}
}
-
+
// MARK: - Feedback Functions
-
+
private func sendFeedback() async {
guard !feedbackEmail.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
- !feedbackText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
+ !feedbackText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ else {
return
}
-
+
await MainActor.run {
- isSendingFeedback = true
+ self.isSendingFeedback = true
}
-
+
let feedbackData = createFeedbackData()
let success = await submitFeedback(data: feedbackData)
-
+
await MainActor.run {
- isSendingFeedback = false
+ self.isSendingFeedback = false
if success {
// Show confirmation and clear form
- showFeedbackConfirmation = true
- feedbackText = ""
- feedbackEmail = ""
- includeDebugLogs = false
+ self.showFeedbackConfirmation = true
+ self.feedbackText = ""
+ self.feedbackEmail = ""
+ self.includeDebugLogs = false
} else {
// Show error to user - inputs are preserved for retry
- feedbackErrorMessage = "We couldn't send your feedback. Please check your internet connection and try again."
- showFeedbackError = true
+ self.feedbackErrorMessage = "We couldn't send your feedback. Please check your internet connection and try again."
+ self.showFeedbackError = true
}
}
}
-
+
private func createFeedbackData() -> [String: Any] {
var feedbackContent = feedbackText.trimmingCharacters(in: .whitespacesAndNewlines)
-
+
if 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"
feedbackContent += "macOS Version: \(ProcessInfo.processInfo.operatingSystemVersionString)\n"
feedbackContent += "Date: \(Date().formatted())\n\n"
-
+
// Add recent log entries
let logFileURL = FileLogger.shared.currentLogFileURL()
if FileManager.default.fileExists(atPath: logFileURL.path) {
@@ -264,39 +258,45 @@ struct FeedbackView: View {
}
}
}
-
+
return [
"email_id": feedbackEmail.trimmingCharacters(in: .whitespacesAndNewlines),
- "feedback": feedbackContent
+ "feedback": feedbackContent,
]
}
-
+
private func submitFeedback(data: [String: Any]) async -> Bool {
guard let url = URL(string: "https://altic.dev/api/fluid/feedback") else {
DebugLogger.shared.error("Invalid feedback API URL", source: "FeedbackView")
return false
}
-
+
do {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONSerialization.data(withJSONObject: data)
-
+
let (_, response) = try await URLSession.shared.data(for: request)
-
+
if let httpResponse = response as? HTTPURLResponse {
let success = (200...299).contains(httpResponse.statusCode)
if success {
DebugLogger.shared.info("Feedback submitted successfully", source: "FeedbackView")
} else {
- DebugLogger.shared.error("Feedback submission failed with status: \(httpResponse.statusCode)", source: "FeedbackView")
+ DebugLogger.shared.error(
+ "Feedback submission failed with status: \(httpResponse.statusCode)",
+ source: "FeedbackView"
+ )
}
return success
}
return false
} catch {
- DebugLogger.shared.error("Network error submitting feedback: \(error.localizedDescription)", source: "FeedbackView")
+ DebugLogger.shared.error(
+ "Network error submitting feedback: \(error.localizedDescription)",
+ source: "FeedbackView"
+ )
return false
}
}
diff --git a/Sources/Fluid/UI/FluidIcon.swift b/Sources/Fluid/UI/FluidIcon.swift
index 95b6a7c5..1a34f8e2 100644
--- a/Sources/Fluid/UI/FluidIcon.swift
+++ b/Sources/Fluid/UI/FluidIcon.swift
@@ -1,42 +1,35 @@
-//
-// FluidIcon.swift
-// Fluid
-//
-// Created by Claude Code
-//
-
import SwiftUI
struct FluidIcon: View {
let size: CGFloat
let lineWidth: CGFloat
let color: Color
-
+
init(size: CGFloat = 24, lineWidth: CGFloat = 2.5, color: Color = .white) {
self.size = size
self.lineWidth = lineWidth
self.color = color
}
-
+
var body: some View {
Canvas { context, canvasSize in
let rect = CGRect(origin: .zero, size: canvasSize)
- let padding: CGFloat = lineWidth / 2
+ let padding: CGFloat = self.lineWidth / 2
let workingRect = rect.insetBy(dx: padding, dy: padding)
-
+
// Geometric F with strategic negative space and bold construction
let path = Path { path in
let width = workingRect.width
let height = workingRect.height
- let strokeWidth = lineWidth
-
+ let strokeWidth = self.lineWidth
+
// Define key points for geometric F construction
let leftEdge = workingRect.minX
let _ = workingRect.maxX
let topEdge = workingRect.minY
let _ = workingRect.maxY
let middleY = workingRect.minY + (height * 0.4) // Slightly above center for better proportions
-
+
// Top horizontal bar - full width, bold
let topBarRect = CGRect(
x: leftEdge,
@@ -45,7 +38,7 @@ struct FluidIcon: View {
height: strokeWidth
)
path.addRect(topBarRect)
-
+
// Vertical spine - bold, geometric
let spineRect = CGRect(
x: leftEdge,
@@ -54,7 +47,7 @@ struct FluidIcon: View {
height: height
)
path.addRect(spineRect)
-
+
// Middle horizontal bar - 60% width for dynamic proportions
let middleBarWidth = width * 0.6
let middleBarRect = CGRect(
@@ -65,35 +58,35 @@ struct FluidIcon: View {
)
path.addRect(middleBarRect)
}
-
+
// Fill the geometric shapes (no stroke, pure geometry)
- context.fill(path, with: .color(color))
-
+ context.fill(path, with: .color(self.color))
+
// Optional: Add subtle inner highlight for premium feel
- if lineWidth > 2 {
+ if self.lineWidth > 2 {
let highlightPath = Path { path in
let highlightOffset: CGFloat = 1
let adjustedRect = workingRect.insetBy(dx: highlightOffset, dy: highlightOffset)
let width = adjustedRect.width
let height = adjustedRect.height
let strokeWidth = max(1, lineWidth - 2)
-
+
let leftEdge = adjustedRect.minX
let topEdge = adjustedRect.minY
let middleY = adjustedRect.minY + (height * 0.4)
-
+
// Thinner inner elements for depth
let topBarRect = CGRect(x: leftEdge, y: topEdge, width: width, height: strokeWidth)
path.addRect(topBarRect)
-
+
let spineRect = CGRect(x: leftEdge, y: topEdge, width: strokeWidth, height: height)
path.addRect(spineRect)
-
+
let middleBarRect = CGRect(x: leftEdge, y: middleY, width: width * 0.6, height: strokeWidth)
path.addRect(middleBarRect)
}
-
- context.fill(highlightPath, with: .color(color.opacity(0.3)))
+
+ context.fill(highlightPath, with: .color(self.color.opacity(0.3)))
}
}
.frame(width: size, height: size)
@@ -106,21 +99,21 @@ struct FluidIconFilled: View {
let color: Color
let backgroundColor: Color
let cornerRadius: CGFloat
-
+
init(size: CGFloat = 32, color: Color = .white, backgroundColor: Color = .blue, cornerRadius: CGFloat = 8) {
self.size = size
self.color = color
self.backgroundColor = backgroundColor
self.cornerRadius = cornerRadius
}
-
+
var body: some View {
ZStack {
- RoundedRectangle(cornerRadius: cornerRadius)
- .fill(backgroundColor)
- .frame(width: size, height: size)
-
- FluidIcon(size: size * 0.6, lineWidth: size * 0.08, color: color)
+ RoundedRectangle(cornerRadius: self.cornerRadius)
+ .fill(self.backgroundColor)
+ .frame(width: self.size, height: self.size)
+
+ FluidIcon(size: self.size * 0.6, lineWidth: self.size * 0.08, color: self.color)
}
}
}
@@ -129,31 +122,31 @@ struct FluidIconFilled: View {
struct FluidIconAdvanced: View {
let size: CGFloat
let color: Color
-
+
init(size: CGFloat = 24, color: Color = .white) {
self.size = size
self.color = color
}
-
+
var body: some View {
Canvas { context, canvasSize in
let rect = CGRect(origin: .zero, size: canvasSize)
- let workingRect = rect.insetBy(dx: size * 0.1, dy: size * 0.1)
-
+ let workingRect = rect.insetBy(dx: self.size * 0.1, dy: self.size * 0.1)
+
// Create sophisticated F with angular cuts and negative space
let path = Path { path in
let width = workingRect.width
let height = workingRect.height
let strokeWidth = max(2, size * 0.12)
let cutAngle: CGFloat = 0.3 // For dynamic angular cuts
-
+
// Main geometric construction points
let leftX = workingRect.minX
let _ = workingRect.maxX
let topY = workingRect.minY
let bottomY = workingRect.maxY
let middleY = workingRect.minY + (height * 0.38)
-
+
// Vertical spine with angular top cut
path.move(to: CGPoint(x: leftX, y: bottomY))
path.addLine(to: CGPoint(x: leftX, y: topY + strokeWidth * cutAngle))
@@ -161,7 +154,7 @@ struct FluidIconAdvanced: View {
path.addLine(to: CGPoint(x: leftX + strokeWidth, y: topY))
path.addLine(to: CGPoint(x: leftX + strokeWidth, y: bottomY))
path.closeSubpath()
-
+
// Top horizontal bar with dynamic width
let topBarWidth = width * 0.85
path.move(to: CGPoint(x: leftX, y: topY))
@@ -169,7 +162,7 @@ struct FluidIconAdvanced: View {
path.addLine(to: CGPoint(x: leftX + topBarWidth - strokeWidth * cutAngle, y: topY + strokeWidth))
path.addLine(to: CGPoint(x: leftX, y: topY + strokeWidth))
path.closeSubpath()
-
+
// Middle bar with angular cut
let middleBarWidth = width * 0.55
path.move(to: CGPoint(x: leftX, y: middleY))
@@ -178,9 +171,9 @@ struct FluidIconAdvanced: View {
path.addLine(to: CGPoint(x: leftX, y: middleY + strokeWidth))
path.closeSubpath()
}
-
- context.fill(path, with: .color(color))
-
+
+ context.fill(path, with: .color(self.color))
+
// Add premium inner glow effect
let glowPath = Path { path in
let inset: CGFloat = 1
@@ -188,18 +181,18 @@ struct FluidIconAdvanced: View {
let strokeWidth = max(1, size * 0.08)
let width = adjustedRect.width
let height = adjustedRect.height
-
+
let leftX = adjustedRect.minX
let topY = adjustedRect.minY
let middleY = adjustedRect.minY + (height * 0.38)
-
+
// Simplified inner elements for glow
path.addRect(CGRect(x: leftX, y: topY, width: strokeWidth, height: height))
path.addRect(CGRect(x: leftX, y: topY, width: width * 0.8, height: strokeWidth))
path.addRect(CGRect(x: leftX, y: middleY, width: width * 0.5, height: strokeWidth))
}
-
- context.fill(glowPath, with: .color(color.opacity(0.4)))
+
+ context.fill(glowPath, with: .color(self.color.opacity(0.4)))
}
.frame(width: size, height: size)
}
@@ -210,37 +203,37 @@ struct FluidIconAdvanced: View {
VStack(spacing: 20) {
Text("Standard Geometric F")
.font(.headline)
-
+
HStack(spacing: 20) {
FluidIcon(size: 24, color: .white)
.background(Color.black.opacity(0.3))
-
+
FluidIcon(size: 32, color: .blue)
-
+
FluidIcon(size: 48, color: .primary)
}
-
+
Text("Advanced Angular F")
.font(.headline)
-
+
HStack(spacing: 20) {
FluidIconAdvanced(size: 24, color: .white)
.background(Color.black.opacity(0.3))
-
+
FluidIconAdvanced(size: 32, color: .blue)
-
+
FluidIconAdvanced(size: 48, color: .primary)
}
-
+
HStack(spacing: 20) {
FluidIconFilled(size: 32, backgroundColor: .blue)
FluidIconFilled(size: 40, backgroundColor: .purple)
FluidIconFilled(size: 48, backgroundColor: .green)
}
-
+
// Large version for app icon
FluidIconFilled(size: 80, backgroundColor: .black, cornerRadius: 16)
}
.padding()
.background(Color.gray.opacity(0.1))
-}
\ No newline at end of file
+}
diff --git a/Sources/Fluid/UI/GlossyEffects.swift b/Sources/Fluid/UI/GlossyEffects.swift
index eb221a06..440752cc 100644
--- a/Sources/Fluid/UI/GlossyEffects.swift
+++ b/Sources/Fluid/UI/GlossyEffects.swift
@@ -1,7 +1,7 @@
import SwiftUI
-
// MARK: - Hoverable Glossy Card Component
+
struct HoverableGlossyCard<Content: View>: View {
@Environment(\.theme) private var theme
@State private var isHovered = false
@@ -22,40 +22,40 @@ struct HoverableGlossyCard<Content: View>: View {
.background(theme.materials.card, in: shape)
.background {
shape
- .fill(theme.palette.cardBackground)
- .overlay(
- shape
- .stroke(
- theme.palette.cardBorder.opacity(isHovered ? 0.5 : 0.25),
- lineWidth: isHovered ? 1.2 : 1
- )
- )
+ .fill(self.theme.palette.cardBackground)
+ .overlay(shape
+ .stroke(
+ self.theme.palette.cardBorder.opacity(self.isHovered ? 0.5 : 0.25),
+ lineWidth: self.isHovered ? 1.2 : 1
+ ))
.shadow(
- color: cardShadow.color.opacity(isHovered ? min(cardShadow.opacity + 0.1, 1.0) : cardShadow.opacity),
- radius: isHovered ? cardShadow.radius + 2 : cardShadow.radius,
+ color: cardShadow.color
+ .opacity(self.isHovered ? min(cardShadow.opacity + 0.1, 1.0) : cardShadow.opacity),
+ radius: self.isHovered ? cardShadow.radius + 2 : cardShadow.radius,
x: cardShadow.x,
- y: isHovered ? cardShadow.y + 1 : cardShadow.y
+ y: self.isHovered ? cardShadow.y + 1 : cardShadow.y
)
}
.scaleEffect(isHovered && !excludeInteractiveElements ? 1.02 : 1.0)
.onHover { hovering in
- isHovered = hovering
+ self.isHovered = hovering
}
.animation(.easeOut(duration: 0.18), value: isHovered)
}
}
// MARK: - Button Hover Extension
+
extension View {
func buttonHoverEffect() -> some View {
- self.modifier(ButtonHoverModifier())
+ modifier(ButtonHoverModifier())
}
}
struct ButtonHoverModifier: ViewModifier {
@Environment(\.theme) private var theme
@State private var isHovered = false
-
+
func body(content: Content) -> some View {
content
.scaleEffect(isHovered ? 1.05 : 1.0)
@@ -65,8 +65,8 @@ struct ButtonHoverModifier: ViewModifier {
x: 0,
y: isHovered ? 3 : 0
)
- .onHover { hovering in
- isHovered = hovering
+ .onHover { hovering in
+ self.isHovered = hovering
}
.animation(.spring(response: 0.2, dampingFraction: 0.7), value: isHovered)
}
@@ -105,6 +105,3 @@ struct ButtonHoverModifier: ViewModifier {
// }
// }
// }
-
-
-
diff --git a/Sources/Fluid/UI/MeetingTranscriptionView.swift b/Sources/Fluid/UI/MeetingTranscriptionView.swift
index 4dcbc09d..6fdc3620 100644
--- a/Sources/Fluid/UI/MeetingTranscriptionView.swift
+++ b/Sources/Fluid/UI/MeetingTranscriptionView.swift
@@ -5,20 +5,21 @@ struct MeetingTranscriptionView: View {
let asrService: ASRService
@StateObject private var transcriptionService: MeetingTranscriptionService
@State private var selectedFileURL: URL?
-
+
init(asrService: ASRService) {
self.asrService = asrService
- self._transcriptionService = StateObject(wrappedValue: MeetingTranscriptionService(asrService: asrService))
+ _transcriptionService = StateObject(wrappedValue: MeetingTranscriptionService(asrService: asrService))
}
+
@State private var showingFilePicker = false
@State private var showingExportDialog = false
@State private var exportFormat: ExportFormat = .text
@State private var showingCopyConfirmation = false
-
+
enum ExportFormat: String, CaseIterable {
case text = "Text (.txt)"
case json = "JSON (.json)"
-
+
var fileExtension: String {
switch self {
case .text: return "txt"
@@ -26,7 +27,7 @@ struct MeetingTranscriptionView: View {
}
}
}
-
+
var body: some View {
VStack(spacing: 0) {
// Header
@@ -34,37 +35,37 @@ struct MeetingTranscriptionView: View {
Image(systemName: "waveform.circle.fill")
.font(.system(size: 48))
.foregroundStyle(.green.gradient)
-
+
Text("Meeting Transcription")
.font(.title2)
.fontWeight(.semibold)
-
+
Text("Upload audio or video files to transcribe")
.font(.subheadline)
.foregroundColor(.secondary)
}
.padding(.top, 40)
.padding(.bottom, 30)
-
+
// Main Content Area
ScrollView {
VStack(spacing: 24) {
// File Selection Card
- fileSelectionCard
-
+ self.fileSelectionCard
+
// Progress Card (only show when transcribing)
- if transcriptionService.isTranscribing {
- progressCard
+ if self.transcriptionService.isTranscribing {
+ self.progressCard
}
-
+
// Results Card (only show when we have results)
if let result = transcriptionService.result {
- resultsCard(result: result)
+ self.resultsCard(result: result)
}
-
+
// Error Card (only show when we have an error)
if let error = transcriptionService.error {
- errorCard(error: error)
+ self.errorCard(error: error)
}
}
.padding(24)
@@ -73,7 +74,7 @@ struct MeetingTranscriptionView: View {
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color(nsColor: .windowBackgroundColor))
.overlay(alignment: .topTrailing) {
- if showingCopyConfirmation {
+ if self.showingCopyConfirmation {
Text("Copied!")
.font(.caption)
.padding(.horizontal, 12)
@@ -86,9 +87,9 @@ struct MeetingTranscriptionView: View {
}
}
}
-
+
// MARK: - File Selection Card
-
+
private var fileSelectionCard: some View {
VStack(spacing: 16) {
if let fileURL = selectedFileURL {
@@ -97,21 +98,21 @@ struct MeetingTranscriptionView: View {
Image(systemName: "doc.fill")
.font(.title2)
.foregroundColor(.green)
-
+
VStack(alignment: .leading, spacing: 4) {
Text(fileURL.lastPathComponent)
.font(.headline)
-
- Text(formatFileSize(fileURL: fileURL))
+
+ Text(self.formatFileSize(fileURL: fileURL))
.font(.caption)
.foregroundColor(.secondary)
}
-
+
Spacer()
-
+
Button(action: {
- selectedFileURL = nil
- transcriptionService.reset()
+ self.selectedFileURL = nil
+ self.transcriptionService.reset()
}) {
Image(systemName: "xmark.circle.fill")
.foregroundColor(.secondary)
@@ -121,11 +122,11 @@ struct MeetingTranscriptionView: View {
.padding()
.background(Color(nsColor: .controlBackgroundColor))
.cornerRadius(8)
-
+
// Transcribe Button
Button(action: {
Task {
- await transcribeFile()
+ await self.transcribeFile()
}
}) {
HStack {
@@ -136,20 +137,20 @@ struct MeetingTranscriptionView: View {
.padding(.vertical, 12)
}
.buttonStyle(.borderedProminent)
- .disabled(transcriptionService.isTranscribing)
-
+ .disabled(self.transcriptionService.isTranscribing)
+
} else {
// File picker button
Button(action: {
- showingFilePicker = true
+ self.showingFilePicker = true
}) {
VStack(spacing: 12) {
Image(systemName: "arrow.up.doc.fill")
.font(.system(size: 32))
-
+
Text("Choose Audio or Video File")
.font(.headline)
-
+
Text("Supported: WAV, MP3, M4A, MP4, MOV, and more")
.font(.caption)
.foregroundColor(.secondary)
@@ -160,11 +161,9 @@ struct MeetingTranscriptionView: View {
.buttonStyle(.plain)
.background(Color(nsColor: .controlBackgroundColor))
.cornerRadius(12)
- .overlay(
- RoundedRectangle(cornerRadius: 12)
- .strokeBorder(style: StrokeStyle(lineWidth: 2, dash: [8]))
- .foregroundColor(.green.opacity(0.3))
- )
+ .overlay(RoundedRectangle(cornerRadius: 12)
+ .strokeBorder(style: StrokeStyle(lineWidth: 2, dash: [8]))
+ .foregroundColor(.green.opacity(0.3)))
}
}
.fileImporter(
@@ -180,29 +179,29 @@ struct MeetingTranscriptionView: View {
allowsMultipleSelection: false
) { result in
switch result {
- case .success(let urls):
+ case let .success(urls):
if let url = urls.first {
- selectedFileURL = url
- transcriptionService.reset()
+ self.selectedFileURL = url
+ self.transcriptionService.reset()
}
- case .failure(let error):
+ case let .failure(error):
print("File picker error: \(error)")
}
}
}
-
+
// MARK: - Progress Card
-
+
private var progressCard: some View {
VStack(spacing: 16) {
- ProgressView(value: transcriptionService.progress)
+ ProgressView(value: self.transcriptionService.progress)
.progressViewStyle(.linear)
-
+
HStack {
ProgressView()
.controlSize(.small)
-
- Text(transcriptionService.currentStatus)
+
+ Text(self.transcriptionService.currentStatus)
.font(.subheadline)
.foregroundColor(.secondary)
}
@@ -211,9 +210,9 @@ struct MeetingTranscriptionView: View {
.background(Color(nsColor: .controlBackgroundColor))
.cornerRadius(12)
}
-
+
// MARK: - Results Card
-
+
private func resultsCard(result: TranscriptionResult) -> some View {
VStack(alignment: .leading, spacing: 16) {
// Header with stats
@@ -221,29 +220,32 @@ struct MeetingTranscriptionView: View {
VStack(alignment: .leading, spacing: 4) {
Text("Transcription Complete")
.font(.headline)
-
+
HStack(spacing: 16) {
Label("\(String(format: "%.1f", result.duration))s", systemImage: "clock")
Label("\(String(format: "%.0f%%", result.confidence * 100))", systemImage: "checkmark.circle")
- Label("\(String(format: "%.1f", result.duration / result.processingTime))x", systemImage: "speedometer")
+ Label(
+ "\(String(format: "%.1f", result.duration / result.processingTime))x",
+ systemImage: "speedometer"
+ )
}
.font(.caption)
.foregroundColor(.secondary)
}
-
+
Spacer()
-
+
// Action buttons
HStack(spacing: 8) {
Button(action: {
- copyToClipboard(result.text)
+ self.copyToClipboard(result.text)
}) {
Image(systemName: "doc.on.doc")
}
.help("Copy to clipboard")
-
+
Button(action: {
- showingExportDialog = true
+ self.showingExportDialog = true
}) {
Image(systemName: "square.and.arrow.up")
}
@@ -251,9 +253,9 @@ struct MeetingTranscriptionView: View {
}
.buttonStyle(.borderless)
}
-
+
Divider()
-
+
// Transcription text
ScrollView {
Text(result.text)
@@ -282,26 +284,26 @@ struct MeetingTranscriptionView: View {
switch result {
case .success:
print("File exported successfully")
- case .failure(let error):
+ case let .failure(error):
print("Export failed: \(error)")
}
}
}
-
+
// MARK: - Error Card
-
+
private func errorCard(error: String) -> some View {
HStack {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundColor(.red)
-
+
Text(error)
.font(.subheadline)
-
+
Spacer()
-
+
Button("Dismiss") {
- transcriptionService.reset()
+ self.transcriptionService.reset()
}
.buttonStyle(.borderless)
}
@@ -309,41 +311,42 @@ struct MeetingTranscriptionView: View {
.background(Color.red.opacity(0.1))
.cornerRadius(12)
}
-
+
// MARK: - Helper Functions
-
+
private func transcribeFile() async {
guard let fileURL = selectedFileURL else { return }
-
+
do {
_ = try await transcriptionService.transcribeFile(fileURL)
} catch {
print("Transcription error: \(error)")
}
}
-
+
private func formatFileSize(fileURL: URL) -> String {
guard let attributes = try? FileManager.default.attributesOfItem(atPath: fileURL.path),
- let fileSize = attributes[.size] as? Int64 else {
+ let fileSize = attributes[.size] as? Int64
+ else {
return "Unknown size"
}
-
+
let formatter = ByteCountFormatter()
formatter.countStyle = .file
return formatter.string(fromByteCount: fileSize)
}
-
+
private func copyToClipboard(_ text: String) {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(text, forType: .string)
-
+
withAnimation {
- showingCopyConfirmation = true
+ self.showingCopyConfirmation = true
}
-
+
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
withAnimation {
- showingCopyConfirmation = false
+ self.showingCopyConfirmation = false
}
}
}
@@ -353,36 +356,38 @@ struct MeetingTranscriptionView: View {
struct TranscriptionDocument: FileDocument {
static var readableContentTypes: [UTType] { [.plainText, .json] }
-
+
let result: TranscriptionResult
let format: MeetingTranscriptionView.ExportFormat
let service: MeetingTranscriptionService
-
- init(result: TranscriptionResult,
- format: MeetingTranscriptionView.ExportFormat,
- service: MeetingTranscriptionService) {
+
+ init(
+ result: TranscriptionResult,
+ format: MeetingTranscriptionView.ExportFormat,
+ service: MeetingTranscriptionService
+ ) {
self.result = result
self.format = format
self.service = service
}
-
+
init(configuration: ReadConfiguration) throws {
fatalError("Reading not supported")
}
-
+
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent("temp.\(format.fileExtension)")
-
+
switch format {
case .text:
try service.exportToText(result, to: tempURL)
case .json:
try service.exportToJSON(result, to: tempURL)
}
-
+
let data = try Data(contentsOf: tempURL)
try? FileManager.default.removeItem(at: tempURL)
-
+
return FileWrapper(regularFileWithContents: data)
}
}
@@ -393,4 +398,3 @@ struct TranscriptionDocument: FileDocument {
MeetingTranscriptionView(asrService: ASRService())
.frame(width: 700, height: 800)
}
-
diff --git a/Sources/Fluid/UI/MenuBarIconGenerator.swift b/Sources/Fluid/UI/MenuBarIconGenerator.swift
index f7b353ce..9e9b9106 100644
--- a/Sources/Fluid/UI/MenuBarIconGenerator.swift
+++ b/Sources/Fluid/UI/MenuBarIconGenerator.swift
@@ -4,56 +4,56 @@ class MenuBarIconGenerator {
static func createMenuBarIcon() -> NSImage? {
let size = NSSize(width: 18, height: 18)
let image = NSImage(size: size)
-
+
image.lockFocus()
-
+
// Clear background (transparent)
NSColor.clear.set()
NSRect(origin: .zero, size: size).fill()
-
+
// Draw white "F" shape
NSColor.white.set()
-
+
let path = NSBezierPath()
-
+
// F shape proportions for 18x18 icon
let x: CGFloat = 4
let y: CGFloat = 2
let width: CGFloat = 10
let height: CGFloat = 14
let strokeWidth: CGFloat = 2
-
+
// Vertical line of F
path.move(to: NSPoint(x: x, y: y))
path.line(to: NSPoint(x: x, y: y + height))
path.line(to: NSPoint(x: x + strokeWidth, y: y + height))
path.line(to: NSPoint(x: x + strokeWidth, y: y + height * 0.6))
-
+
// Top horizontal line
path.line(to: NSPoint(x: x + width * 0.7, y: y + height * 0.6))
path.line(to: NSPoint(x: x + width * 0.7, y: y + height * 0.6 + strokeWidth))
path.line(to: NSPoint(x: x + strokeWidth, y: y + height * 0.6 + strokeWidth))
-
+
// Middle horizontal line
path.line(to: NSPoint(x: x + strokeWidth, y: y + height * 0.8))
path.line(to: NSPoint(x: x + width * 0.6, y: y + height * 0.8))
path.line(to: NSPoint(x: x + width * 0.6, y: y + height * 0.8 + strokeWidth))
path.line(to: NSPoint(x: x + strokeWidth, y: y + height * 0.8 + strokeWidth))
-
+
// Complete the F
path.line(to: NSPoint(x: x + strokeWidth, y: y + height))
path.line(to: NSPoint(x: x + width, y: y + height))
path.line(to: NSPoint(x: x + width, y: y + height - strokeWidth))
path.line(to: NSPoint(x: x, y: y + height - strokeWidth))
path.close()
-
+
path.fill()
-
+
image.unlockFocus()
-
+
// Set as template image
image.isTemplate = true
-
+
return image
}
-}
\ No newline at end of file
+}
diff --git a/Sources/Fluid/UI/MouseTracker.swift b/Sources/Fluid/UI/MouseTracker.swift
index 411ab587..9289e1a0 100644
--- a/Sources/Fluid/UI/MouseTracker.swift
+++ b/Sources/Fluid/UI/MouseTracker.swift
@@ -1,16 +1,16 @@
-import SwiftUI
import Combine
+import SwiftUI
@MainActor
class MousePositionTracker: ObservableObject {
@Published var mousePosition: CGPoint = .zero
@Published var windowFrame: CGRect = .zero
-
+
private var lastUpdateTime: TimeInterval = 0
private var lastFrameUpdateTime: TimeInterval = 0
- private let updateInterval: TimeInterval = 1.0/15.0 // 15fps (reduced for performance during gestures)
+ private let updateInterval: TimeInterval = 1.0 / 15.0 // 15fps (reduced for performance during gestures)
private let frameUpdateInterval: TimeInterval = 0.1 // Debounce frame updates during scroll
-
+
var relativePosition: CGPoint {
guard windowFrame.width > 0 && windowFrame.height > 0 else { return .zero }
return CGPoint(
@@ -18,29 +18,29 @@ class MousePositionTracker: ObservableObject {
y: (mousePosition.y - windowFrame.minY) / windowFrame.height
)
}
-
+
func updateMousePosition(_ position: CGPoint) {
// Validate position to prevent infinity/NaN geometry errors
- guard position.x.isFinite && position.y.isFinite else { return }
- guard position.x >= 0 && position.y >= 0 else { return }
-
+ guard position.x.isFinite, position.y.isFinite else { return }
+ guard position.x >= 0, position.y >= 0 else { return }
+
let now = CACurrentMediaTime()
guard now - lastUpdateTime >= updateInterval else { return }
-
+
mousePosition = position
lastUpdateTime = now
}
-
+
func updateWindowFrame(_ frame: CGRect) {
// Validate frame to prevent infinity/NaN geometry errors
- guard frame.width.isFinite && frame.height.isFinite else { return }
- guard frame.minX.isFinite && frame.minY.isFinite else { return }
- guard frame.width > 0 && frame.height > 0 else { return }
-
+ guard frame.width.isFinite, frame.height.isFinite else { return }
+ guard frame.minX.isFinite, frame.minY.isFinite else { return }
+ guard frame.width > 0, frame.height > 0 else { return }
+
// Debounce frame updates during scroll to prevent rapid invalid geometry
let now = CACurrentMediaTime()
guard now - lastFrameUpdateTime >= frameUpdateInterval else { return }
-
+
windowFrame = frame
lastFrameUpdateTime = now
}
@@ -48,46 +48,44 @@ class MousePositionTracker: ObservableObject {
struct MouseTrackingModifier: ViewModifier {
let tracker: MousePositionTracker
-
+
func body(content: Content) -> some View {
content
.onContinuousHover { phase in
switch phase {
- case .active(let location):
+ case let .active(location):
// Validate location is finite before processing
guard location.x.isFinite && location.y.isFinite else { return }
- guard tracker.windowFrame != .zero else { return }
-
+ guard self.tracker.windowFrame != .zero else { return }
+
// Convert to global coordinates for consistent tracking
let globalLocation = CGPoint(
- x: location.x + tracker.windowFrame.minX,
- y: location.y + tracker.windowFrame.minY
+ x: location.x + self.tracker.windowFrame.minX,
+ y: location.y + self.tracker.windowFrame.minY
)
- tracker.updateMousePosition(globalLocation)
+ self.tracker.updateMousePosition(globalLocation)
case .ended:
break
}
}
- .background(
- GeometryReader { geometry in
- Color.clear
- .onAppear {
- let globalFrame = geometry.frame(in: .global)
- tracker.updateWindowFrame(globalFrame)
- }
- .onChange(of: geometry.frame(in: .global)) { _, newFrame in
- // Skip updates when view is scrolled off-screen (prevents invalid geometry)
- guard newFrame.minY < NSScreen.main?.frame.height ?? 1000 else { return }
- guard newFrame.maxY > 0 else { return }
- tracker.updateWindowFrame(newFrame)
- }
- }
- )
+ .background(GeometryReader { geometry in
+ Color.clear
+ .onAppear {
+ let globalFrame = geometry.frame(in: .global)
+ self.tracker.updateWindowFrame(globalFrame)
+ }
+ .onChange(of: geometry.frame(in: .global)) { _, newFrame in
+ // Skip updates when view is scrolled off-screen (prevents invalid geometry)
+ guard newFrame.minY < NSScreen.main?.frame.height ?? 1000 else { return }
+ guard newFrame.maxY > 0 else { return }
+ self.tracker.updateWindowFrame(newFrame)
+ }
+ })
}
}
extension View {
func withMouseTracking(_ tracker: MousePositionTracker) -> some View {
- self.modifier(MouseTrackingModifier(tracker: tracker))
+ modifier(MouseTrackingModifier(tracker: tracker))
}
-}
\ No newline at end of file
+}
diff --git a/Sources/Fluid/UI/RecordingView.swift b/Sources/Fluid/UI/RecordingView.swift
index f96b4fcd..6508152f 100644
--- a/Sources/Fluid/UI/RecordingView.swift
+++ b/Sources/Fluid/UI/RecordingView.swift
@@ -1,22 +1,15 @@
-//
-// RecordingView.swift
-// fluid
-//
-// Recording controls and configuration view
-//
-
-import SwiftUI
import AVFoundation
+import SwiftUI
struct RecordingView: View {
@EnvironmentObject var appServices: AppServices
private var asr: ASRService { appServices.asr }
@Environment(\.theme) private var theme
@Binding var appear: Bool
-
+
let stopAndProcessTranscription: () async -> Void
let startRecording: () -> Void
-
+
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 14) {
@@ -45,44 +38,45 @@ struct RecordingView: View {
// Status indicator
HStack {
Circle()
- .fill(asr.isRunning ? .red : asr.isAsrReady ? .green : .secondary)
+ .fill(self.asr.isRunning ? .red : self.asr.isAsrReady ? .green : .secondary)
.frame(width: 8, height: 8)
- Text(asr.isRunning ? "Recording..." : asr.isAsrReady ? "Ready to record" : "Model not ready")
+ Text(self.asr.isRunning ? "Recording..." : self.asr
+ .isAsrReady ? "Ready to record" : "Model not ready")
.font(.subheadline)
- .foregroundStyle(asr.isRunning ? .red : asr.isAsrReady ? .green : .secondary)
+ .foregroundStyle(self.asr.isRunning ? .red : self.asr
+ .isAsrReady ? .green : .secondary)
}
// Recording Control (Single Toggle Button)
Button(action: {
- if asr.isRunning {
+ if self.asr.isRunning {
Task {
- await stopAndProcessTranscription()
+ await self.stopAndProcessTranscription()
}
} else {
- startRecording()
+ self.startRecording()
}
}) {
HStack {
- Image(systemName: asr.isRunning ? "stop.fill" : "mic.fill")
+ Image(systemName: self.asr.isRunning ? "stop.fill" : "mic.fill")
.font(.system(size: 16, weight: .semibold))
- Text(asr.isRunning ? "Stop Recording" : "Start Recording")
+ Text(self.asr.isRunning ? "Stop Recording" : "Start Recording")
}
.frame(maxWidth: .infinity)
}
- .buttonStyle(PremiumButtonStyle(isRecording: asr.isRunning))
+ .buttonStyle(PremiumButtonStyle(isRecording: self.asr.isRunning))
.buttonHoverEffect()
- .scaleEffect(asr.isRunning ? 1.05 : 1.0)
- .animation(.spring(response: 0.3), value: asr.isRunning)
- .disabled(!asr.isAsrReady && !asr.isRunning)
+ .scaleEffect(self.asr.isRunning ? 1.05 : 1.0)
+ .animation(.spring(response: 0.3), value: self.asr.isRunning)
+ .disabled(!self.asr.isAsrReady && !self.asr.isRunning)
}
}
.padding(14)
}
- .modifier(CardAppearAnimation(delay: 0.1, appear: $appear))
+ .modifier(CardAppearAnimation(delay: 0.1, appear: self.$appear))
}
.padding(14)
}
}
}
-
diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swift
index 50ccf4bc..d4f565f3 100644
--- a/Sources/Fluid/UI/SettingsView.swift
+++ b/Sources/Fluid/UI/SettingsView.swift
@@ -1,13 +1,6 @@
-//
-// SettingsView.swift
-// fluid
-//
-// App preferences and audio device settings
-//
-
-import SwiftUI
import AVFoundation
import PromiseKit
+import SwiftUI
struct SettingsView: View {
@EnvironmentObject var appServices: AppServices
@@ -32,13 +25,13 @@ struct SettingsView: View {
@Binding var pressAndHoldModeEnabled: Bool
@Binding var enableStreamingPreview: Bool
@Binding var copyToClipboard: Bool
-
+
// CRITICAL FIX: Cache default device names to avoid CoreAudio calls during view body evaluation.
// Querying AudioDevice.getDefaultInputDevice() in the view body triggers HALSystem::InitializeShell()
// which races with SwiftUI's AttributeGraph metadata processing and causes EXC_BAD_ACCESS crashes.
@State private var cachedDefaultInputName: String = ""
@State private var cachedDefaultOutputName: String = ""
-
+
let hotkeyManager: GlobalHotkeyManager?
let menuBarManager: MenuBarManager
let startRecording: () -> Void
@@ -47,7 +40,7 @@ struct SettingsView: View {
let restartApp: () -> Void
let revealAppInFinder: () -> Void
let openApplicationsFolder: () -> Void
-
+
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 16) {
@@ -61,7 +54,7 @@ struct SettingsView: View {
VStack(spacing: 0) {
// Launch at startup
- settingsToggleRow(
+ self.settingsToggleRow(
title: "Launch at startup",
description: "Automatically start FluidVoice when you log in",
footnote: "Note: Requires app to be signed for this to work.",
@@ -74,7 +67,7 @@ struct SettingsView: View {
Divider().padding(.vertical, 10)
// Show in Dock
- settingsToggleRow(
+ self.settingsToggleRow(
title: "Show in Dock",
description: "Display FluidVoice icon in the Dock",
footnote: "Note: May require app restart to take effect.",
@@ -96,31 +89,34 @@ struct SettingsView: View {
.font(.subheadline)
.foregroundStyle(.secondary)
}
-
+
Spacer()
-
+
Toggle("", isOn: Binding(
get: { SettingsStore.shared.autoUpdateCheckEnabled },
set: { SettingsStore.shared.autoUpdateCheckEnabled = $0 }
))
.toggleStyle(.switch)
- .tint(theme.palette.accent)
+ .tint(self.theme.palette.accent)
.labelsHidden()
}
-
+
if let lastCheck = SettingsStore.shared.lastUpdateCheckDate {
Text("Last checked: \(lastCheck.formatted(date: .abbreviated, time: .shortened))")
.font(.caption)
.foregroundStyle(.tertiary)
}
}
-
+
// Update Buttons
HStack(spacing: 10) {
Button("Check for Updates") {
Task { @MainActor in
do {
- try await SimpleUpdater.shared.checkAndUpdate(owner: "altic-dev", repo: "Fluid-oss")
+ try await SimpleUpdater.shared.checkAndUpdate(
+ owner: "altic-dev",
+ repo: "Fluid-oss"
+ )
let ok = NSAlert()
ok.messageText = "Update Found!"
ok.informativeText = "A new version is available and will be installed now."
@@ -142,9 +138,9 @@ struct SettingsView: View {
}
}
.buttonStyle(.borderedProminent)
- .tint(theme.palette.accent)
+ .tint(self.theme.palette.accent)
.controlSize(.regular)
-
+
Button("Release Notes") {
if let url = URL(string: "https://github.com/altic-dev/Fluid-oss/releases") {
NSWorkspace.shared.open(url)
@@ -158,47 +154,49 @@ struct SettingsView: View {
}
.padding(16)
}
-
+
// Microphone Permission Card
ThemedCard(style: .standard) {
VStack(alignment: .leading, spacing: 14) {
Label("Microphone Permission", systemImage: "mic.fill")
.font(.headline)
.foregroundStyle(.primary)
-
+
VStack(alignment: .leading, spacing: 12) {
HStack(spacing: 10) {
Circle()
- .fill(asr.micStatus == .authorized ? theme.palette.success : theme.palette.warning)
+ .fill(self.asr.micStatus == .authorized ? self.theme.palette.success : self.theme
+ .palette.warning)
.frame(width: 8, height: 8)
-
+
VStack(alignment: .leading, spacing: 2) {
- Text(asr.micStatus == .authorized ? "Microphone access granted" :
- asr.micStatus == .denied ? "Microphone access denied" :
- "Microphone access not determined")
+ Text(self.asr.micStatus == .authorized ? "Microphone access granted" :
+ self.asr.micStatus == .denied ? "Microphone access denied" :
+ "Microphone access not determined")
.font(.body)
- .foregroundStyle(asr.micStatus == .authorized ? .primary : theme.palette.warning)
-
- if asr.micStatus != .authorized {
+ .foregroundStyle(self.asr.micStatus == .authorized ? .primary : self.theme
+ .palette.warning)
+
+ if self.asr.micStatus != .authorized {
Text("Microphone access is required for voice recording")
.font(.subheadline)
.foregroundStyle(.secondary)
}
}
Spacer()
-
- if asr.micStatus == .notDetermined {
+
+ if self.asr.micStatus == .notDetermined {
Button {
- asr.requestMicAccess()
+ self.asr.requestMicAccess()
} label: {
Label("Grant Access", systemImage: "mic.fill")
}
.buttonStyle(.borderedProminent)
- .tint(theme.palette.accent)
+ .tint(self.theme.palette.accent)
.controlSize(.regular)
- } else if asr.micStatus == .denied {
+ } else if self.asr.micStatus == .denied {
Button {
- asr.openSystemSettingsForMic()
+ self.asr.openSystemSettingsForMic()
} label: {
Label("Open Settings", systemImage: "gear")
}
@@ -206,43 +204,52 @@ struct SettingsView: View {
.controlSize(.regular)
}
}
-
- if asr.micStatus != .authorized {
- instructionsBox(
+
+ if self.asr.micStatus != .authorized {
+ self.instructionsBox(
title: "How to enable microphone access:",
- steps: asr.micStatus == .notDetermined
- ? ["Click **Grant Access** above", "Choose **Allow** in the system dialog"]
- : ["Click **Open Settings** above", "Find **FluidVoice** in the microphone list", "Toggle **FluidVoice ON** to allow access"]
+ steps: self.asr.micStatus == .notDetermined
+ ? [
+ "Click **Grant Access** above",
+ "Choose **Allow** in the system dialog",
+ ]
+ : [
+ "Click **Open Settings** above",
+ "Find **FluidVoice** in the microphone list",
+ "Toggle **FluidVoice ON** to allow access",
+ ]
)
}
}
}
.padding(16)
}
-
+
// Global Hotkey Card
ThemedCard(style: .standard) {
VStack(alignment: .leading, spacing: 14) {
Label("Global Hotkey", systemImage: "keyboard")
.font(.headline)
.foregroundStyle(.primary)
-
- if accessibilityEnabled {
+
+ if self.accessibilityEnabled {
VStack(alignment: .leading, spacing: 12) {
// Status indicator
HStack(spacing: 8) {
- if isRecordingShortcut || isRecordingCommandModeShortcut || isRecordingRewriteShortcut {
+ if self.isRecordingShortcut || self.isRecordingCommandModeShortcut || self
+ .isRecordingRewriteShortcut
+ {
Image(systemName: "hand.point.up.left.fill")
.foregroundStyle(.orange)
Text("Press your new hotkey combination now...")
.font(.subheadline)
.foregroundStyle(.orange)
- } else if hotkeyManagerInitialized {
+ } else if self.hotkeyManagerInitialized {
Image(systemName: "checkmark.circle.fill")
.foregroundStyle(.green)
Text("Global Shortcuts Active")
.font(.subheadline.weight(.medium))
-
+
Spacer()
} else {
ProgressView()
@@ -259,170 +266,172 @@ struct SettingsView: View {
}
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
- .background(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(.ultraThinMaterial.opacity(0.5))
- .overlay(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .stroke(.white.opacity(0.1), lineWidth: 1)
- )
- )
-
+ .background(RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(.ultraThinMaterial.opacity(0.5))
+ .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .stroke(.white.opacity(0.1), lineWidth: 1)))
+
// MARK: - Shortcuts Section
+
VStack(alignment: .leading, spacing: 8) {
Text("Keyboard Shortcuts")
.font(.subheadline.weight(.medium))
.foregroundStyle(.secondary)
-
- shortcutRow(
+
+ self.shortcutRow(
icon: "mic.fill",
iconColor: .secondary,
title: "Transcribe Mode",
description: "Dictate text anywhere",
- shortcut: hotkeyShortcut,
- isRecording: isRecordingShortcut,
+ shortcut: self.hotkeyShortcut,
+ isRecording: self.isRecordingShortcut,
onChangePressed: {
- DebugLogger.shared.debug("Starting to record new transcribe shortcut", source: "SettingsView")
- isRecordingShortcut = true
+ DebugLogger.shared
+ .debug(
+ "Starting to record new transcribe shortcut",
+ source: "SettingsView"
+ )
+ self.isRecordingShortcut = true
}
)
-
+
Divider()
-
- shortcutRow(
+
+ self.shortcutRow(
icon: "terminal.fill",
iconColor: .secondary,
title: "Command Mode",
description: "Execute voice commands",
- shortcut: commandModeShortcut,
- isRecording: isRecordingCommandModeShortcut,
- isEnabled: $commandModeShortcutEnabled,
+ shortcut: self.commandModeShortcut,
+ isRecording: self.isRecordingCommandModeShortcut,
+ isEnabled: self.$commandModeShortcutEnabled,
onChangePressed: {
- DebugLogger.shared.debug("Starting to record new command mode shortcut", source: "SettingsView")
- isRecordingCommandModeShortcut = true
+ DebugLogger.shared
+ .debug(
+ "Starting to record new command mode shortcut",
+ source: "SettingsView"
+ )
+ self.isRecordingCommandModeShortcut = true
}
)
-
+
Divider()
-
- shortcutRow(
+
+ self.shortcutRow(
icon: "pencil.and.outline",
iconColor: .secondary,
title: "Write Mode",
description: "Select text and speak how to rewrite, or write new content",
- shortcut: rewriteShortcut,
- isRecording: isRecordingRewriteShortcut,
- isEnabled: $rewriteShortcutEnabled,
+ shortcut: self.rewriteShortcut,
+ isRecording: self.isRecordingRewriteShortcut,
+ isEnabled: self.$rewriteShortcutEnabled,
onChangePressed: {
- DebugLogger.shared.debug("Starting to record new write mode shortcut", source: "SettingsView")
- isRecordingRewriteShortcut = true
+ DebugLogger.shared
+ .debug(
+ "Starting to record new write mode shortcut",
+ source: "SettingsView"
+ )
+ self.isRecordingRewriteShortcut = true
}
)
}
.padding(12)
- .background(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(.ultraThinMaterial.opacity(0.5))
- .overlay(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .stroke(.white.opacity(0.08), lineWidth: 1)
- )
- )
-
+ .background(RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(.ultraThinMaterial.opacity(0.5))
+ .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .stroke(.white.opacity(0.08), lineWidth: 1)))
+
// MARK: - Options Section
+
VStack(spacing: 0) {
- optionToggleRow(
+ self.optionToggleRow(
title: "Press and Hold Mode",
description: "The shortcut only records while you hold it down, giving you quick push-to-talk style control.",
- isOn: $pressAndHoldModeEnabled
+ isOn: self.$pressAndHoldModeEnabled
)
- .onChange(of: pressAndHoldModeEnabled) { _, newValue in
+ .onChange(of: self.pressAndHoldModeEnabled) { _, newValue in
SettingsStore.shared.pressAndHoldMode = newValue
- hotkeyManager?.enablePressAndHoldMode(newValue)
+ self.hotkeyManager?.enablePressAndHoldMode(newValue)
}
-
+
Divider().padding(.vertical, 8)
-
- optionToggleRow(
+
+ self.optionToggleRow(
title: "Show Live Preview",
description: "Display transcription text in real-time in the overlay as you speak.",
- isOn: $enableStreamingPreview
+ isOn: self.$enableStreamingPreview
)
- .onChange(of: enableStreamingPreview) { _, newValue in
+ .onChange(of: self.enableStreamingPreview) { _, newValue in
SettingsStore.shared.enableStreamingPreview = newValue
}
-
+
Divider().padding(.vertical, 8)
-
- optionToggleRow(
+
+ self.optionToggleRow(
title: "Copy to Clipboard",
description: "Automatically copy transcribed text to clipboard as a backup.",
- isOn: $copyToClipboard
+ isOn: self.$copyToClipboard
)
- .onChange(of: copyToClipboard) { _, newValue in
+ .onChange(of: self.copyToClipboard) { _, newValue in
SettingsStore.shared.copyTranscriptionToClipboard = newValue
}
}
.padding(12)
- .background(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(.ultraThinMaterial.opacity(0.5))
- .overlay(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .stroke(.white.opacity(0.08), lineWidth: 1)
- )
- )
+ .background(RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(.ultraThinMaterial.opacity(0.5))
+ .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .stroke(.white.opacity(0.08), lineWidth: 1)))
}
} else {
// Hotkey disabled - accessibility not enabled
VStack(alignment: .leading, spacing: 12) {
HStack(spacing: 10) {
Circle()
- .fill(theme.palette.warning)
+ .fill(self.theme.palette.warning)
.frame(width: 8, height: 8)
-
+
VStack(alignment: .leading, spacing: 2) {
HStack(spacing: 6) {
Image(systemName: "exclamationmark.triangle.fill")
- .foregroundStyle(theme.palette.warning)
+ .foregroundStyle(self.theme.palette.warning)
Text("Accessibility permissions required")
.font(.body)
- .foregroundStyle(theme.palette.warning)
+ .foregroundStyle(self.theme.palette.warning)
}
Text("Required for global hotkey functionality")
.font(.subheadline)
.foregroundStyle(.secondary)
}
Spacer()
-
+
Button("Open Accessibility Settings") {
- openAccessibilitySettings()
+ self.openAccessibilitySettings()
}
.buttonStyle(.borderedProminent)
- .tint(theme.palette.accent)
+ .tint(self.theme.palette.accent)
.controlSize(.regular)
}
-
- instructionsBox(
+
+ self.instructionsBox(
title: "Follow these steps to enable Accessibility:",
steps: [
"Click **Open Accessibility Settings** above",
"In the Accessibility window, click the **+ button**",
"Navigate to Applications and select **FluidVoice**",
- "Click **Open**, then toggle **FluidVoice ON** in the list"
+ "Click **Open**, then toggle **FluidVoice ON** in the list",
],
warningStyle: true
)
-
+
HStack(spacing: 10) {
Button("Reveal in Finder") {
- revealAppInFinder()
+ self.revealAppInFinder()
}
.buttonStyle(.bordered)
.controlSize(.small)
-
+
Button("Open Applications") {
- openApplicationsFolder()
+ self.openApplicationsFolder()
}
.buttonStyle(.bordered)
.controlSize(.small)
@@ -432,32 +441,32 @@ struct SettingsView: View {
}
.padding(16)
}
-
+
// Audio Devices Card
ThemedCard(style: .standard) {
VStack(alignment: .leading, spacing: 14) {
Label("Audio Devices", systemImage: "speaker.wave.2.fill")
.font(.headline)
.foregroundStyle(.primary)
-
+
VStack(alignment: .leading, spacing: 12) {
HStack {
Text("Input Device")
.font(.body)
Spacer()
- Picker("Input Device", selection: $selectedInputUID) {
- ForEach(inputDevices, id: \.uid) { dev in
+ Picker("Input Device", selection: self.$selectedInputUID) {
+ ForEach(self.inputDevices, id: \.uid) { dev in
Text(dev.name).tag(dev.uid)
}
}
.pickerStyle(.menu)
.frame(width: 240)
- .onChange(of: selectedInputUID) { _, newUID in
+ .onChange(of: self.selectedInputUID) { _, newUID in
SettingsStore.shared.preferredInputDeviceUID = newUID
_ = AudioDevice.setDefaultInputDevice(uid: newUID)
- if asr.isRunning {
- asr.stopWithoutTranscription()
- startRecording()
+ if self.asr.isRunning {
+ self.asr.stopWithoutTranscription()
+ self.startRecording()
}
}
}
@@ -466,14 +475,14 @@ struct SettingsView: View {
Text("Output Device")
.font(.body)
Spacer()
- Picker("Output Device", selection: $selectedOutputUID) {
- ForEach(outputDevices, id: \.uid) { dev in
+ Picker("Output Device", selection: self.$selectedOutputUID) {
+ ForEach(self.outputDevices, id: \.uid) { dev in
Text(dev.name).tag(dev.uid)
}
}
.pickerStyle(.menu)
.frame(width: 240)
- .onChange(of: selectedOutputUID) { _, newUID in
+ .onChange(of: self.selectedOutputUID) { _, newUID in
SettingsStore.shared.preferredOutputDeviceUID = newUID
_ = AudioDevice.setDefaultOutputDevice(uid: newUID)
}
@@ -481,10 +490,10 @@ struct SettingsView: View {
HStack(spacing: 10) {
Button {
- refreshDevices()
+ self.refreshDevices()
// Update cached default device names on refresh
- cachedDefaultInputName = AudioDevice.getDefaultInputDevice()?.name ?? ""
- cachedDefaultOutputName = AudioDevice.getDefaultOutputDevice()?.name ?? ""
+ self.cachedDefaultInputName = AudioDevice.getDefaultInputDevice()?.name ?? ""
+ self.cachedDefaultOutputName = AudioDevice.getDefaultOutputDevice()?.name ?? ""
} label: {
Label("Refresh", systemImage: "arrow.clockwise")
}
@@ -492,11 +501,11 @@ struct SettingsView: View {
.controlSize(.regular)
Spacer()
-
+
// CRITICAL FIX: Use cached values instead of querying CoreAudio in view body.
// Querying AudioDevice here triggers HALSystem::InitializeShell() race condition.
- if !cachedDefaultInputName.isEmpty && !cachedDefaultOutputName.isEmpty {
- Text("Default: \(cachedDefaultInputName) / \(cachedDefaultOutputName)")
+ if !self.cachedDefaultInputName.isEmpty && !self.cachedDefaultOutputName.isEmpty {
+ Text("Default: \(self.cachedDefaultInputName) / \(self.cachedDefaultOutputName)")
.font(.caption)
.foregroundStyle(.tertiary)
.lineLimit(1)
@@ -506,14 +515,14 @@ struct SettingsView: View {
}
.padding(16)
}
-
+
// Visualization Sensitivity Card
ThemedCard(style: .standard) {
VStack(alignment: .leading, spacing: 14) {
Label("Visualization", systemImage: "waveform")
.font(.headline)
.foregroundStyle(.primary)
-
+
VStack(alignment: .leading, spacing: 12) {
HStack {
VStack(alignment: .leading, spacing: 2) {
@@ -523,32 +532,32 @@ struct SettingsView: View {
.font(.subheadline)
.foregroundStyle(.secondary)
}
-
+
Spacer()
-
+
Button("Reset") {
- visualizerNoiseThreshold = 0.4
- SettingsStore.shared.visualizerNoiseThreshold = visualizerNoiseThreshold
+ self.visualizerNoiseThreshold = 0.4
+ SettingsStore.shared.visualizerNoiseThreshold = self.visualizerNoiseThreshold
}
.buttonStyle(.bordered)
.controlSize(.small)
}
-
+
HStack(spacing: 10) {
Text("More")
.font(.caption)
.foregroundStyle(.secondary)
.frame(width: 36, alignment: .trailing)
-
- Slider(value: $visualizerNoiseThreshold, in: 0.01...0.8, step: 0.01)
+
+ Slider(value: self.$visualizerNoiseThreshold, in: 0.01...0.8, step: 0.01)
.controlSize(.regular)
-
+
Text("Less")
.font(.caption)
.foregroundStyle(.secondary)
.frame(width: 36, alignment: .leading)
-
- Text(String(format: "%.2f", visualizerNoiseThreshold))
+
+ Text(String(format: "%.2f", self.visualizerNoiseThreshold))
.font(.caption.monospaced())
.foregroundStyle(.tertiary)
.frame(width: 36)
@@ -595,20 +604,20 @@ struct SettingsView: View {
await AudioStartupGate.shared.scheduleOpenAfterInitialUISettled()
await AudioStartupGate.shared.waitUntilOpen()
- refreshDevices()
+ self.refreshDevices()
// CRITICAL FIX: Populate cached default device names after onAppear, not during view body evaluation.
// This avoids the CoreAudio/SwiftUI AttributeGraph race condition that causes EXC_BAD_ACCESS.
- cachedDefaultInputName = AudioDevice.getDefaultInputDevice()?.name ?? ""
- cachedDefaultOutputName = AudioDevice.getDefaultOutputDevice()?.name ?? ""
+ self.cachedDefaultInputName = AudioDevice.getDefaultInputDevice()?.name ?? ""
+ self.cachedDefaultOutputName = AudioDevice.getDefaultOutputDevice()?.name ?? ""
}
}
.onChange(of: visualizerNoiseThreshold) { _, newValue in
SettingsStore.shared.visualizerNoiseThreshold = newValue
}
}
-
+
// MARK: - Helper Views
-
+
@ViewBuilder
private func settingsToggleRow(
title: String,
@@ -625,15 +634,15 @@ struct SettingsView: View {
.font(.subheadline)
.foregroundStyle(.secondary)
}
-
+
Spacer()
-
+
Toggle("", isOn: isOn)
.toggleStyle(.switch)
- .tint(theme.palette.accent)
+ .tint(self.theme.palette.accent)
.labelsHidden()
}
-
+
if let footnote = footnote {
Text(footnote)
.font(.caption)
@@ -641,7 +650,7 @@ struct SettingsView: View {
}
}
}
-
+
@ViewBuilder
private func optionToggleRow(
title: String,
@@ -656,16 +665,16 @@ struct SettingsView: View {
.font(.caption)
.foregroundStyle(.secondary)
}
-
+
Spacer()
-
+
Toggle("", isOn: isOn)
.toggleStyle(.switch)
- .tint(theme.palette.accent)
+ .tint(self.theme.palette.accent)
.labelsHidden()
}
}
-
+
@ViewBuilder
private func instructionsBox(
title: String,
@@ -675,19 +684,19 @@ struct SettingsView: View {
VStack(alignment: .leading, spacing: 8) {
HStack(spacing: 6) {
Image(systemName: "info.circle.fill")
- .foregroundStyle(warningStyle ? theme.palette.warning : theme.palette.accent)
+ .foregroundStyle(warningStyle ? self.theme.palette.warning : self.theme.palette.accent)
.font(.caption)
Text(title)
.font(.caption.weight(.medium))
.foregroundStyle(.secondary)
}
-
+
VStack(alignment: .leading, spacing: 4) {
ForEach(Array(steps.enumerated()), id: \.offset) { index, step in
HStack(alignment: .top, spacing: 8) {
Text("\(index + 1).")
.font(.caption)
- .foregroundStyle(warningStyle ? theme.palette.warning : theme.palette.accent)
+ .foregroundStyle(warningStyle ? self.theme.palette.warning : self.theme.palette.accent)
.fontWeight(.semibold)
.frame(width: 16, alignment: .trailing)
Text(.init(step))
@@ -698,12 +707,10 @@ struct SettingsView: View {
}
}
.padding(12)
- .background(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill((warningStyle ? theme.palette.warning : theme.palette.accent).opacity(0.12))
- )
+ .background(RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill((warningStyle ? theme.palette.warning : theme.palette.accent).opacity(0.12)))
}
-
+
@ViewBuilder
private func shortcutRow(
icon: String,
@@ -733,11 +740,11 @@ struct SettingsView: View {
}
Spacer()
-
+
if let isEnabled {
Toggle("", isOn: isEnabled)
.toggleStyle(.switch)
- .tint(theme.palette.accent)
+ .tint(self.theme.palette.accent)
.labelsHidden()
}
}
@@ -752,23 +759,17 @@ struct SettingsView: View {
.foregroundStyle(.orange)
.padding(.horizontal, 8)
.padding(.vertical, 4)
- .background(
- RoundedRectangle(cornerRadius: 5, style: .continuous)
- .fill(.orange.opacity(0.2))
- )
+ .background(RoundedRectangle(cornerRadius: 5, style: .continuous)
+ .fill(.orange.opacity(0.2)))
} else {
Text(shortcut.displayString)
.font(.caption.monospaced().weight(.medium))
.padding(.horizontal, 8)
.padding(.vertical, 4)
- .background(
- RoundedRectangle(cornerRadius: 5, style: .continuous)
- .fill(.quaternary.opacity(0.5))
- .overlay(
- RoundedRectangle(cornerRadius: 5, style: .continuous)
- .stroke(.primary.opacity(0.15), lineWidth: 1)
- )
- )
+ .background(RoundedRectangle(cornerRadius: 5, style: .continuous)
+ .fill(.quaternary.opacity(0.5))
+ .overlay(RoundedRectangle(cornerRadius: 5, style: .continuous)
+ .stroke(.primary.opacity(0.15), lineWidth: 1)))
}
Button("Change") {
@@ -798,12 +799,12 @@ struct FillerWordsEditor: View {
// Word chips
FlowLayout(spacing: 6) {
- ForEach(fillerWords, id: \.self) { word in
+ ForEach(self.fillerWords, id: \.self) { word in
HStack(spacing: 4) {
Text(word)
.font(.caption)
Button {
- removeWord(word)
+ self.removeWord(word)
} label: {
Image(systemName: "xmark")
.font(.caption2)
@@ -812,30 +813,28 @@ struct FillerWordsEditor: View {
}
.padding(.horizontal, 8)
.padding(.vertical, 4)
- .background(
- RoundedRectangle(cornerRadius: 6, style: .continuous)
- .fill(.quaternary)
- )
+ .background(RoundedRectangle(cornerRadius: 6, style: .continuous)
+ .fill(.quaternary))
}
}
// Add new word
HStack(spacing: 8) {
- TextField("Add word", text: $newWord)
+ TextField("Add word", text: self.$newWord)
.textFieldStyle(.roundedBorder)
.frame(width: 100)
- .onSubmit { addWord() }
+ .onSubmit { self.addWord() }
- Button("Add") { addWord() }
+ Button("Add") { self.addWord() }
.buttonStyle(.bordered)
.controlSize(.small)
- .disabled(newWord.trimmingCharacters(in: .whitespaces).isEmpty)
+ .disabled(self.newWord.trimmingCharacters(in: .whitespaces).isEmpty)
Spacer()
Button("Reset") {
- fillerWords = SettingsStore.defaultFillerWords
- SettingsStore.shared.fillerWords = fillerWords
+ self.fillerWords = SettingsStore.defaultFillerWords
+ SettingsStore.shared.fillerWords = self.fillerWords
}
.buttonStyle(.bordered)
.controlSize(.small)
@@ -870,11 +869,17 @@ struct FlowLayout: Layout {
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
let result = 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), proposal: .unspecified)
+ subviews[index].place(
+ at: CGPoint(x: bounds.minX + position.x, y: bounds.minY + position.y),
+ proposal: .unspecified
+ )
}
}
- private func arrangeSubviews(proposal: ProposedViewSize, subviews: Subviews) -> (size: CGSize, positions: [CGPoint]) {
+ private func arrangeSubviews(
+ proposal: ProposedViewSize,
+ subviews: Subviews
+ ) -> (size: CGSize, positions: [CGPoint]) {
let maxWidth = proposal.width ?? .infinity
var positions: [CGPoint] = []
var x: CGFloat = 0
@@ -883,7 +888,7 @@ struct FlowLayout: Layout {
for subview in subviews {
let size = subview.sizeThatFits(.unspecified)
- if x + size.width > maxWidth && x > 0 {
+ if x + size.width > maxWidth, x > 0 {
x = 0
y += rowHeight + spacing
rowHeight = 0
diff --git a/Sources/Fluid/UI/StatsView.swift b/Sources/Fluid/UI/StatsView.swift
index fa9691b2..53ba30fc 100644
--- a/Sources/Fluid/UI/StatsView.swift
+++ b/Sources/Fluid/UI/StatsView.swift
@@ -1,71 +1,64 @@
-//
-// StatsView.swift
-// Fluid
-//
-// Usage statistics dashboard with gamification elements
-//
-
import SwiftUI
struct StatsView: View {
@ObservedObject private var historyStore = TranscriptionHistoryStore.shared
@ObservedObject private var settings = SettingsStore.shared
@Environment(\.theme) private var theme
-
+
@State private var showResetConfirmation: Bool = false
@State private var showWPMEditor: Bool = false
@State private var editingWPM: String = ""
- @State private var chartDays: Int = 7 // Toggle between 7 and 30
-
+ @State private var chartDays: Int = 7 // Toggle between 7 and 30
+
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 16) {
// Header row: Time Saved + Total Words
HStack(spacing: 16) {
- timeSavedCard
- totalWordsCard
+ self.timeSavedCard
+ self.totalWordsCard
}
-
+
// Second row: Streak + Transcriptions
HStack(spacing: 16) {
- streakCard
- transcriptionsCard
+ self.streakCard
+ self.transcriptionsCard
}
-
+
// Activity Chart
- activityChartCard
-
+ self.activityChartCard
+
// Milestones
- milestonesCard
-
+ self.milestonesCard
+
// Insights
- insightsCard
-
+ self.insightsCard
+
// Personal Records
- recordsCard
-
+ self.recordsCard
+
// Reset Button
- resetSection
+ self.resetSection
}
.padding(20)
}
}
-
+
// MARK: - Time Saved Card
-
+
private var timeSavedCard: some View {
StatCard(title: "TIME SAVED", icon: "clock.fill") {
VStack(alignment: .leading, spacing: 8) {
- Text(historyStore.formattedTimeSaved(typingWPM: settings.userTypingWPM))
+ Text(self.historyStore.formattedTimeSaved(typingWPM: self.settings.userTypingWPM))
.font(.system(size: 32, weight: .bold, design: .rounded))
.foregroundStyle(.primary)
-
+
Button {
- editingWPM = "\(settings.userTypingWPM)"
- showWPMEditor = true
+ self.editingWPM = "\(self.settings.userTypingWPM)"
+ self.showWPMEditor = true
} label: {
HStack(spacing: 4) {
- Text("Based on \(settings.userTypingWPM) WPM typing")
+ Text("Based on \(self.settings.userTypingWPM) WPM typing")
.font(.system(size: 11))
Image(systemName: "pencil")
.font(.system(size: 9))
@@ -76,41 +69,41 @@ struct StatsView: View {
}
}
.popover(isPresented: $showWPMEditor) {
- wpmEditorPopover
+ self.wpmEditorPopover
}
}
-
+
private var wpmEditorPopover: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Your Typing Speed")
.font(.system(size: 13, weight: .semibold))
-
+
HStack {
- TextField("WPM", text: $editingWPM)
+ TextField("WPM", text: self.$editingWPM)
.textFieldStyle(.roundedBorder)
.frame(width: 60)
.multilineTextAlignment(.center)
-
+
Text("words per minute")
.font(.system(size: 12))
.foregroundStyle(.secondary)
}
-
+
Text("Average typing: 40 WPM\nProfessional: 65-75 WPM")
.font(.system(size: 10))
.foregroundStyle(.tertiary)
-
+
HStack {
Button("Cancel") {
- showWPMEditor = false
+ self.showWPMEditor = false
}
.buttonStyle(.bordered)
-
+
Button("Save") {
if let wpm = Int(editingWPM), wpm > 0 {
- settings.userTypingWPM = wpm
+ self.settings.userTypingWPM = wpm
}
- showWPMEditor = false
+ self.showWPMEditor = false
}
.buttonStyle(.borderedProminent)
}
@@ -118,21 +111,21 @@ struct StatsView: View {
.padding(16)
.frame(width: 220)
}
-
+
// MARK: - Total Words Card
-
+
private var totalWordsCard: some View {
StatCard(title: "TOTAL WORDS", icon: "text.word.spacing") {
VStack(alignment: .leading, spacing: 8) {
- Text(formatNumber(historyStore.totalWords))
+ Text(self.formatNumber(self.historyStore.totalWords))
.font(.system(size: 32, weight: .bold, design: .rounded))
.foregroundStyle(.primary)
-
- let today = historyStore.wordsToday
+
+ let today = self.historyStore.wordsToday
if today > 0 {
- Text("+\(formatNumber(today)) today")
+ Text("+\(self.formatNumber(today)) today")
.font(.system(size: 11))
- .foregroundStyle(theme.palette.success)
+ .foregroundStyle(self.theme.palette.success)
} else {
Text("Start dictating")
.font(.system(size: 11))
@@ -141,67 +134,67 @@ struct StatsView: View {
}
}
}
-
+
// MARK: - Streak Card
-
+
private var streakCard: some View {
StatCard(title: "CURRENT STREAK", icon: "flame.fill") {
VStack(alignment: .leading, spacing: 8) {
HStack(alignment: .firstTextBaseline, spacing: 4) {
- Text("\(historyStore.currentStreak)")
+ Text("\(self.historyStore.currentStreak)")
.font(.system(size: 32, weight: .bold, design: .rounded))
- .foregroundStyle(historyStore.currentStreak > 0 ? theme.palette.warning : .primary)
-
- Text(historyStore.currentStreak == 1 ? "day" : "days")
+ .foregroundStyle(self.historyStore.currentStreak > 0 ? self.theme.palette.warning : .primary)
+
+ Text(self.historyStore.currentStreak == 1 ? "day" : "days")
.font(.system(size: 14, weight: .medium))
.foregroundStyle(.secondary)
}
-
- Text("Best: \(historyStore.bestStreak) days")
+
+ Text("Best: \(self.historyStore.bestStreak) days")
.font(.system(size: 11))
.foregroundStyle(.secondary)
}
}
}
-
+
// MARK: - Transcriptions Card
-
+
private var transcriptionsCard: some View {
StatCard(title: "TRANSCRIPTIONS", icon: "doc.text.fill") {
VStack(alignment: .leading, spacing: 8) {
- Text("\(historyStore.entries.count)")
+ Text("\(self.historyStore.entries.count)")
.font(.system(size: 32, weight: .bold, design: .rounded))
.foregroundStyle(.primary)
-
- Text("Avg: \(historyStore.averageWordsPerTranscription) words each")
+
+ Text("Avg: \(self.historyStore.averageWordsPerTranscription) words each")
.font(.system(size: 11))
.foregroundStyle(.secondary)
}
}
}
-
+
// MARK: - Activity Chart Card
-
+
private var activityChartCard: some View {
VStack(alignment: .leading, spacing: 12) {
HStack {
Label("ACTIVITY", systemImage: "chart.bar.fill")
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(.secondary)
-
+
Spacer()
-
- Picker("", selection: $chartDays) {
+
+ Picker("", selection: self.$chartDays) {
Text("7 days").tag(7)
Text("30 days").tag(30)
}
.pickerStyle(.segmented)
.frame(width: 140)
}
-
- let data = historyStore.dailyWordCounts(days: chartDays)
+
+ let data = self.historyStore.dailyWordCounts(days: self.chartDays)
let maxWords = data.map { $0.words }.max() ?? 0
-
+
if maxWords == 0 {
// Empty state
HStack {
@@ -219,18 +212,19 @@ struct StatsView: View {
}
} else {
// Bar chart
- HStack(alignment: .bottom, spacing: chartDays == 7 ? 8 : 2) {
- ForEach(Array(data.enumerated()), id: \.offset) { index, item in
+ HStack(alignment: .bottom, spacing: self.chartDays == 7 ? 8 : 2) {
+ ForEach(Array(data.enumerated()), id: \.offset) { _, item in
VStack(spacing: 4) {
// Bar (avoid division by zero)
- let height = (item.words > 0 && maxWords > 0) ? CGFloat(item.words) / CGFloat(maxWords) * 80 : 2
+ let height = (item.words > 0 && maxWords > 0) ? CGFloat(item.words) / CGFloat(maxWords) *
+ 80 : 2
RoundedRectangle(cornerRadius: 3)
- .fill(item.words > 0 ? theme.palette.accent : Color.secondary.opacity(0.2))
- .frame(width: chartDays == 7 ? 30 : 8, height: max(2, height))
-
+ .fill(item.words > 0 ? self.theme.palette.accent : Color.secondary.opacity(0.2))
+ .frame(width: self.chartDays == 7 ? 30 : 8, height: max(2, height))
+
// Label (only for 7-day view)
- if chartDays == 7 {
- Text(dayLabel(item.date))
+ if self.chartDays == 7 {
+ Text(self.dayLabel(item.date))
.font(.system(size: 9, weight: .medium))
.foregroundStyle(.secondary)
}
@@ -239,286 +233,264 @@ struct StatsView: View {
}
.frame(height: 110)
.frame(maxWidth: .infinity)
-
+
// Summary
HStack {
let totalPeriod = data.reduce(0) { $0 + $1.words }
let activeDays = data.filter { $0.words > 0 }.count
-
- Text("\(formatNumber(totalPeriod)) words")
+
+ Text("\(self.formatNumber(totalPeriod)) words")
.font(.system(size: 11, weight: .medium))
.foregroundStyle(.primary)
-
+
Text("across \(activeDays) active days")
.font(.system(size: 11))
.foregroundStyle(.secondary)
-
+
Spacer()
}
}
}
.padding(16)
- .background(
- RoundedRectangle(cornerRadius: 12)
- .fill(.ultraThinMaterial)
- .overlay(
- RoundedRectangle(cornerRadius: 12)
- .stroke(.white.opacity(0.08), lineWidth: 1)
- )
- )
+ .background(RoundedRectangle(cornerRadius: 12)
+ .fill(.ultraThinMaterial)
+ .overlay(RoundedRectangle(cornerRadius: 12)
+ .stroke(.white.opacity(0.08), lineWidth: 1)))
}
-
+
// MARK: - Milestones Card
-
+
private var milestonesCard: some View {
VStack(alignment: .leading, spacing: 12) {
HStack {
Label("MILESTONES", systemImage: "flag.fill")
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(.secondary)
-
+
Spacer()
-
- Text("\(historyStore.totalMilestonesAchieved)/\(historyStore.totalMilestonesPossible)")
+
+ Text("\(self.historyStore.totalMilestonesAchieved)/\(self.historyStore.totalMilestonesPossible)")
.font(.system(size: 11, weight: .medium))
- .foregroundStyle(theme.palette.accent)
+ .foregroundStyle(self.theme.palette.accent)
}
-
+
VStack(alignment: .leading, spacing: 10) {
// Word milestones
- milestoneRow(
+ self.milestoneRow(
title: "Words",
- milestones: historyStore.wordMilestones
+ milestones: self.historyStore.wordMilestones
)
-
+
// Transcription milestones
- milestoneRow(
+ self.milestoneRow(
title: "Transcriptions",
- milestones: historyStore.transcriptionMilestones
+ milestones: self.historyStore.transcriptionMilestones
)
-
+
// Streak milestones
- milestoneRow(
+ self.milestoneRow(
title: "Streak",
- milestones: historyStore.streakMilestones
+ milestones: self.historyStore.streakMilestones
)
}
}
.padding(16)
- .background(
- RoundedRectangle(cornerRadius: 12)
- .fill(.ultraThinMaterial)
- .overlay(
- RoundedRectangle(cornerRadius: 12)
- .stroke(.white.opacity(0.08), lineWidth: 1)
- )
- )
+ .background(RoundedRectangle(cornerRadius: 12)
+ .fill(.ultraThinMaterial)
+ .overlay(RoundedRectangle(cornerRadius: 12)
+ .stroke(.white.opacity(0.08), lineWidth: 1)))
}
-
+
private func milestoneRow(title: String, milestones: [(target: Int, achieved: Bool, label: String)]) -> some View {
HStack(spacing: 8) {
Text(title)
.font(.system(size: 10, weight: .medium))
.foregroundStyle(.secondary)
.frame(width: 80, alignment: .leading)
-
+
ForEach(Array(milestones.enumerated()), id: \.offset) { _, milestone in
HStack(spacing: 3) {
Image(systemName: milestone.achieved ? "checkmark.circle.fill" : "circle")
.font(.system(size: 10))
- .foregroundStyle(milestone.achieved ? theme.palette.success : Color.secondary.opacity(0.4))
-
+ .foregroundStyle(milestone.achieved ? self.theme.palette.success : Color.secondary.opacity(0.4))
+
Text(milestone.label)
.font(.system(size: 10, weight: milestone.achieved ? .semibold : .regular))
.foregroundStyle(milestone.achieved ? .primary : .secondary)
}
.padding(.horizontal, 6)
.padding(.vertical, 3)
- .background(
- RoundedRectangle(cornerRadius: 4)
- .fill(milestone.achieved ? theme.palette.success.opacity(0.1) : Color.clear)
- )
+ .background(RoundedRectangle(cornerRadius: 4)
+ .fill(milestone.achieved ? self.theme.palette.success.opacity(0.1) : Color.clear))
}
-
+
Spacer()
}
}
-
+
// MARK: - Insights Card
-
+
private var insightsCard: some View {
VStack(alignment: .leading, spacing: 12) {
Label("INSIGHTS", systemImage: "lightbulb.fill")
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(.secondary)
-
+
LazyVGrid(columns: [
GridItem(.flexible(), spacing: 12),
- GridItem(.flexible(), spacing: 12)
+ GridItem(.flexible(), spacing: 12),
], spacing: 12) {
// Top Apps
- insightItem(
+ self.insightItem(
icon: "app.fill",
title: "Top Apps",
- value: historyStore.topAppsFormatted(limit: 3).joined(separator: ", "),
+ value: self.historyStore.topAppsFormatted(limit: 3).joined(separator: ", "),
fallback: "No data yet"
)
-
+
// AI Enhancement Rate
- insightItem(
+ self.insightItem(
icon: "sparkles",
title: "AI Enhanced",
- value: "\(historyStore.aiEnhancementRate)%",
+ value: "\(self.historyStore.aiEnhancementRate)%",
fallback: "0%"
)
-
+
// Peak Hours
- insightItem(
+ self.insightItem(
icon: "clock.fill",
title: "Peak Time",
- value: historyStore.peakHourFormatted,
+ value: self.historyStore.peakHourFormatted,
fallback: "N/A"
)
-
+
// Avg Length
- insightItem(
+ self.insightItem(
icon: "ruler.fill",
title: "Avg Length",
- value: "\(historyStore.averageWordsPerTranscription) words",
+ value: "\(self.historyStore.averageWordsPerTranscription) words",
fallback: "0 words"
)
}
}
.padding(16)
- .background(
- RoundedRectangle(cornerRadius: 12)
- .fill(.ultraThinMaterial)
- .overlay(
- RoundedRectangle(cornerRadius: 12)
- .stroke(.white.opacity(0.08), lineWidth: 1)
- )
- )
+ .background(RoundedRectangle(cornerRadius: 12)
+ .fill(.ultraThinMaterial)
+ .overlay(RoundedRectangle(cornerRadius: 12)
+ .stroke(.white.opacity(0.08), lineWidth: 1)))
}
-
+
private func insightItem(icon: String, title: String, value: String, fallback: String) -> some View {
HStack(spacing: 10) {
Image(systemName: icon)
.font(.system(size: 12))
.foregroundStyle(.tertiary)
.frame(width: 20)
-
+
VStack(alignment: .leading, spacing: 2) {
Text(title)
.font(.system(size: 10, weight: .medium))
.foregroundStyle(.secondary)
-
+
Text(value.isEmpty ? fallback : value)
.font(.system(size: 12, weight: .medium))
.foregroundStyle(.primary)
.lineLimit(1)
}
-
+
Spacer()
}
.padding(10)
- .background(
- RoundedRectangle(cornerRadius: 8)
- .fill(.quaternary.opacity(0.3))
- )
+ .background(RoundedRectangle(cornerRadius: 8)
+ .fill(.quaternary.opacity(0.3)))
}
-
+
// MARK: - Personal Records Card
-
+
private var recordsCard: some View {
VStack(alignment: .leading, spacing: 12) {
Label("PERSONAL RECORDS", systemImage: "trophy.fill")
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(.secondary)
-
+
HStack(spacing: 12) {
- recordItem(
+ self.recordItem(
title: "Longest Transcription",
- value: "\(historyStore.longestTranscriptionWords) words"
+ value: "\(self.historyStore.longestTranscriptionWords) words"
)
-
- recordItem(
+
+ self.recordItem(
title: "Most Words in a Day",
- value: "\(formatNumber(historyStore.mostWordsInDay)) words"
+ value: "\(self.formatNumber(self.historyStore.mostWordsInDay)) words"
)
-
- recordItem(
+
+ self.recordItem(
title: "Most in a Day",
- value: "\(historyStore.mostTranscriptionsInDay) transcriptions"
+ value: "\(self.historyStore.mostTranscriptionsInDay) transcriptions"
)
}
}
.padding(16)
- .background(
- RoundedRectangle(cornerRadius: 12)
- .fill(.ultraThinMaterial)
- .overlay(
- RoundedRectangle(cornerRadius: 12)
- .stroke(.white.opacity(0.08), lineWidth: 1)
- )
- )
+ .background(RoundedRectangle(cornerRadius: 12)
+ .fill(.ultraThinMaterial)
+ .overlay(RoundedRectangle(cornerRadius: 12)
+ .stroke(.white.opacity(0.08), lineWidth: 1)))
}
-
+
private func recordItem(title: String, value: String) -> some View {
VStack(alignment: .leading, spacing: 4) {
Text(title)
.font(.system(size: 10, weight: .medium))
.foregroundStyle(.secondary)
-
+
Text(value)
.font(.system(size: 14, weight: .semibold, design: .rounded))
.foregroundStyle(.primary)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(10)
- .background(
- RoundedRectangle(cornerRadius: 8)
- .fill(theme.palette.accent.opacity(0.08))
- )
+ .background(RoundedRectangle(cornerRadius: 8)
+ .fill(theme.palette.accent.opacity(0.08)))
}
-
+
// MARK: - Reset Section
-
+
private var resetSection: some View {
HStack {
Spacer()
-
+
Button {
- showResetConfirmation = true
+ self.showResetConfirmation = true
} label: {
Label("Reset All Stats", systemImage: "trash")
.font(.system(size: 12, weight: .medium))
.foregroundStyle(.secondary)
}
.buttonStyle(.plain)
- .opacity(historyStore.entries.isEmpty ? 0.3 : 0.7)
- .disabled(historyStore.entries.isEmpty)
-
+ .opacity(self.historyStore.entries.isEmpty ? 0.3 : 0.7)
+ .disabled(self.historyStore.entries.isEmpty)
+
Spacer()
}
.padding(.top, 8)
.alert("Reset All Stats", isPresented: $showResetConfirmation) {
- Button("Cancel", role: .cancel) { }
+ Button("Cancel", role: .cancel) {}
Button("Reset Everything", role: .destructive) {
- historyStore.clearAllHistory()
+ self.historyStore.clearAllHistory()
}
} message: {
- Text("This will permanently delete all \(historyStore.entries.count) transcriptions and reset all statistics. This action cannot be undone.")
+ Text("This will permanently delete all \(self.historyStore.entries.count) transcriptions and reset all statistics. This action cannot be undone.")
}
}
-
+
// MARK: - Helpers
-
+
private func formatNumber(_ number: Int) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter.string(from: NSNumber(value: number)) ?? "\(number)"
}
-
+
private func dayLabel(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "EEE"
@@ -532,25 +504,21 @@ private struct StatCard<Content: View>: View {
let title: String
let icon: String
@ViewBuilder let content: Content
-
+
var body: some View {
VStack(alignment: .leading, spacing: 10) {
- Label(title, systemImage: icon)
+ Label(self.title, systemImage: self.icon)
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(.secondary)
-
- content
+
+ self.content
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(16)
- .background(
- RoundedRectangle(cornerRadius: 12)
- .fill(.ultraThinMaterial)
- .overlay(
- RoundedRectangle(cornerRadius: 12)
- .stroke(.white.opacity(0.08), lineWidth: 1)
- )
- )
+ .background(RoundedRectangle(cornerRadius: 12)
+ .fill(.ultraThinMaterial)
+ .overlay(RoundedRectangle(cornerRadius: 12)
+ .stroke(.white.opacity(0.08), lineWidth: 1)))
}
}
@@ -559,4 +527,3 @@ private struct StatCard<Content: View>: View {
.frame(width: 600, height: 800)
.environment(\.theme, AppTheme.dark)
}
-
diff --git a/Sources/Fluid/UI/TranscriptionHistoryView.swift b/Sources/Fluid/UI/TranscriptionHistoryView.swift
index b0466ba0..a51f060e 100644
--- a/Sources/Fluid/UI/TranscriptionHistoryView.swift
+++ b/Sources/Fluid/UI/TranscriptionHistoryView.swift
@@ -1,94 +1,90 @@
-//
-// TranscriptionHistoryView.swift
-// Fluid
-//
-// Transcription history browser with search and detail view
-//
-
import SwiftUI
struct TranscriptionHistoryView: View {
@ObservedObject private var historyStore = TranscriptionHistoryStore.shared
@Environment(\.theme) private var theme
-
+
@State private var searchQuery: String = ""
@State private var showClearConfirmation: Bool = false
@State private var selectedEntryID: UUID?
-
+
private var filteredEntries: [TranscriptionHistoryEntry] {
historyStore.search(query: searchQuery)
}
-
+
private var selectedEntry: TranscriptionHistoryEntry? {
guard let id = selectedEntryID else { return filteredEntries.first }
return filteredEntries.first(where: { $0.id == id })
}
-
+
var body: some View {
HSplitView {
// MARK: - Left Panel: Entry List
+
VStack(spacing: 0) {
// Search Bar
- searchBar
+ self.searchBar
.padding(12)
-
+
Divider()
.opacity(0.3)
-
+
// Entry List
- if filteredEntries.isEmpty {
- emptyStateView
+ if self.filteredEntries.isEmpty {
+ self.emptyStateView
} else {
- entryListView
+ self.entryListView
}
-
+
// Footer with stats and clear button
- footerView
+ self.footerView
}
.frame(minWidth: 280, idealWidth: 320, maxWidth: 400)
- .background(theme.palette.cardBackground.opacity(0.3))
-
+ .background(self.theme.palette.cardBackground.opacity(0.3))
+
// MARK: - Right Panel: Entry Detail
+
if let entry = selectedEntry {
- entryDetailView(entry)
+ self.entryDetailView(entry)
.frame(minWidth: 400)
} else {
- noSelectionView
+ self.noSelectionView
.frame(minWidth: 400)
}
}
.onAppear {
- if selectedEntryID == nil {
- selectedEntryID = filteredEntries.first?.id
+ if self.selectedEntryID == nil {
+ self.selectedEntryID = self.filteredEntries.first?.id
}
}
.alert("Clear All History", isPresented: $showClearConfirmation) {
- Button("Cancel", role: .cancel) { }
+ Button("Cancel", role: .cancel) {}
Button("Clear All", role: .destructive) {
withAnimation(.easeInOut(duration: 0.2)) {
- historyStore.clearAllHistory()
- selectedEntryID = nil
+ self.historyStore.clearAllHistory()
+ self.selectedEntryID = nil
}
}
} message: {
- Text("This will permanently delete all \(historyStore.entries.count) transcription entries. This action cannot be undone.")
+ Text("This will permanently delete all \(self.historyStore.entries.count) transcription entries. This action cannot be undone.")
}
}
-
+
// MARK: - Search Bar
+
private var searchBar: some View {
HStack(spacing: 8) {
Image(systemName: "magnifyingglass")
.font(.system(size: 13, weight: .medium))
.foregroundStyle(.secondary)
-
- TextField("Search transcriptions...", text: $searchQuery)
+
+ TextField("Search transcriptions...", text: self.$searchQuery)
.textFieldStyle(.plain)
.font(.system(size: 13))
-
- if !searchQuery.isEmpty {
+
+ if !self.searchQuery.isEmpty {
Button {
- searchQuery = ""
+ self.searchQuery = ""
} label: {
Image(systemName: "xmark.circle.fill")
.font(.system(size: 12))
@@ -99,35 +95,32 @@ struct TranscriptionHistoryView: View {
}
.padding(.horizontal, 10)
.padding(.vertical, 8)
- .background(
- RoundedRectangle(cornerRadius: 8)
- .fill(.ultraThinMaterial)
- .overlay(
- RoundedRectangle(cornerRadius: 8)
- .stroke(.white.opacity(0.08), lineWidth: 1)
- )
- )
+ .background(RoundedRectangle(cornerRadius: 8)
+ .fill(.ultraThinMaterial)
+ .overlay(RoundedRectangle(cornerRadius: 8)
+ .stroke(.white.opacity(0.08), lineWidth: 1)))
}
-
+
// MARK: - Entry List
+
private var entryListView: some View {
ScrollView {
LazyVStack(spacing: 2) {
- ForEach(filteredEntries) { entry in
- entryRow(entry)
+ ForEach(self.filteredEntries) { entry in
+ self.entryRow(entry)
}
}
.padding(.horizontal, 8)
.padding(.vertical, 6)
}
}
-
+
private func entryRow(_ entry: TranscriptionHistoryEntry) -> some View {
let isSelected = selectedEntryID == entry.id
-
+
return Button {
withAnimation(.easeInOut(duration: 0.15)) {
- selectedEntryID = entry.id
+ self.selectedEntryID = entry.id
}
} label: {
VStack(alignment: .leading, spacing: 4) {
@@ -137,26 +130,24 @@ struct TranscriptionHistoryView: View {
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(isSelected ? .white : .secondary)
.lineLimit(1)
-
+
if entry.wasAIProcessed {
Text("AI")
.font(.system(size: 9, weight: .bold))
- .foregroundStyle(isSelected ? .white.opacity(0.8) : theme.palette.accent)
+ .foregroundStyle(isSelected ? .white.opacity(0.8) : self.theme.palette.accent)
.padding(.horizontal, 4)
.padding(.vertical, 1)
- .background(
- RoundedRectangle(cornerRadius: 3)
- .fill(isSelected ? .white.opacity(0.2) : theme.palette.accent.opacity(0.15))
- )
+ .background(RoundedRectangle(cornerRadius: 3)
+ .fill(isSelected ? .white.opacity(0.2) : self.theme.palette.accent.opacity(0.15)))
}
-
+
Spacer()
-
+
Text(entry.relativeTimeString)
.font(.system(size: 10, weight: .medium))
.foregroundStyle(isSelected ? .white.opacity(0.7) : Color.secondary.opacity(0.6))
}
-
+
// Preview text
Text(entry.previewText)
.font(.system(size: 12))
@@ -167,10 +158,8 @@ struct TranscriptionHistoryView: View {
.padding(.horizontal, 10)
.padding(.vertical, 8)
.frame(maxWidth: .infinity, alignment: .leading)
- .background(
- RoundedRectangle(cornerRadius: 8)
- .fill(isSelected ? theme.palette.accent : Color.clear)
- )
+ .background(RoundedRectangle(cornerRadius: 8)
+ .fill(isSelected ? self.theme.palette.accent : Color.clear))
.contentShape(Rectangle())
}
.buttonStyle(.plain)
@@ -181,7 +170,7 @@ struct TranscriptionHistoryView: View {
} label: {
Label("Copy Text", systemImage: "doc.on.doc")
}
-
+
if entry.wasAIProcessed {
Button {
NSPasteboard.general.clearContents()
@@ -190,14 +179,14 @@ struct TranscriptionHistoryView: View {
Label("Copy Raw Text", systemImage: "doc.on.doc.fill")
}
}
-
+
Divider()
-
+
Button(role: .destructive) {
withAnimation(.easeInOut(duration: 0.2)) {
- historyStore.deleteEntry(id: entry.id)
- if selectedEntryID == entry.id {
- selectedEntryID = filteredEntries.first(where: { $0.id != entry.id })?.id
+ self.historyStore.deleteEntry(id: entry.id)
+ if self.selectedEntryID == entry.id {
+ self.selectedEntryID = self.filteredEntries.first(where: { $0.id != entry.id })?.id
}
}
} label: {
@@ -205,53 +194,55 @@ struct TranscriptionHistoryView: View {
}
}
}
-
+
// MARK: - Empty State
+
private var emptyStateView: some View {
VStack(spacing: 16) {
Spacer()
-
- Image(systemName: searchQuery.isEmpty ? "clock.arrow.circlepath" : "magnifyingglass")
+
+ Image(systemName: self.searchQuery.isEmpty ? "clock.arrow.circlepath" : "magnifyingglass")
.font(.system(size: 36, weight: .light))
.foregroundStyle(.tertiary)
-
+
VStack(spacing: 4) {
- Text(searchQuery.isEmpty ? "No History Yet" : "No Results")
+ Text(self.searchQuery.isEmpty ? "No History Yet" : "No Results")
.font(.system(size: 14, weight: .semibold))
.foregroundStyle(.secondary)
-
- Text(searchQuery.isEmpty
- ? "Your transcriptions will appear here"
- : "Try a different search term")
+
+ Text(self.searchQuery.isEmpty
+ ? "Your transcriptions will appear here"
+ : "Try a different search term")
.font(.system(size: 12))
.foregroundStyle(.tertiary)
.multilineTextAlignment(.center)
}
-
+
Spacer()
}
.frame(maxWidth: .infinity)
.padding()
}
-
+
// MARK: - Footer
+
private var footerView: some View {
VStack(spacing: 0) {
Divider()
.opacity(0.3)
-
+
HStack {
// Stats
- Text("\(historyStore.entries.count) entries")
+ Text("\(self.historyStore.entries.count) entries")
.font(.system(size: 11, weight: .medium))
.foregroundStyle(.tertiary)
-
+
Spacer()
-
+
// Clear All Button
- if !historyStore.entries.isEmpty {
+ if !self.historyStore.entries.isEmpty {
Button {
- showClearConfirmation = true
+ self.showClearConfirmation = true
} label: {
Text("Clear All")
.font(.system(size: 11, weight: .medium))
@@ -265,8 +256,9 @@ struct TranscriptionHistoryView: View {
.padding(.vertical, 10)
}
}
-
+
// MARK: - Entry Detail View
+
private func entryDetailView(_ entry: TranscriptionHistoryEntry) -> some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
@@ -275,9 +267,9 @@ struct TranscriptionHistoryView: View {
HStack {
Text("Transcription Details")
.font(.system(size: 18, weight: .semibold))
-
+
Spacer()
-
+
// Copy button
Button {
NSPasteboard.general.clearContents()
@@ -289,48 +281,48 @@ struct TranscriptionHistoryView: View {
.buttonStyle(.bordered)
.controlSize(.small)
}
-
+
Text(entry.fullDateString)
.font(.system(size: 13))
.foregroundStyle(.secondary)
}
-
+
Divider()
.opacity(0.3)
-
+
// Final Text Section
- detailSection(
+ self.detailSection(
title: "Final Text",
content: entry.processedText,
badge: entry.wasAIProcessed ? "AI Enhanced" : nil
)
-
+
// Raw Text Section (only if different)
if entry.wasAIProcessed {
- detailSection(
+ self.detailSection(
title: "Original Transcription",
content: entry.rawText,
badge: nil,
isSecondary: true
)
}
-
+
Divider()
.opacity(0.3)
-
+
// Metadata Grid
- metadataGrid(entry)
-
+ self.metadataGrid(entry)
+
Spacer(minLength: 20)
-
+
// Delete Button
HStack {
Spacer()
Button(role: .destructive) {
withAnimation(.easeInOut(duration: 0.2)) {
- let nextEntry = filteredEntries.first(where: { $0.id != entry.id })
- historyStore.deleteEntry(id: entry.id)
- selectedEntryID = nextEntry?.id
+ let nextEntry = self.filteredEntries.first(where: { $0.id != entry.id })
+ self.historyStore.deleteEntry(id: entry.id)
+ self.selectedEntryID = nextEntry?.id
}
} label: {
Label("Delete Entry", systemImage: "trash")
@@ -345,7 +337,7 @@ struct TranscriptionHistoryView: View {
}
.background(theme.palette.cardBackground.opacity(0.15))
}
-
+
private func detailSection(
title: String,
content: String,
@@ -359,37 +351,31 @@ struct TranscriptionHistoryView: View {
.foregroundStyle(.secondary)
.textCase(.uppercase)
.tracking(0.5)
-
+
if let badge = badge {
Text(badge)
.font(.system(size: 9, weight: .bold))
- .foregroundStyle(theme.palette.accent)
+ .foregroundStyle(self.theme.palette.accent)
.padding(.horizontal, 6)
.padding(.vertical, 2)
- .background(
- RoundedRectangle(cornerRadius: 4)
- .fill(theme.palette.accent.opacity(0.15))
- )
+ .background(RoundedRectangle(cornerRadius: 4)
+ .fill(self.theme.palette.accent.opacity(0.15)))
}
}
-
+
Text(content)
.font(.system(size: 14, design: .default))
.foregroundStyle(isSecondary ? .secondary : .primary)
.textSelection(.enabled)
.padding(14)
.frame(maxWidth: .infinity, alignment: .leading)
- .background(
- RoundedRectangle(cornerRadius: 10)
- .fill(.ultraThinMaterial)
- .overlay(
- RoundedRectangle(cornerRadius: 10)
- .stroke(.white.opacity(isSecondary ? 0.04 : 0.08), lineWidth: 1)
- )
- )
+ .background(RoundedRectangle(cornerRadius: 10)
+ .fill(.ultraThinMaterial)
+ .overlay(RoundedRectangle(cornerRadius: 10)
+ .stroke(.white.opacity(isSecondary ? 0.04 : 0.08), lineWidth: 1)))
}
}
-
+
private func metadataGrid(_ entry: TranscriptionHistoryEntry) -> some View {
VStack(alignment: .leading, spacing: 12) {
Text("Details")
@@ -397,53 +383,60 @@ struct TranscriptionHistoryView: View {
.foregroundStyle(.secondary)
.textCase(.uppercase)
.tracking(0.5)
-
+
LazyVGrid(columns: [
GridItem(.flexible(), spacing: 16),
- GridItem(.flexible(), spacing: 16)
+ GridItem(.flexible(), spacing: 16),
], spacing: 12) {
- metadataItem(icon: "app.fill", label: "Application", value: entry.appName.isEmpty ? "Unknown" : entry.appName)
- metadataItem(icon: "macwindow", label: "Window", value: entry.windowTitle.isEmpty ? "Unknown" : entry.windowTitle)
- metadataItem(icon: "character.cursor.ibeam", label: "Characters", value: "\(entry.characterCount)")
- metadataItem(icon: "sparkles", label: "AI Processed", value: entry.wasAIProcessed ? "Yes" : "No")
+ self.metadataItem(
+ icon: "app.fill",
+ label: "Application",
+ value: entry.appName.isEmpty ? "Unknown" : entry.appName
+ )
+ self.metadataItem(
+ icon: "macwindow",
+ label: "Window",
+ value: entry.windowTitle.isEmpty ? "Unknown" : entry.windowTitle
+ )
+ self.metadataItem(icon: "character.cursor.ibeam", label: "Characters", value: "\(entry.characterCount)")
+ self.metadataItem(icon: "sparkles", label: "AI Processed", value: entry.wasAIProcessed ? "Yes" : "No")
}
}
}
-
+
private func metadataItem(icon: String, label: String, value: String) -> some View {
HStack(spacing: 10) {
Image(systemName: icon)
.font(.system(size: 12, weight: .medium))
.foregroundStyle(.tertiary)
.frame(width: 20)
-
+
VStack(alignment: .leading, spacing: 2) {
Text(label)
.font(.system(size: 10, weight: .medium))
.foregroundStyle(.tertiary)
-
+
Text(value)
.font(.system(size: 12, weight: .medium))
.foregroundStyle(.primary)
.lineLimit(1)
}
-
+
Spacer()
}
.padding(10)
- .background(
- RoundedRectangle(cornerRadius: 8)
- .fill(.ultraThinMaterial.opacity(0.5))
- )
+ .background(RoundedRectangle(cornerRadius: 8)
+ .fill(.ultraThinMaterial.opacity(0.5)))
}
-
+
// MARK: - No Selection View
+
private var noSelectionView: some View {
VStack(spacing: 16) {
Image(systemName: "text.quote")
.font(.system(size: 40, weight: .light))
.foregroundStyle(.tertiary)
-
+
Text("Select a transcription")
.font(.system(size: 14, weight: .medium))
.foregroundStyle(.secondary)
@@ -458,4 +451,3 @@ struct TranscriptionHistoryView: View {
.frame(width: 800, height: 600)
.environment(\.theme, AppTheme.dark)
}
-
diff --git a/Sources/Fluid/UI/Visualization/AudioVisualizationShared.swift b/Sources/Fluid/UI/Visualization/AudioVisualizationShared.swift
index 70cf3a4f..fb30a8ce 100644
--- a/Sources/Fluid/UI/Visualization/AudioVisualizationShared.swift
+++ b/Sources/Fluid/UI/Visualization/AudioVisualizationShared.swift
@@ -1,20 +1,17 @@
-import SwiftUI
import Combine
+import SwiftUI
-protocol AudioVisualizationConfig
-{
+protocol AudioVisualizationConfig {
var noiseThreshold: CGFloat { get }
var maxAnimationScale: CGFloat { get }
var animationSpring: Animation { get }
}
-final class AudioVisualizationData: ObservableObject
-{
+final class AudioVisualizationData: ObservableObject {
@Published var audioLevel: CGFloat = 0.0
private var cancellable: AnyCancellable?
- init(audioLevelPublisher: AnyPublisher<CGFloat, Never>)
- {
+ init(audioLevelPublisher: AnyPublisher<CGFloat, Never>) {
cancellable = audioLevelPublisher
.receive(on: RunLoop.main)
.sink { [weak self] level in
@@ -22,10 +19,7 @@ final class AudioVisualizationData: ObservableObject
}
}
- deinit
- {
+ deinit {
cancellable?.cancel()
}
}
-
-
diff --git a/Sources/Fluid/UI/WelcomeView.swift b/Sources/Fluid/UI/WelcomeView.swift
index c09c7bd0..36c5b8d1 100644
--- a/Sources/Fluid/UI/WelcomeView.swift
+++ b/Sources/Fluid/UI/WelcomeView.swift
@@ -1,13 +1,6 @@
-//
-// WelcomeView.swift
-// fluid
-//
-// Welcome and setup guide view
-//
-
-import SwiftUI
import AppKit
import AVFoundation
+import SwiftUI
struct WelcomeView: View {
@EnvironmentObject var appServices: AppServices
@@ -17,27 +10,27 @@ struct WelcomeView: View {
@Binding var playgroundUsed: Bool
var isTranscriptionFocused: FocusState<Bool>.Binding
@Environment(\.theme) private var theme
-
+
let accessibilityEnabled: Bool
let providerAPIKeys: [String: String]
let currentProvider: String
let openAIBaseURL: String
let availableModels: [String]
let selectedModel: String
-
+
let stopAndProcessTranscription: () async -> Void
let startRecording: () -> Void
let isLocalEndpoint: (String) -> Bool
let openAccessibilitySettings: () -> Void
-
+
private var commandModeShortcutDisplay: String {
settings.commandModeHotkeyShortcut.displayString
}
-
+
private var writeModeShortcutDisplay: String {
settings.rewriteModeHotkeyShortcut.displayString
}
-
+
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
@@ -45,7 +38,7 @@ struct WelcomeView: View {
HStack(spacing: 10) {
Image(systemName: "book.fill")
.font(.title2)
- .foregroundStyle(theme.palette.accent)
+ .foregroundStyle(self.theme.palette.accent)
Text("Welcome to FluidVoice")
.font(.title2.weight(.bold))
}
@@ -56,105 +49,121 @@ struct WelcomeView: View {
VStack(alignment: .leading, spacing: 12) {
Label("Quick Setup", systemImage: "checkmark.circle.fill")
.font(.headline)
- .foregroundStyle(theme.palette.accent)
+ .foregroundStyle(self.theme.palette.accent)
VStack(alignment: .leading, spacing: 8) {
SetupStepView(
step: 1,
// Consider model step complete if ready OR downloaded (even if not loaded)
- title: (asr.isAsrReady || asr.modelsExistOnDisk) ? "Voice Model Ready" : "Download Voice Model",
- description: asr.isAsrReady
+ title: (self.asr.isAsrReady || self.asr.modelsExistOnDisk) ?
+ "Voice Model Ready" :
+ "Download Voice Model",
+ description: self.asr.isAsrReady
? "Speech recognition model is loaded and ready"
- : (asr.modelsExistOnDisk
+ : (self.asr.modelsExistOnDisk
? "Model downloaded, will load when needed"
: "Download the AI model for offline voice transcription (~500MB)"),
- status: (asr.isAsrReady || asr.modelsExistOnDisk) ? .completed : .pending,
+ status: (self.asr.isAsrReady || self.asr.modelsExistOnDisk) ? .completed :
+ .pending,
action: {
- selectedSidebarItem = .aiSettings
+ self.selectedSidebarItem = .aiSettings
},
actionButtonTitle: "Go to AI Settings",
- showActionButton: !(asr.isAsrReady || asr.modelsExistOnDisk)
+ showActionButton: !(self.asr.isAsrReady || self.asr.modelsExistOnDisk)
)
-
+
SetupStepView(
step: 2,
- title: asr.micStatus == .authorized ? "Microphone Permission Granted" : "Grant Microphone Permission",
- description: asr.micStatus == .authorized
- ? "FluidVoice has access to your microphone"
+ title: self.asr
+ .micStatus == .authorized ? "Microphone Permission Granted" :
+ "Grant Microphone Permission",
+ description: self.asr.micStatus == .authorized
+ ? "FluidVoice has access to your microphone"
: "Allow FluidVoice to access your microphone for voice input",
- status: asr.micStatus == .authorized ? .completed : .pending,
+ status: self.asr.micStatus == .authorized ? .completed : .pending,
action: {
- if asr.micStatus == .notDetermined {
- asr.requestMicAccess()
- } else if asr.micStatus == .denied {
- asr.openSystemSettingsForMic()
+ if self.asr.micStatus == .notDetermined {
+ self.asr.requestMicAccess()
+ } else if self.asr.micStatus == .denied {
+ self.asr.openSystemSettingsForMic()
}
},
- actionButtonTitle: asr.micStatus == .notDetermined ? "Grant Access" : "Open Settings",
- showActionButton: asr.micStatus != .authorized
+ actionButtonTitle: self.asr
+ .micStatus == .notDetermined ? "Grant Access" : "Open Settings",
+ showActionButton: self.asr.micStatus != .authorized
)
SetupStepView(
step: 3,
- title: accessibilityEnabled ? "Accessibility Enabled" : "Enable Accessibility",
- description: accessibilityEnabled
- ? "Accessibility permission granted for typing into apps"
+ title: self
+ .accessibilityEnabled ? "Accessibility Enabled" : "Enable Accessibility",
+ description: self.accessibilityEnabled
+ ? "Accessibility permission granted for typing into apps"
: "Grant accessibility permission to type text into other apps",
- status: accessibilityEnabled ? .completed : .pending,
+ status: self.accessibilityEnabled ? .completed : .pending,
action: {
- openAccessibilitySettings()
+ self.openAccessibilitySettings()
},
actionButtonTitle: "Open Settings",
- showActionButton: !accessibilityEnabled
+ showActionButton: !self.accessibilityEnabled
)
SetupStepView(
step: 4,
title: {
- let hasApiKey = providerAPIKeys[currentProvider]?.isEmpty == false
- let isLocal = isLocalEndpoint(openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines))
- let hasModel = availableModels.contains(selectedModel)
+ let hasApiKey = self.providerAPIKeys[self.currentProvider]?
+ .isEmpty == false
+ let isLocal = self
+ .isLocalEndpoint(self.openAIBaseURL
+ .trimmingCharacters(in: .whitespacesAndNewlines))
+ let hasModel = self.availableModels.contains(self.selectedModel)
let isConfigured = (isLocal || hasApiKey) && hasModel
return isConfigured ? "AI Enhancement Configured" : "Set Up AI Enhancement (Optional)"
}(),
description: {
- let hasApiKey = providerAPIKeys[currentProvider]?.isEmpty == false
- let isLocal = isLocalEndpoint(openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines))
- let hasModel = availableModels.contains(selectedModel)
+ let hasApiKey = self.providerAPIKeys[self.currentProvider]?
+ .isEmpty == false
+ let isLocal = self
+ .isLocalEndpoint(self.openAIBaseURL
+ .trimmingCharacters(in: .whitespacesAndNewlines))
+ let hasModel = self.availableModels.contains(self.selectedModel)
let isConfigured = (isLocal || hasApiKey) && hasModel
- return isConfigured
- ? "AI-powered text enhancement is ready to use"
+ return isConfigured
+ ? "AI-powered text enhancement is ready to use"
: "Configure API keys for AI-powered text enhancement"
}(),
status: {
- let hasApiKey = providerAPIKeys[currentProvider]?.isEmpty == false
- let isLocal = isLocalEndpoint(openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines))
- let hasModel = availableModels.contains(selectedModel)
+ let hasApiKey = self.providerAPIKeys[self.currentProvider]?
+ .isEmpty == false
+ let isLocal = self
+ .isLocalEndpoint(self.openAIBaseURL
+ .trimmingCharacters(in: .whitespacesAndNewlines))
+ let hasModel = self.availableModels.contains(self.selectedModel)
return ((isLocal || hasApiKey) && hasModel) ? .completed : .pending
}(),
action: {
- selectedSidebarItem = .aiSettings
+ self.selectedSidebarItem = .aiSettings
},
actionButtonTitle: "Configure AI"
)
SetupStepView(
step: 5,
- title: playgroundUsed ? "Setup Tested Successfully" : "Test Your Setup",
- description: playgroundUsed
- ? "You've successfully tested voice transcription"
+ title: self.playgroundUsed ? "Setup Tested Successfully" : "Test Your Setup",
+ description: self.playgroundUsed
+ ? "You've successfully tested voice transcription"
: "Try the playground below to test your complete setup",
- status: playgroundUsed ? .completed : .pending,
+ status: self.playgroundUsed ? .completed : .pending,
action: {
// Scroll to playground or focus on it
withAnimation {
- isTranscriptionFocused.wrappedValue = true
+ self.isTranscriptionFocused.wrappedValue = true
}
},
actionButtonTitle: "Go to Playground",
- showActionButton: !playgroundUsed
+ showActionButton: !self.playgroundUsed
)
- .id("playground-step-\(playgroundUsed)")
+ .id("playground-step-\(self.playgroundUsed)")
}
}
.padding(14)
@@ -168,9 +177,21 @@ struct WelcomeView: View {
.foregroundStyle(.green)
VStack(alignment: .leading, spacing: 10) {
- howToStep(number: 1, title: "Start Recording", description: "Press your hotkey (default: Right Option/Alt) or click the button")
- howToStep(number: 2, title: "Speak Clearly", description: "Speak naturally - works best in quiet environments")
- howToStep(number: 3, title: "Auto-Type Result", description: "Transcription is automatically typed into your focused app")
+ self.howToStep(
+ number: 1,
+ title: "Start Recording",
+ description: "Press your hotkey (default: Right Option/Alt) or click the button"
+ )
+ self.howToStep(
+ number: 2,
+ title: "Speak Clearly",
+ description: "Speak naturally - works best in quiet environments"
+ )
+ self.howToStep(
+ number: 3,
+ title: "Auto-Type Result",
+ description: "Transcription is automatically typed into your focused app"
+ )
}
}
.frame(maxWidth: .infinity, alignment: .leading)
@@ -185,14 +206,14 @@ struct WelcomeView: View {
Label("Command Mode", systemImage: "terminal.fill")
.font(.headline)
.foregroundStyle(Color(red: 1.0, green: 0.35, blue: 0.35))
-
- featureBadge("New", color: Color(red: 1.0, green: 0.35, blue: 0.35))
- featureBadge("Alpha", color: Color(red: 1.0, green: 0.35, blue: 0.35).opacity(0.7))
-
+
+ self.featureBadge("New", color: Color(red: 1.0, green: 0.35, blue: 0.35))
+ self.featureBadge("Alpha", color: Color(red: 1.0, green: 0.35, blue: 0.35).opacity(0.7))
+
Spacer()
-
+
Button("Open") {
- selectedSidebarItem = .commandMode
+ self.selectedSidebarItem = .commandMode
}
.buttonStyle(.bordered)
.controlSize(.small)
@@ -206,10 +227,10 @@ struct WelcomeView: View {
Text("Getting Started")
.font(.subheadline.weight(.medium))
.foregroundStyle(.orange)
-
+
HStack(spacing: 4) {
Text("Press")
- keyboardBadge(commandModeShortcutDisplay)
+ self.keyboardBadge(self.commandModeShortcutDisplay)
Text("to open, speak your command, then press again to send.")
}
.font(.caption)
@@ -220,10 +241,13 @@ struct WelcomeView: View {
Text("Examples")
.font(.subheadline.weight(.medium))
.foregroundStyle(.orange)
- commandModeExample(icon: "folder", text: "\"List files in my Downloads folder\"")
- commandModeExample(icon: "plus.rectangle.on.folder", text: "\"Create a folder called Projects on Desktop\"")
- commandModeExample(icon: "network", text: "\"What's my IP address?\"")
- commandModeExample(icon: "safari", text: "\"Open Safari\"")
+ self.commandModeExample(icon: "folder", text: "\"List files in my Downloads folder\"")
+ self.commandModeExample(
+ icon: "plus.rectangle.on.folder",
+ text: "\"Create a folder called Projects on Desktop\""
+ )
+ self.commandModeExample(icon: "network", text: "\"What's my IP address?\"")
+ self.commandModeExample(icon: "safari", text: "\"Open Safari\"")
}
HStack(spacing: 4) {
@@ -246,13 +270,13 @@ struct WelcomeView: View {
Label("Write Mode", systemImage: "pencil.and.outline")
.font(.headline)
.foregroundStyle(.blue)
-
- featureBadge("New", color: .blue)
-
+
+ self.featureBadge("New", color: .blue)
+
Spacer()
-
+
Button("Open") {
- selectedSidebarItem = .rewriteMode
+ self.selectedSidebarItem = .rewriteMode
}
.buttonStyle(.bordered)
.controlSize(.small)
@@ -267,35 +291,35 @@ struct WelcomeView: View {
Text("To Write Fresh")
.font(.subheadline.weight(.medium))
.foregroundStyle(.blue)
-
+
HStack(spacing: 4) {
Text("Press")
- keyboardBadge(writeModeShortcutDisplay)
+ self.keyboardBadge(self.writeModeShortcutDisplay)
Text("and speak what you want to write.")
}
.font(.caption)
.foregroundStyle(.primary.opacity(0.8))
-
- writeModeExample(text: "\"Write an email asking for time off\"")
- writeModeExample(text: "\"Draft a thank you note\"")
+
+ self.writeModeExample(text: "\"Write an email asking for time off\"")
+ self.writeModeExample(text: "\"Draft a thank you note\"")
}
-
+
VStack(alignment: .leading, spacing: 6) {
Text("To Rewrite/Edit")
.font(.subheadline.weight(.medium))
.foregroundStyle(.blue)
-
+
HStack(spacing: 4) {
Text("Select text first, then press")
- keyboardBadge(writeModeShortcutDisplay)
+ self.keyboardBadge(self.writeModeShortcutDisplay)
Text("and speak your instruction.")
}
.font(.caption)
.foregroundStyle(.primary.opacity(0.8))
-
- writeModeExample(text: "\"Make this more formal\"")
- writeModeExample(text: "\"Fix grammar and spelling\"")
- writeModeExample(text: "\"Summarize this\"")
+
+ self.writeModeExample(text: "\"Make this more formal\"")
+ self.writeModeExample(text: "\"Fix grammar and spelling\"")
+ self.writeModeExample(text: "\"Summarize this\"")
}
}
}
@@ -321,8 +345,8 @@ struct WelcomeView: View {
}
Spacer()
-
- if asr.isRunning {
+
+ if self.asr.isRunning {
HStack(spacing: 6) {
Circle()
.fill(.red)
@@ -331,16 +355,16 @@ struct WelcomeView: View {
.font(.caption.weight(.medium))
.foregroundStyle(.red)
}
- } else if !asr.finalText.isEmpty {
- Text("\(asr.finalText.count) characters")
+ } else if !self.asr.finalText.isEmpty {
+ Text("\(self.asr.finalText.count) characters")
.font(.caption)
.foregroundStyle(.secondary)
}
- if !asr.finalText.isEmpty {
+ if !self.asr.finalText.isEmpty {
Button {
NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(asr.finalText, forType: .string)
+ NSPasteboard.general.setString(self.asr.finalText, forType: .string)
} label: {
Label("Copy", systemImage: "doc.on.doc")
}
@@ -353,31 +377,31 @@ struct WelcomeView: View {
// Recording Control
VStack(spacing: 10) {
Button {
- if asr.isRunning {
+ if self.asr.isRunning {
Task {
- await stopAndProcessTranscription()
+ await self.stopAndProcessTranscription()
}
} else {
- startRecording()
- playgroundUsed = true
+ self.startRecording()
+ self.playgroundUsed = true
SettingsStore.shared.playgroundUsed = true
}
} label: {
HStack {
- Image(systemName: asr.isRunning ? "stop.fill" : "mic.fill")
- Text(asr.isRunning ? "Stop Recording" : "Start Recording")
+ Image(systemName: self.asr.isRunning ? "stop.fill" : "mic.fill")
+ Text(self.asr.isRunning ? "Stop Recording" : "Start Recording")
}
.frame(maxWidth: .infinity)
}
- .buttonStyle(PremiumButtonStyle(isRecording: asr.isRunning))
+ .buttonStyle(PremiumButtonStyle(isRecording: self.asr.isRunning))
.buttonHoverEffect()
- .scaleEffect(asr.isRunning ? 1.02 : 1.0)
- .animation(.spring(response: 0.3), value: asr.isRunning)
- .disabled(!asr.isAsrReady && !asr.isRunning)
+ .scaleEffect(self.asr.isRunning ? 1.02 : 1.0)
+ .animation(.spring(response: 0.3), value: self.asr.isRunning)
+ .disabled(!self.asr.isAsrReady && !self.asr.isRunning)
- if !asr.isRunning && !asr.finalText.isEmpty {
+ if !self.asr.isRunning && !self.asr.finalText.isEmpty {
Button("Clear Results") {
- asr.finalText = ""
+ self.asr.finalText = ""
}
.buttonStyle(.bordered)
.controlSize(.small)
@@ -387,67 +411,61 @@ struct WelcomeView: View {
// Text Area
VStack(alignment: .leading, spacing: 8) {
TextEditor(text: Binding(
- get: { asr.finalText },
- set: { asr.finalText = $0 }
+ get: { self.asr.finalText },
+ set: { self.asr.finalText = $0 }
))
- .font(.body)
- .focused(isTranscriptionFocused)
- .frame(height: 140)
- .padding(10)
- .background(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(
- asr.isRunning ? theme.palette.accent.opacity(0.06) : Color(nsColor: NSColor.textBackgroundColor)
- )
- .overlay(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .strokeBorder(
- asr.isRunning ? theme.palette.accent.opacity(0.4) : Color(nsColor: NSColor.separatorColor),
- lineWidth: asr.isRunning ? 2 : 1
- )
- )
- )
- .scrollContentBackground(.hidden)
- .overlay(
- VStack(spacing: 8) {
- if asr.isRunning {
- Image(systemName: "waveform")
- .font(.title2)
- .foregroundStyle(theme.palette.accent)
- Text("Listening... Speak now!")
- .font(.subheadline.weight(.medium))
- .foregroundStyle(theme.palette.accent)
- Text("Transcription will appear when you stop recording")
- .font(.caption)
- .foregroundStyle(theme.palette.accent.opacity(0.7))
- } else if asr.finalText.isEmpty {
- Image(systemName: "text.bubble")
- .font(.title2)
- .foregroundStyle(.secondary.opacity(0.5))
- Text("Ready to test!")
- .font(.subheadline.weight(.medium))
- Text("Click 'Start Recording' or press your hotkey")
- .font(.caption)
- .foregroundStyle(.secondary)
- }
- }
- .allowsHitTesting(false)
- )
+ .font(.body)
+ .focused(self.isTranscriptionFocused)
+ .frame(height: 140)
+ .padding(10)
+ .background(RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(self.asr.isRunning ? self.theme.palette.accent
+ .opacity(0.06) : Color(nsColor: NSColor.textBackgroundColor))
+ .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .strokeBorder(
+ self.asr.isRunning ? self.theme.palette.accent
+ .opacity(0.4) : Color(nsColor: NSColor.separatorColor),
+ lineWidth: self.asr.isRunning ? 2 : 1
+ )))
+ .scrollContentBackground(.hidden)
+ .overlay(VStack(spacing: 8) {
+ if self.asr.isRunning {
+ Image(systemName: "waveform")
+ .font(.title2)
+ .foregroundStyle(self.theme.palette.accent)
+ Text("Listening... Speak now!")
+ .font(.subheadline.weight(.medium))
+ .foregroundStyle(self.theme.palette.accent)
+ Text("Transcription will appear when you stop recording")
+ .font(.caption)
+ .foregroundStyle(self.theme.palette.accent.opacity(0.7))
+ } else if self.asr.finalText.isEmpty {
+ Image(systemName: "text.bubble")
+ .font(.title2)
+ .foregroundStyle(.secondary.opacity(0.5))
+ Text("Ready to test!")
+ .font(.subheadline.weight(.medium))
+ Text("Click 'Start Recording' or press your hotkey")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ }
+ .allowsHitTesting(false))
- if !asr.finalText.isEmpty {
+ if !self.asr.finalText.isEmpty {
HStack(spacing: 8) {
Button {
NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(asr.finalText, forType: .string)
+ NSPasteboard.general.setString(self.asr.finalText, forType: .string)
} label: {
Label("Copy Text", systemImage: "doc.on.doc")
}
.buttonStyle(.borderedProminent)
- .tint(theme.palette.accent)
+ .tint(self.theme.palette.accent)
.controlSize(.small)
Button("Clear & Test Again") {
- asr.finalText = ""
+ self.asr.finalText = ""
}
.buttonStyle(.bordered)
.controlSize(.small)
@@ -460,7 +478,6 @@ struct WelcomeView: View {
}
.padding(16)
}
-
}
.padding(16)
}
@@ -469,25 +486,25 @@ struct WelcomeView: View {
// This prevents the Quick Setup from showing stale status before ASRService.initialize() runs
Task { @MainActor in
// Check microphone status without triggering the full initialize() delay
- asr.micStatus = AVCaptureDevice.authorizationStatus(for: .audio)
-
+ self.asr.micStatus = AVCaptureDevice.authorizationStatus(for: .audio)
+
// Check if models exist on disk
- asr.checkIfModelsExist()
+ self.asr.checkIfModelsExist()
}
}
}
-
+
// MARK: - Helper Views
-
+
private func howToStep(number: Int, title: String, description: String) -> some View {
HStack(alignment: .top, spacing: 10) {
ZStack {
Circle()
- .fill(theme.palette.accent.opacity(0.15))
+ .fill(self.theme.palette.accent.opacity(0.15))
.frame(width: 28, height: 28)
Text("\(number)")
.font(.caption.weight(.bold))
- .foregroundStyle(theme.palette.accent)
+ .foregroundStyle(self.theme.palette.accent)
}
VStack(alignment: .leading, spacing: 2) {
Text(title)
@@ -499,7 +516,7 @@ struct WelcomeView: View {
Spacer()
}
}
-
+
private func featureBadge(_ text: String, color: Color) -> some View {
Text(text)
.font(.caption2.weight(.semibold))
@@ -508,7 +525,7 @@ struct WelcomeView: View {
.padding(.vertical, 2)
.background(color, in: RoundedRectangle(cornerRadius: 4, style: .continuous))
}
-
+
private func keyboardBadge(_ text: String) -> some View {
Text(text)
.font(.caption.weight(.medium))
@@ -516,7 +533,7 @@ struct WelcomeView: View {
.padding(.vertical, 2)
.background(Color.primary.opacity(0.1), in: RoundedRectangle(cornerRadius: 4, style: .continuous))
}
-
+
private func commandModeExample(icon: String, text: String) -> some View {
HStack(spacing: 6) {
Image(systemName: icon)
@@ -528,7 +545,7 @@ struct WelcomeView: View {
.foregroundStyle(.primary.opacity(0.8))
}
}
-
+
private func writeModeExample(text: String) -> some View {
HStack(spacing: 6) {
Text("•")
@@ -539,4 +556,3 @@ struct WelcomeView: View {
}
}
}
-
diff --git a/Sources/Fluid/Views/CommandModeView.swift b/Sources/Fluid/Views/CommandModeView.swift
index bb2c7072..3253d5f2 100644
--- a/Sources/Fluid/Views/CommandModeView.swift
+++ b/Sources/Fluid/Views/CommandModeView.swift
@@ -8,108 +8,108 @@ struct CommandModeView: View {
@EnvironmentObject var menuBarManager: MenuBarManager
var onClose: (() -> Void)?
@State private var inputText: String = ""
-
+
// Local state for available models (derived from shared AI Settings pool)
@State private var availableModels: [String] = []
-
+
// UI State
@State private var showingClearConfirmation = false
@State private var showHowTo = false
@State private var isHoveringHowTo = false
-
+
@Environment(\.theme) private var theme
-
+
var body: some View {
VStack(spacing: 0) {
// Header
- headerView
-
+ self.headerView
+
// How To (collapsible)
- howToSection
-
+ self.howToSection
+
Divider()
-
+
// Chat Area
- chatArea
-
+ self.chatArea
+
// Pending Command Confirmation (if any)
if let pending = service.pendingCommand {
- pendingCommandView(pending)
+ self.pendingCommandView(pending)
}
-
+
Divider()
-
+
// Input Area
- inputArea
+ self.inputArea
}
.onAppear {
- updateAvailableModels()
+ self.updateAvailableModels()
// Disable notch output when using in-app UI (conversation is shared but notch shouldn't show)
- service.enableNotchOutput = false
+ self.service.enableNotchOutput = false
}
.onDisappear {
// Re-enable notch output when leaving in-app UI
- service.enableNotchOutput = true
+ self.service.enableNotchOutput = true
}
.onChange(of: asr.finalText) { _, newText in
if !newText.isEmpty {
- inputText = newText
+ self.inputText = newText
}
}
- .onChange(of: settings.commandModeSelectedProviderID) { _, _ in
- updateAvailableModels()
+ .onChange(of: settings.commandModeSelectedProviderID) { _, _ in
+ self.updateAvailableModels()
}
.onExitCommand {
- onClose?()
+ self.onClose?()
}
}
-
+
// MARK: - Header
-
+
private var headerView: some View {
HStack {
HStack(spacing: 8) {
Text("Command Mode")
.font(.title2)
.fontWeight(.bold)
-
+
Text("Alpha")
.font(.caption2)
.fontWeight(.semibold)
.foregroundStyle(.white)
.padding(.horizontal, 6)
.padding(.vertical, 2)
- .background(Color(red: 1.0, green: 0.35, blue: 0.35)) // Command mode red
+ .background(Color(red: 1.0, green: 0.35, blue: 0.35)) // Command mode red
.cornerRadius(4)
}
-
+
Spacer()
-
+
// Chat management buttons
HStack(spacing: 4) {
// New Chat Button
- Button(action: { service.createNewChat() }) {
+ Button(action: { self.service.createNewChat() }) {
Image(systemName: "plus")
}
.buttonStyle(.bordered)
.help("New chat")
- .disabled(service.isProcessing)
-
+ .disabled(self.service.isProcessing)
+
// Recent Chats Menu
Menu {
- let recentChats = service.getRecentChats()
+ let recentChats = self.service.getRecentChats()
if recentChats.isEmpty {
Text("No recent chats")
.foregroundStyle(.secondary)
} else {
ForEach(recentChats) { chat in
- Button(action: {
- if chat.id != service.currentChatID {
- service.switchToChat(id: chat.id)
+ Button(action: {
+ if chat.id != self.service.currentChatID {
+ self.service.switchToChat(id: chat.id)
}
}) {
HStack {
- if chat.id == service.currentChatID {
+ if chat.id == self.service.currentChatID {
Image(systemName: "checkmark")
.font(.caption)
}
@@ -121,7 +121,7 @@ struct CommandModeView: View {
.foregroundStyle(.secondary)
}
}
- .disabled(service.isProcessing)
+ .disabled(self.service.isProcessing)
}
}
} label: {
@@ -130,22 +130,22 @@ struct CommandModeView: View {
.menuStyle(.borderlessButton)
.frame(width: 32, height: 24)
.help("Recent chats")
-
+
// Delete Chat Button - deletes the current chat entirely
- Button(action: { showingClearConfirmation = true }) {
+ Button(action: { self.showingClearConfirmation = true }) {
Image(systemName: "trash")
}
.buttonStyle(.bordered)
.help("Delete chat")
- .disabled(service.isProcessing)
+ .disabled(self.service.isProcessing)
}
-
+
Divider()
.frame(height: 20)
.padding(.horizontal, 8)
-
+
// Confirm Before Execute Toggle
- Toggle(isOn: $settings.commandModeConfirmBeforeExecute) {
+ Toggle(isOn: self.$settings.commandModeConfirmBeforeExecute) {
Label("Confirm", systemImage: "checkmark.shield")
.font(.caption)
}
@@ -160,43 +160,43 @@ struct CommandModeView: View {
titleVisibility: .visible
) {
Button("Delete", role: .destructive) {
- service.deleteCurrentChat()
+ self.service.deleteCurrentChat()
}
Button("Cancel", role: .cancel) {}
}
}
-
+
// MARK: - How To Section
-
+
private var shortcutDisplay: String {
settings.commandModeHotkeyShortcut.displayString
}
-
+
private var howToSection: some View {
VStack(spacing: 0) {
// Toggle button with hover effect
- Button(action: { withAnimation(.easeInOut(duration: 0.2)) { showHowTo.toggle() } }) {
+ Button(action: { withAnimation(.easeInOut(duration: 0.2)) { self.showHowTo.toggle() } }) {
HStack {
Image(systemName: "questionmark.circle")
.font(.caption)
Text("How to use")
.font(.caption)
Spacer()
- Image(systemName: showHowTo ? "chevron.up" : "chevron.down")
+ Image(systemName: self.showHowTo ? "chevron.up" : "chevron.down")
.font(.caption2)
}
- .foregroundStyle(isHoveringHowTo ? .primary : .secondary)
+ .foregroundStyle(self.isHoveringHowTo ? .primary : .secondary)
.padding(.horizontal, 16)
.padding(.vertical, 8)
- .background(isHoveringHowTo ? Color.primary.opacity(0.05) : Color.clear)
+ .background(self.isHoveringHowTo ? Color.primary.opacity(0.05) : Color.clear)
.cornerRadius(4)
}
.buttonStyle(.plain)
.onHover { hovering in
- withAnimation(.easeInOut(duration: 0.15)) { isHoveringHowTo = hovering }
+ withAnimation(.easeInOut(duration: 0.15)) { self.isHoveringHowTo = hovering }
}
-
- if showHowTo {
+
+ if self.showHowTo {
VStack(alignment: .leading, spacing: 12) {
// Start section
VStack(alignment: .leading, spacing: 4) {
@@ -204,11 +204,11 @@ struct CommandModeView: View {
.font(.caption)
.fontWeight(.semibold)
.foregroundStyle(.secondary)
-
+
HStack(spacing: 4) {
Text("Press")
.font(.caption)
- Text(shortcutDisplay)
+ Text(self.shortcutDisplay)
.font(.caption)
.fontWeight(.medium)
.padding(.horizontal, 6)
@@ -220,22 +220,22 @@ struct CommandModeView: View {
}
.foregroundStyle(.primary.opacity(0.8))
}
-
+
// Examples
VStack(alignment: .leading, spacing: 4) {
Text("Examples")
.font(.caption)
.fontWeight(.semibold)
.foregroundStyle(.secondary)
-
+
VStack(alignment: .leading, spacing: 4) {
- howToItem("\"List files in my Downloads folder\"")
- howToItem("\"Create a folder called Projects on Desktop\"")
- howToItem("\"What's my IP address?\"")
- howToItem("\"Open Safari\"")
+ self.howToItem("\"List files in my Downloads folder\"")
+ self.howToItem("\"Create a folder called Projects on Desktop\"")
+ self.howToItem("\"What's my IP address?\"")
+ self.howToItem("\"Open Safari\"")
}
}
-
+
// Caution note
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 4) {
@@ -245,7 +245,7 @@ struct CommandModeView: View {
.fontWeight(.semibold)
}
.font(.caption)
-
+
Text("AI can make mistakes. Avoid dangerous commands like deleting important files. Destructive actions will ask for confirmation.")
.font(.caption)
.foregroundStyle(.secondary)
@@ -258,7 +258,7 @@ struct CommandModeView: View {
}
.background(Color(nsColor: .windowBackgroundColor).opacity(0.5))
}
-
+
private func howToItem(_ text: String) -> some View {
HStack(spacing: 6) {
Text("•")
@@ -268,52 +268,52 @@ struct CommandModeView: View {
.foregroundStyle(.primary.opacity(0.8))
}
}
-
+
// MARK: - Chat Area
-
+
private var chatArea: some View {
ScrollViewReader { proxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 12) {
- ForEach(service.conversationHistory) { message in
+ ForEach(self.service.conversationHistory) { message in
MessageBubble(message: message)
.id(message.id)
}
-
- if service.isProcessing {
+
+ if self.service.isProcessing {
VStack(alignment: .leading, spacing: 8) {
- processingIndicator
-
+ self.processingIndicator
+
// Show streaming text in real-time
- if !service.streamingText.isEmpty {
- streamingTextView
+ if !self.service.streamingText.isEmpty {
+ self.streamingTextView
}
}
.id("processing")
}
-
+
Color.clear.frame(height: 1).id("bottom")
}
.padding()
}
- .onChange(of: service.conversationHistory.count) { _, _ in
- scrollToBottom(proxy)
+ .onChange(of: self.service.conversationHistory.count) { _, _ in
+ self.scrollToBottom(proxy)
}
- .onChange(of: service.isProcessing) { _, isProcessing in
+ .onChange(of: self.service.isProcessing) { _, isProcessing in
// Scroll when processing starts, not on every streaming update
if isProcessing {
- scrollToBottom(proxy)
+ self.scrollToBottom(proxy)
}
}
- .onChange(of: service.currentStep) { _, _ in
- scrollToBottom(proxy)
+ .onChange(of: self.service.currentStep) { _, _ in
+ self.scrollToBottom(proxy)
}
// Removed: .onChange(of: service.streamingText) - causes scroll on every token, too expensive
}
}
-
+
// MARK: - Processing Indicator (Minimal with Shimmer)
-
+
private var processingIndicator: some View {
CommandShimmerText(text: currentStepLabel)
.padding(.horizontal, 12)
@@ -321,9 +321,9 @@ struct CommandModeView: View {
.background(Color(nsColor: .controlBackgroundColor).opacity(0.6))
.cornerRadius(6)
}
-
+
// MARK: - Streaming Text View (Real-time AI response)
-
+
private var streamingTextView: some View {
// Use fixedSize to prevent expensive re-layout on every update
Text(service.streamingText)
@@ -334,28 +334,28 @@ struct CommandModeView: View {
.frame(maxWidth: 520, alignment: .leading)
.background(Color(nsColor: .textBackgroundColor).opacity(0.5))
.cornerRadius(8)
- .drawingGroup() // Flatten to bitmap for faster updates
- // textSelection disabled during streaming - re-enabled in final message
+ .drawingGroup() // Flatten to bitmap for faster updates
+ // textSelection disabled during streaming - re-enabled in final message
}
-
+
private var currentStepLabel: String {
guard let step = service.currentStep else { return "Working..." }
switch step {
case .thinking: return "Thinking..."
- case .checking(let cmd): return "Checking \(truncateCommand(cmd, to: 30))"
- case .executing(let cmd): return "Running \(truncateCommand(cmd, to: 30))"
+ case let .checking(cmd): return "Checking \(truncateCommand(cmd, to: 30))"
+ case let .executing(cmd): return "Running \(truncateCommand(cmd, to: 30))"
case .verifying: return "Verifying..."
- case .completed(let success): return success ? "Done" : "Stopped"
+ case let .completed(success): return success ? "Done" : "Stopped"
}
}
-
+
private func truncateCommand(_ cmd: String, to limit: Int) -> String {
if cmd.count > limit {
return String(cmd.prefix(limit - 3)) + "..."
}
return cmd
}
-
+
private func scrollToBottom(_ proxy: ScrollViewProxy) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
withAnimation(.easeOut(duration: 0.2)) {
@@ -363,13 +363,13 @@ struct CommandModeView: View {
}
}
}
-
+
// MARK: - Pending Command
-
+
private func pendingCommandView(_ pending: CommandModeService.PendingCommand) -> some View {
VStack(spacing: 10) {
Divider()
-
+
HStack {
Image(systemName: "exclamationmark.shield.fill")
.foregroundStyle(.orange)
@@ -385,7 +385,7 @@ struct CommandModeView: View {
}
Spacer()
}
-
+
// Command preview
VStack(alignment: .leading, spacing: 0) {
HStack {
@@ -399,9 +399,9 @@ struct CommandModeView: View {
.padding(.horizontal, 10)
.padding(.vertical, 6)
.background(Color(nsColor: .windowBackgroundColor))
-
+
Divider()
-
+
Text(pending.command)
.font(.system(.callout, design: .monospaced))
.textSelection(.enabled)
@@ -409,20 +409,18 @@ struct CommandModeView: View {
}
.background(Color(nsColor: .textBackgroundColor))
.cornerRadius(8)
- .overlay(
- RoundedRectangle(cornerRadius: 8)
- .stroke(Color.orange.opacity(0.5), lineWidth: 1)
- )
-
+ .overlay(RoundedRectangle(cornerRadius: 8)
+ .stroke(Color.orange.opacity(0.5), lineWidth: 1))
+
HStack(spacing: 12) {
- Button(action: { service.cancelPendingCommand() }) {
+ Button(action: { self.service.cancelPendingCommand() }) {
Label("Cancel", systemImage: "xmark")
}
.buttonStyle(.bordered)
.keyboardShortcut(.escape, modifiers: [])
-
+
Button(action: {
- Task { await service.confirmAndExecute() }
+ Task { await self.service.confirmAndExecute() }
}) {
Label("Run Command", systemImage: "play.fill")
}
@@ -434,124 +432,129 @@ struct CommandModeView: View {
.padding()
.background(Color.orange.opacity(0.08))
}
-
+
// MARK: - Input Area
-
+
private var inputArea: some View {
HStack(spacing: 8) {
// Provider Selector (compact)
- Picker("", selection: $settings.commandModeSelectedProviderID) {
+ Picker("", selection: self.$settings.commandModeSelectedProviderID) {
Text("OpenAI").tag("openai")
Text("Groq").tag("groq")
-
+
// Apple Intelligence - disabled for Command Mode (no tool support)
Text("Apple Intelligence (No tools)")
.foregroundColor(.secondary)
.tag("apple-intelligence-disabled")
-
- ForEach(settings.savedProviders) { provider in
+
+ ForEach(self.settings.savedProviders) { provider in
Text(provider.name).tag(provider.id)
}
}
.frame(width: 110)
- .onChange(of: settings.commandModeSelectedProviderID) { _, newValue in
+ .onChange(of: self.settings.commandModeSelectedProviderID) { _, newValue in
// Prevent selecting disabled Apple Intelligence
if newValue == "apple-intelligence-disabled" || newValue == "apple-intelligence" {
- settings.commandModeSelectedProviderID = "openai"
+ self.settings.commandModeSelectedProviderID = "openai"
}
}
-
+
// Model Selector (compact)
- Picker("", selection: Binding(
- get: { settings.commandModeSelectedModel ?? availableModels.first ?? "gpt-4o" },
- set: { settings.commandModeSelectedModel = $0 }
- )) {
- ForEach(availableModels, id: \.self) { model in
+ Picker(
+ "",
+ selection: Binding(
+ get: {
+ self.settings.commandModeSelectedModel ?? self.availableModels.first ?? "gpt-4o"
+ },
+ set: { self.settings.commandModeSelectedModel = $0 }
+ )
+ ) {
+ ForEach(self.availableModels, id: \.self) { model in
Text(model).tag(model)
}
}
.frame(width: 130)
-
+
// Input field (flexible)
- TextField("Type a command or ask a question...", text: $inputText)
+ TextField("Type a command or ask a question...", text: self.$inputText)
.textFieldStyle(.roundedBorder)
.onSubmit {
- submitCommand()
+ self.submitCommand()
}
-
- Button(action: submitCommand) {
+
+ Button(action: self.submitCommand) {
Image(systemName: "arrow.up.circle.fill")
.font(.title2)
}
.buttonStyle(.plain)
- .disabled(inputText.isEmpty || service.isProcessing)
-
+ .disabled(self.inputText.isEmpty || self.service.isProcessing)
+
// Voice Input
- Button(action: toggleRecording) {
- Image(systemName: asr.isRunning ? "stop.circle.fill" : "mic.circle.fill")
+ Button(action: self.toggleRecording) {
+ Image(systemName: self.asr.isRunning ? "stop.circle.fill" : "mic.circle.fill")
.font(.title2)
- .foregroundStyle(asr.isRunning ? Color.red : Color.accentColor)
+ .foregroundStyle(self.asr.isRunning ? Color.red : Color.accentColor)
}
.buttonStyle(.plain)
}
.padding()
.background(Color(nsColor: .windowBackgroundColor))
}
-
+
// MARK: - Actions
-
+
private func toggleRecording() {
if asr.isRunning {
- Task { await asr.stop() }
+ Task { await self.asr.stop() }
} else {
asr.start()
}
}
-
+
private func submitCommand() {
guard !inputText.isEmpty else { return }
let text = inputText
inputText = ""
Task {
- await service.processUserCommand(text)
+ await self.service.processUserCommand(text)
}
}
-
+
private func updateAvailableModels() {
let currentProviderID = settings.commandModeSelectedProviderID
let currentModel = settings.commandModeSelectedModel ?? "gpt-4o"
-
+
// Pull models from the shared pool configured in AI Settings
let possibleKeys = providerKeys(for: currentProviderID)
let storedList = possibleKeys.lazy
.compactMap { SettingsStore.shared.availableModelsByProvider[$0] }
.first { !$0.isEmpty }
-
+
if let stored = storedList {
availableModels = stored
} else {
availableModels = defaultModels(for: currentProviderID)
}
-
+
// If current model not in list, select first available
if !availableModels.contains(currentModel) {
settings.commandModeSelectedModel = availableModels.first ?? "gpt-4o"
}
}
-
+
/// Returns possible keys used to store models for a provider.
private func providerKeys(for providerID: String) -> [String] {
var keys: [String] = []
let trimmed = providerID.trimmingCharacters(in: .whitespacesAndNewlines)
-
+
if trimmed.isEmpty {
return [providerID]
}
-
+
if trimmed == "openai" || trimmed == "groq" {
return [trimmed]
}
-
+
if trimmed.hasPrefix("custom:") {
keys.append(trimmed)
keys.append(String(trimmed.dropFirst("custom:".count)))
@@ -559,13 +562,13 @@ struct CommandModeView: View {
keys.append("custom:\(trimmed)")
keys.append(trimmed)
}
-
+
// Add legacy key used in ContentView before the fix
keys.append("custom:\\(trimmed)")
-
+
return Array(Set(keys))
}
-
+
private func defaultModels(for provider: String) -> [String] {
switch provider {
case "openai": return ["gpt-4.1"]
@@ -579,28 +582,26 @@ struct CommandModeView: View {
struct CommandShimmerText: View {
let text: String
-
+
@State private var shimmerPhase: CGFloat = 0
-
+
var body: some View {
Text(text)
.font(.system(size: 11, weight: .medium))
- .foregroundStyle(
- LinearGradient(
- colors: [
- Color.primary.opacity(0.4),
- Color.primary.opacity(0.4),
- Color.primary.opacity(0.8),
- 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)
- )
- )
+ .foregroundStyle(LinearGradient(
+ colors: [
+ Color.primary.opacity(0.4),
+ Color.primary.opacity(0.4),
+ Color.primary.opacity(0.8),
+ 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)
+ ))
.onAppear {
withAnimation(.linear(duration: 1.2).repeatForever(autoreverses: false)) {
- shimmerPhase = 1.3
+ self.shimmerPhase = 1.3
}
}
}
@@ -610,21 +611,21 @@ struct CommandShimmerText: View {
struct MessageBubble: View {
let message: CommandModeService.Message
-
+
var body: some View {
HStack(alignment: .top) {
- if message.role == .user {
+ if self.message.role == .user {
Spacer()
- userMessageView
+ self.userMessageView
} else {
- agentMessageView
+ self.agentMessageView
Spacer()
}
}
}
-
+
// MARK: - User Message
-
+
private var userMessageView: some View {
Text(message.content)
.font(.system(size: 13))
@@ -634,9 +635,9 @@ struct MessageBubble: View {
.cornerRadius(10)
.frame(maxWidth: 380, alignment: .trailing)
}
-
+
// MARK: - Agent Message
-
+
private var agentMessageView: some View {
VStack(alignment: .leading, spacing: 6) {
// Purpose label (minimal, gray)
@@ -645,33 +646,34 @@ struct MessageBubble: View {
.font(.system(size: 11))
.foregroundStyle(.secondary)
}
-
+
// Main content
- if message.role == .tool {
- toolOutputView
+ if self.message.role == .tool {
+ self.toolOutputView
} else if let tc = message.toolCall {
- commandCallView(tc)
- } else if !message.content.isEmpty {
- textContentView
+ self.commandCallView(tc)
+ } else if !self.message.content.isEmpty {
+ self.textContentView
}
}
.frame(maxWidth: 520, alignment: .leading)
}
-
+
// MARK: - Command Call View (Minimal)
-
+
private func commandCallView(_ tc: CommandModeService.Message.ToolCall) -> some View {
VStack(alignment: .leading, spacing: 4) {
// Reasoning text (if meaningful)
- if !message.content.isEmpty &&
- !message.content.lowercased().starts(with: "checking") &&
- !message.content.lowercased().starts(with: "executing") &&
- !message.content.lowercased().starts(with: "i'll") {
- Text(message.content)
+ if !self.message.content.isEmpty &&
+ !self.message.content.lowercased().starts(with: "checking") &&
+ !self.message.content.lowercased().starts(with: "executing") &&
+ !self.message.content.lowercased().starts(with: "i'll")
+ {
+ Text(self.message.content)
.font(.system(size: 12))
.foregroundStyle(.secondary)
}
-
+
// Command block - clean and simple
Text(tc.command)
.font(.system(size: 12, design: .monospaced))
@@ -683,21 +685,21 @@ struct MessageBubble: View {
.cornerRadius(6)
}
}
-
+
// MARK: - Tool Output View (Minimal)
-
+
private var toolOutputView: some View {
let parsed = parseToolOutput(message.content)
-
+
return VStack(alignment: .leading, spacing: 0) {
// Minimal header - just status and time
HStack(spacing: 6) {
Text(parsed.success ? "Success" : "Error")
.font(.system(size: 11, weight: .medium))
.foregroundStyle(parsed.success ? .primary : .secondary)
-
+
Spacer()
-
+
if parsed.executionTime > 0 {
Text("\(parsed.executionTime)ms")
.font(.system(size: 10))
@@ -706,21 +708,21 @@ struct MessageBubble: View {
}
.padding(.horizontal, 10)
.padding(.vertical, 6)
-
+
// Output content (if any)
if !parsed.output.isEmpty || parsed.error != nil {
Divider()
.padding(.horizontal, 10)
-
+
ScrollView(.vertical, showsIndicators: false) {
VStack(alignment: .leading, spacing: 2) {
if !parsed.output.isEmpty {
- Text(markdownAttributedString(from: parsed.output))
+ Text(self.markdownAttributedString(from: parsed.output))
.font(.system(size: 11, design: .monospaced))
.foregroundStyle(.secondary)
.textSelection(.enabled)
}
-
+
if let error = parsed.error, !error.isEmpty {
Text(error)
.font(.system(size: 11, design: .monospaced))
@@ -738,30 +740,32 @@ struct MessageBubble: View {
.background(Color(nsColor: .textBackgroundColor).opacity(0.5))
.cornerRadius(6)
}
-
+
// MARK: - Text Content View (Minimal)
-
+
private var textContentView: some View {
Text(markdownAttributedString(from: message.content))
.font(.system(size: 13))
.textSelection(.enabled)
}
-
+
// MARK: - Markdown Rendering
-
+
private func markdownAttributedString(from text: String) -> AttributedString {
do {
- let attributed = try AttributedString(markdown: text, options: AttributedString.MarkdownParsingOptions(
- interpretedSyntax: .inlineOnlyPreservingWhitespace
- ))
+ let attributed = try AttributedString(
+ markdown: text,
+ options: AttributedString
+ .MarkdownParsingOptions(interpretedSyntax: .inlineOnlyPreservingWhitespace)
+ )
return attributed
} catch {
return AttributedString(text)
}
}
-
+
// MARK: - Helpers
-
+
private struct ParsedOutput {
let success: Bool
let output: String
@@ -769,13 +773,14 @@ struct MessageBubble: View {
let exitCode: Int
let executionTime: Int
}
-
+
private func parseToolOutput(_ json: String) -> ParsedOutput {
guard let data = json.data(using: .utf8),
- let parsed = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+ let parsed = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
+ else {
return ParsedOutput(success: false, output: json, error: nil, exitCode: -1, executionTime: 0)
}
-
+
return ParsedOutput(
success: parsed["success"] as? Bool ?? false,
output: parsed["output"] as? String ?? "",
diff --git a/Sources/Fluid/Views/NotchContentViews.swift b/Sources/Fluid/Views/NotchContentViews.swift
index 84ad25ff..f724102b 100644
--- a/Sources/Fluid/Views/NotchContentViews.swift
+++ b/Sources/Fluid/Views/NotchContentViews.swift
@@ -1,87 +1,82 @@
-//
-// NotchContentViews.swift
-// Fluid
-//
-// Created by Assistant
-//
-
-import SwiftUI
import Combine
+import SwiftUI
// MARK: - Observable state for notch content (Singleton)
@MainActor
class NotchContentState: ObservableObject {
static let shared = NotchContentState()
-
+
@Published var transcriptionText: String = ""
@Published var mode: OverlayMode = .dictation
- @Published var isProcessing: Bool = false // AI processing state
-
+ @Published var isProcessing: Bool = false // AI processing state
+
// Cached transcription lines to avoid recomputing on every render
@Published private(set) var cachedLine1: String = ""
@Published private(set) var cachedLine2: String = ""
-
+
// MARK: - Expanded Command Output State
+
@Published var isExpandedForCommandOutput: Bool = false
- @Published var commandOutput: String = "" // Final or streaming output
- @Published var commandStreamingText: String = "" // Real-time streaming text
- @Published var commandInputText: String = "" // User's follow-up input
+ @Published var commandOutput: String = "" // Final or streaming output
+ @Published var commandStreamingText: String = "" // Real-time streaming text
+ @Published var commandInputText: String = "" // User's follow-up input
@Published var commandConversationHistory: [CommandOutputMessage] = []
@Published var isCommandProcessing: Bool = false
-
+
// MARK: - Chat History State
+
@Published var recentChats: [ChatSession] = []
@Published var currentChatTitle: String = "New Chat"
-
+
// Command output message model
struct CommandOutputMessage: Identifiable, Equatable {
let id = UUID()
let role: Role
let content: String
- let timestamp: Date = Date()
-
+ let timestamp: Date = .init()
+
enum Role: Equatable {
case user
case assistant
- case status // For "Running...", "Checking...", etc.
+ case status // For "Running...", "Checking...", etc.
}
}
-
+
// Callback for submitting follow-up commands from the notch
var onSubmitFollowUp: ((String) async -> Void)?
-
+
private init() {}
-
+
/// Set AI processing state
func setProcessing(_ processing: Bool) {
isProcessing = processing
}
-
+
/// Update transcription and recompute cached lines
func updateTranscription(_ text: String) {
guard text != transcriptionText else { return }
transcriptionText = text
recomputeTranscriptionLines()
}
-
+
/// Recompute cached transcription lines (called only when text changes)
private func recomputeTranscriptionLines() {
let text = transcriptionText
-
+
guard !text.isEmpty else {
cachedLine1 = ""
cachedLine2 = ""
return
}
-
+
// Show last ~100 characters
let maxChars = 100
let displayText = text.count > maxChars ? String(text.suffix(maxChars)) : text
-
+
// Split into words
let words = displayText.split(separator: " ").map(String.init)
-
+
if words.count <= 6 {
// Short: only line 2
cachedLine1 = ""
@@ -93,11 +88,12 @@ class NotchContentState: ObservableObject {
cachedLine2 = words[midPoint...].joined(separator: " ")
}
}
-
+
// MARK: - Recording State for Expanded View
+
@Published var isRecordingInExpandedMode: Bool = false
- @Published var expandedModeAudioLevel: CGFloat = 0 // Audio level for waveform in expanded mode
-
+ @Published var expandedModeAudioLevel: CGFloat = 0 // Audio level for waveform in expanded mode
+
/// Set recording state (for waveform visibility in expanded view)
func setRecordingInExpandedMode(_ recording: Bool) {
isRecordingInExpandedMode = recording
@@ -105,39 +101,39 @@ class NotchContentState: ObservableObject {
expandedModeAudioLevel = 0
}
}
-
+
/// Update audio level for expanded mode waveform
func updateExpandedModeAudioLevel(_ level: CGFloat) {
guard isRecordingInExpandedMode else { return }
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
+ isRecordingInExpandedMode = false // Not recording when first showing output
}
-
+
/// Update streaming text in real-time
func updateCommandStreamingText(_ text: String) {
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)
}
-
+
/// Set command processing state
func setCommandProcessing(_ processing: Bool) {
isCommandProcessing = processing
}
-
+
/// Clear command output and hide expanded view
func clearCommandOutput() {
isExpandedForCommandOutput = false
@@ -147,14 +143,14 @@ class NotchContentState: ObservableObject {
commandConversationHistory.removeAll()
isCommandProcessing = false
}
-
+
/// Hide expanded view but keep history
func collapseCommandOutput() {
isExpandedForCommandOutput = false
}
-
+
// MARK: - Chat History Methods
-
+
/// Refresh recent chats from store
func refreshRecentChats() {
recentChats = ChatHistoryStore.shared.getRecentChats(excludingCurrent: false)
@@ -175,7 +171,7 @@ extension OverlayMode {
case .rewrite:
return Color(red: 0.45, green: 0.55, blue: 1.0) // Lighter blue
case .write:
- return Color(red: 0.4, green: 0.6, blue: 1.0) // Blue
+ return Color(red: 0.4, green: 0.6, blue: 1.0) // Blue
case .command:
return Color(red: 1.0, green: 0.35, blue: 0.35) // Red
}
@@ -187,28 +183,26 @@ extension OverlayMode {
struct ShimmerText: View {
let text: String
let color: Color
-
+
@State private var shimmerPhase: CGFloat = 0
-
+
var body: some View {
Text(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)
- ],
- startPoint: UnitPoint(x: shimmerPhase - 0.3, y: 0.5),
- endPoint: UnitPoint(x: shimmerPhase + 0.3, y: 0.5)
- )
- )
+ .foregroundStyle(LinearGradient(
+ colors: [
+ color.opacity(0.4),
+ color.opacity(0.4),
+ color.opacity(1.0),
+ color.opacity(0.4),
+ color.opacity(0.4),
+ ],
+ startPoint: UnitPoint(x: shimmerPhase - 0.3, y: 0.5),
+ endPoint: UnitPoint(x: shimmerPhase + 0.3, y: 0.5)
+ ))
.onAppear {
withAnimation(.linear(duration: 1.2).repeatForever(autoreverses: false)) {
- shimmerPhase = 1.3
+ self.shimmerPhase = 1.3
}
}
}
@@ -219,11 +213,11 @@ struct ShimmerText: View {
struct NotchExpandedView: View {
let audioPublisher: AnyPublisher<CGFloat, Never>
@ObservedObject private var contentState = NotchContentState.shared
-
+
private var modeColor: Color {
contentState.mode.notchColor
}
-
+
private var modeLabel: String {
switch contentState.mode {
case .dictation: return "Dictate"
@@ -232,7 +226,7 @@ struct NotchExpandedView: View {
case .command: return "Command"
}
}
-
+
private var processingLabel: String {
switch contentState.mode {
case .dictation: return "Refining..."
@@ -241,40 +235,40 @@ struct NotchExpandedView: View {
case .command: return "Working..."
}
}
-
+
private var hasTranscription: Bool {
!contentState.transcriptionText.isEmpty
}
-
+
// Check if there's command history that can be expanded
private var canExpandCommandHistory: Bool {
contentState.mode == .command && !contentState.commandConversationHistory.isEmpty
}
-
+
var body: some View {
VStack(spacing: 4) {
// Visualization + Mode label row
HStack(spacing: 6) {
NotchWaveformView(
- audioPublisher: audioPublisher,
- color: modeColor
+ audioPublisher: self.audioPublisher,
+ color: self.modeColor
)
.frame(width: 80, height: 22)
-
+
// Mode label - shimmer effect when processing
- if contentState.isProcessing {
- ShimmerText(text: processingLabel, color: modeColor)
+ if self.contentState.isProcessing {
+ ShimmerText(text: self.processingLabel, color: self.modeColor)
} else {
- Text(modeLabel)
+ Text(self.modeLabel)
.font(.system(size: 9, weight: .medium))
- .foregroundStyle(modeColor)
+ .foregroundStyle(self.modeColor)
.opacity(0.9)
}
}
-
+
// Transcription preview (single line, minimal)
- if hasTranscription && !contentState.isProcessing {
- Text(contentState.cachedLine2)
+ if self.hasTranscription && !self.contentState.isProcessing {
+ Text(self.contentState.cachedLine2)
.font(.system(size: 10, weight: .medium))
.foregroundStyle(.white.opacity(0.75))
.lineLimit(1)
@@ -286,10 +280,10 @@ struct NotchExpandedView: View {
.padding(.horizontal, 8)
.padding(.vertical, 6)
.background(Color.black)
- .contentShape(Rectangle()) // Make entire area tappable
+ .contentShape(Rectangle()) // Make entire area tappable
.onTapGesture {
// If in command mode with history, clicking expands the conversation
- if canExpandCommandHistory {
+ if self.canExpandCommandHistory {
NotchOverlayManager.shared.onNotchClicked?()
}
}
@@ -304,131 +298,142 @@ struct NotchExpandedView: View {
struct NotchWaveformView: View {
let audioPublisher: AnyPublisher<CGFloat, Never>
let color: Color
-
+
@StateObject private var data: AudioVisualizationData
@ObservedObject private var contentState = NotchContentState.shared
@State private var barHeights: [CGFloat] = Array(repeating: 3, count: 7)
- @State private var glowPhase: CGFloat = 0 // 0 to 1, controls glow intensity
+ @State private var glowPhase: CGFloat = 0 // 0 to 1, controls glow intensity
@State private var glowTimer: Timer? = nil
- @State private var noiseThreshold: CGFloat = CGFloat(SettingsStore.shared.visualizerNoiseThreshold)
-
+ @State private var noiseThreshold: CGFloat = .init(SettingsStore.shared.visualizerNoiseThreshold)
+
private let barCount = 7
private let barWidth: CGFloat = 3
private let barSpacing: CGFloat = 4
private let minHeight: CGFloat = 3
private let maxHeight: CGFloat = 20
-
+
// 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
}
-
+
private var currentGlowRadius: CGFloat {
contentState.isProcessing ? 2 + 4 * sin(glowPhase * .pi * 2) : 2
}
-
+
private var currentOuterGlowRadius: CGFloat {
contentState.isProcessing ? 6 * sin(glowPhase * .pi * 2) : 0
}
-
+
init(audioPublisher: AnyPublisher<CGFloat, Never>, color: Color, isProcessing: Bool = false) {
self.audioPublisher = audioPublisher
self.color = color
- self._data = StateObject(wrappedValue: AudioVisualizationData(audioLevelPublisher: audioPublisher))
+ _data = StateObject(wrappedValue: AudioVisualizationData(audioLevelPublisher: audioPublisher))
}
-
+
var body: some View {
HStack(spacing: barSpacing) {
- ForEach(0..<barCount, id: \.self) { index in
- RoundedRectangle(cornerRadius: barWidth / 2)
- .fill(color)
- .frame(width: barWidth, height: barHeights[index])
- .shadow(color: color.opacity(currentGlowIntensity), radius: currentGlowRadius, x: 0, y: 0)
- .shadow(color: color.opacity(currentGlowIntensity * 0.5), radius: currentOuterGlowRadius, x: 0, y: 0)
+ ForEach(0..<self.barCount, id: \.self) { index in
+ RoundedRectangle(cornerRadius: self.barWidth / 2)
+ .fill(self.color)
+ .frame(width: self.barWidth, height: self.barHeights[index])
+ .shadow(
+ color: self.color.opacity(self.currentGlowIntensity),
+ radius: self.currentGlowRadius,
+ x: 0,
+ y: 0
+ )
+ .shadow(
+ color: self.color.opacity(self.currentGlowIntensity * 0.5),
+ radius: self.currentOuterGlowRadius,
+ x: 0,
+ y: 0
+ )
}
}
.onChange(of: data.audioLevel) { _, level in
- if !contentState.isProcessing {
- updateBars(level: level)
+ if !self.contentState.isProcessing {
+ self.updateBars(level: level)
}
}
.onChange(of: contentState.isProcessing) { _, processing in
if processing {
- setStaticProcessingBars()
- startGlowAnimation()
+ self.setStaticProcessingBars()
+ self.startGlowAnimation()
} else {
- stopGlowAnimation()
+ self.stopGlowAnimation()
}
}
.onAppear {
- if contentState.isProcessing {
- setStaticProcessingBars()
- startGlowAnimation()
+ if self.contentState.isProcessing {
+ self.setStaticProcessingBars()
+ self.startGlowAnimation()
} else {
- updateBars(level: 0)
+ self.updateBars(level: 0)
}
}
.onDisappear {
- stopGlowAnimation()
+ self.stopGlowAnimation()
}
.onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in
// Update threshold when user changes sensitivity setting
let newThreshold = CGFloat(SettingsStore.shared.visualizerNoiseThreshold)
- if newThreshold != noiseThreshold {
- noiseThreshold = newThreshold
+ if newThreshold != self.noiseThreshold {
+ self.noiseThreshold = newThreshold
}
}
}
-
+
private func startGlowAnimation() {
stopGlowAnimation() // Clean up any existing timer
glowPhase = 0
-
+
// Timer-based animation for explicit control
glowTimer = Timer.scheduledTimer(withTimeInterval: 1.0 / 30.0, repeats: true) { _ in
withAnimation(.linear(duration: 1.0 / 30.0)) {
- glowPhase += 1.0 / 30.0 / 1.5 // Complete cycle in 1.5 seconds
- if glowPhase >= 1.0 {
- glowPhase = 0
+ self.glowPhase += 1.0 / 30.0 / 1.5 // Complete cycle in 1.5 seconds
+ if self.glowPhase >= 1.0 {
+ self.glowPhase = 0
}
}
}
}
-
+
private func stopGlowAnimation() {
glowTimer?.invalidate()
glowTimer = nil
glowPhase = 0
}
-
+
private func setStaticProcessingBars() {
// Set bars to a nice static shape (taller in center)
withAnimation(.easeInOut(duration: 0.3)) {
- for i in 0..<barCount {
- let centerDistance = abs(CGFloat(i) - CGFloat(barCount - 1) / 2)
- let centerFactor = 1.0 - (centerDistance / CGFloat(barCount / 2)) * 0.4
- barHeights[i] = minHeight + (maxHeight - minHeight) * 0.5 * centerFactor
+ for i in 0..<self.barCount {
+ let centerDistance = abs(CGFloat(i) - CGFloat(self.barCount - 1) / 2)
+ let centerFactor = 1.0 - (centerDistance / CGFloat(self.barCount / 2)) * 0.4
+ self.barHeights[i] = self.minHeight + (self.maxHeight - self.minHeight) * 0.5 * centerFactor
}
}
}
-
+
private func updateBars(level: CGFloat) {
let normalizedLevel = min(max(level, 0), 1)
- let isActive = normalizedLevel > noiseThreshold // Use user's sensitivity setting
-
+ let isActive = normalizedLevel > noiseThreshold // Use user's sensitivity setting
+
withAnimation(.spring(response: 0.15, dampingFraction: 0.6)) {
- for i in 0..<barCount {
- let centerDistance = abs(CGFloat(i) - CGFloat(barCount - 1) / 2)
- let centerFactor = 1.0 - (centerDistance / CGFloat(barCount / 2)) * 0.4
-
+ for i in 0..<self.barCount {
+ let centerDistance = abs(CGFloat(i) - CGFloat(self.barCount - 1) / 2)
+ let centerFactor = 1.0 - (centerDistance / CGFloat(self.barCount / 2)) * 0.4
+
if isActive {
// Scale audio level relative to threshold for smoother response
- let adjustedLevel = (normalizedLevel - noiseThreshold) / (1.0 - noiseThreshold)
+ let adjustedLevel = (normalizedLevel - self.noiseThreshold) / (1.0 - self.noiseThreshold)
let randomVariation = CGFloat.random(in: 0.7...1.0)
- barHeights[i] = minHeight + (maxHeight - minHeight) * adjustedLevel * centerFactor * randomVariation
+ self.barHeights[i] = self
+ .minHeight + (self.maxHeight - self.minHeight) * adjustedLevel * centerFactor * randomVariation
} else {
// Complete stillness when below threshold
- barHeights[i] = minHeight
+ self.barHeights[i] = self.minHeight
}
}
}
@@ -440,22 +445,22 @@ struct NotchWaveformView: View {
struct NotchCompactLeadingView: View {
@ObservedObject private var contentState = NotchContentState.shared
@State private var isPulsing = false
-
+
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)
- .onAppear { isPulsing = true }
- .onDisappear { isPulsing = false }
+ .onAppear { self.isPulsing = true }
+ .onDisappear { self.isPulsing = false }
}
}
struct NotchCompactTrailingView: View {
@ObservedObject private var contentState = NotchContentState.shared
@State private var isPulsing = false
-
+
var body: some View {
Circle()
.fill(contentState.mode.notchColor)
@@ -463,8 +468,8 @@ struct NotchCompactTrailingView: View {
.opacity(isPulsing ? 0.5 : 1.0)
.scaleEffect(isPulsing ? 0.85 : 1.0)
.animation(.easeInOut(duration: 1.0).repeatForever(autoreverses: true), value: isPulsing)
- .onAppear { isPulsing = true }
- .onDisappear { isPulsing = false }
+ .onAppear { self.isPulsing = true }
+ .onDisappear { self.isPulsing = false }
}
}
@@ -477,7 +482,7 @@ struct NotchCommandOutputExpandedView: View {
let onNewChat: () -> Void
let onSwitchChat: (String) -> Void
let onClearChat: () -> Void
-
+
@ObservedObject private var contentState = NotchContentState.shared
@State private var inputText: String = ""
@FocusState private var isInputFocused: Bool
@@ -486,129 +491,134 @@ struct NotchCommandOutputExpandedView: View {
@State private var isHoveringRecent = false
@State private var isHoveringClear = false
@State private var isHoveringDismiss = false
-
+
private let commandRed = Color(red: 1.0, green: 0.35, blue: 0.35)
-
+
// Dynamic height based on content (max half screen)
private var dynamicHeight: CGFloat {
- let baseHeight: CGFloat = 120 // Minimum height
+ let baseHeight: CGFloat = 120 // Minimum height
let contentHeight = estimateContentHeight()
- let maxHeight = (NSScreen.main?.frame.height ?? 800) * 0.45 // 45% of screen
+ let maxHeight = (NSScreen.main?.frame.height ?? 800) * 0.45 // 45% of screen
return min(max(baseHeight, contentHeight), maxHeight)
}
-
+
private func estimateContentHeight() -> CGFloat {
- var height: CGFloat = 80 // Header + input area
-
+ var height: CGFloat = 80 // Header + input area
+
// Estimate based on conversation history
for message in contentState.commandConversationHistory {
- let lineCount = max(1, message.content.count / 60) // ~60 chars per line
- height += CGFloat(lineCount) * 18 + 16 // Line height + padding
+ 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 {
let lineCount = max(1, contentState.commandStreamingText.count / 60)
height += CGFloat(lineCount) * 18 + 16
}
-
+
return height
}
-
+
var body: some View {
VStack(spacing: 0) {
// Header with waveform and dismiss
- headerView
-
+ self.headerView
+
// Transcription preview (shown while recording)
- transcriptionPreview
-
+ self.transcriptionPreview
+
Divider()
- .background(commandRed.opacity(0.3))
-
+ .background(self.commandRed.opacity(0.3))
+
// Scrollable conversation area
- conversationArea
-
+ self.conversationArea
+
// Input area for follow-up commands
- inputArea
+ self.inputArea
}
.frame(width: 380, height: dynamicHeight)
.background(Color.black)
.clipShape(RoundedRectangle(cornerRadius: 16))
- .animation(.spring(response: 0.3, dampingFraction: 0.8), value: contentState.commandConversationHistory.count)
+ .animation(
+ .spring(response: 0.3, dampingFraction: 0.8),
+ value: 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)
}
-
+
// MARK: - Header
-
+
private var headerView: some View {
HStack(spacing: 8) {
// Left: Waveform + Mode label
HStack(spacing: 6) {
// Waveform - only show when recording, otherwise show static indicator
- if contentState.isRecordingInExpandedMode {
- ExpandedModeWaveformView(color: commandRed)
+ if self.contentState.isRecordingInExpandedMode {
+ ExpandedModeWaveformView(color: self.commandRed)
.frame(width: 50, height: 18)
} else {
// Static indicator when not recording
HStack(spacing: 3) {
ForEach(0..<5, id: \.self) { _ in
RoundedRectangle(cornerRadius: 1.5)
- .fill(commandRed.opacity(0.4))
+ .fill(self.commandRed.opacity(0.4))
.frame(width: 3, height: 6)
}
}
.frame(width: 50, height: 18)
}
-
+
// Mode label
- if contentState.isRecordingInExpandedMode {
+ if self.contentState.isRecordingInExpandedMode {
Text("Listening...")
.font(.system(size: 11, weight: .medium))
- .foregroundStyle(commandRed)
- } else if contentState.isCommandProcessing {
- ShimmerText(text: "Working...", color: commandRed)
+ .foregroundStyle(self.commandRed)
+ } else if self.contentState.isCommandProcessing {
+ ShimmerText(text: "Working...", color: self.commandRed)
} else {
Text("Command")
.font(.system(size: 11, weight: .medium))
- .foregroundStyle(commandRed.opacity(0.7))
+ .foregroundStyle(self.commandRed.opacity(0.7))
}
}
-
+
Spacer()
-
+
// Right: Chat management buttons + Dismiss
HStack(spacing: 6) {
// New Chat Button (+)
- Button(action: onNewChat) {
+ Button(action: self.onNewChat) {
ZStack {
Circle()
- .fill(isHoveringNewChat ? commandRed.opacity(0.25) : commandRed.opacity(0.12))
+ .fill(self.isHoveringNewChat ? self.commandRed.opacity(0.25) : self.commandRed
+ .opacity(0.12))
.frame(width: 22, height: 22)
Image(systemName: "plus")
.font(.system(size: 10, weight: .semibold))
- .foregroundStyle(contentState.isCommandProcessing ? .white.opacity(0.3) : commandRed.opacity(0.85))
+ .foregroundStyle(self.contentState.isCommandProcessing ? .white.opacity(0.3) : self
+ .commandRed.opacity(0.85))
}
}
.buttonStyle(.plain)
.contentShape(Circle())
- .onHover { isHoveringNewChat = $0 }
- .disabled(contentState.isCommandProcessing)
+ .onHover { self.isHoveringNewChat = $0 }
+ .disabled(self.contentState.isCommandProcessing)
.help("New chat")
-
+
// Recent Chats Menu
Menu {
- let recentChats = contentState.recentChats
+ let recentChats = self.contentState.recentChats
let currentID = ChatHistoryStore.shared.currentChatID
if recentChats.isEmpty {
Text("No recent chats")
.foregroundStyle(.secondary)
} else {
ForEach(recentChats) { chat in
- Button(action: {
+ Button(action: {
if chat.id != currentID {
- onSwitchChat(chat.id)
+ self.onSwitchChat(chat.id)
}
}) {
HStack {
@@ -624,86 +634,88 @@ struct NotchCommandOutputExpandedView: View {
.foregroundStyle(.secondary)
}
}
- .disabled(contentState.isCommandProcessing)
+ .disabled(self.contentState.isCommandProcessing)
}
}
} label: {
ZStack {
Circle()
- .fill(isHoveringRecent ? commandRed.opacity(0.25) : commandRed.opacity(0.12))
+ .fill(self.isHoveringRecent ? self.commandRed.opacity(0.25) : self.commandRed.opacity(0.12))
.frame(width: 22, height: 22)
Image(systemName: "clock.arrow.circlepath")
.font(.system(size: 9, weight: .semibold))
- .foregroundStyle(commandRed.opacity(0.85))
+ .foregroundStyle(self.commandRed.opacity(0.85))
}
}
.menuIndicator(.hidden)
.menuStyle(.button)
.buttonStyle(.plain)
.frame(width: 22, height: 22)
- .onHover { isHoveringRecent = $0 }
+ .onHover { self.isHoveringRecent = $0 }
.help("Recent chats")
-
+
// Delete Chat Button - deletes the current chat entirely
- Button(action: onClearChat) {
+ Button(action: self.onClearChat) {
ZStack {
Circle()
- .fill(isHoveringClear ? commandRed.opacity(0.25) : commandRed.opacity(0.12))
+ .fill(self.isHoveringClear ? self.commandRed.opacity(0.25) : self.commandRed.opacity(0.12))
.frame(width: 22, height: 22)
Image(systemName: "trash")
.font(.system(size: 9, weight: .semibold))
- .foregroundStyle(contentState.isCommandProcessing ? .white.opacity(0.3) : commandRed.opacity(0.85))
+ .foregroundStyle(self.contentState.isCommandProcessing ? .white.opacity(0.3) : self
+ .commandRed.opacity(0.85))
}
}
.buttonStyle(.plain)
.contentShape(Circle())
- .onHover { isHoveringClear = $0 }
- .disabled(contentState.isCommandProcessing)
+ .onHover { self.isHoveringClear = $0 }
+ .disabled(self.contentState.isCommandProcessing)
.help("Delete chat")
-
+
// Vertical divider
Rectangle()
.fill(.white.opacity(0.15))
.frame(width: 1, height: 14)
.padding(.horizontal, 2)
-
+
// Dismiss Button (X)
- Button(action: onDismiss) {
+ Button(action: self.onDismiss) {
ZStack {
Circle()
- .fill(isHoveringDismiss ? commandRed.opacity(0.25) : commandRed.opacity(0.12))
+ .fill(self.isHoveringDismiss ? self.commandRed.opacity(0.25) : self.commandRed
+ .opacity(0.12))
.frame(width: 22, height: 22)
Image(systemName: "xmark")
.font(.system(size: 9, weight: .bold))
- .foregroundStyle(commandRed.opacity(0.85))
+ .foregroundStyle(self.commandRed.opacity(0.85))
}
}
.buttonStyle(.plain)
.contentShape(Circle())
- .onHover { isHoveringDismiss = $0 }
+ .onHover { self.isHoveringDismiss = $0 }
.help("Close (Escape)")
}
}
.padding(.horizontal, 12)
.padding(.vertical, 8)
.onAppear {
- contentState.refreshRecentChats()
+ self.contentState.refreshRecentChats()
}
}
-
+
// MARK: - Transcription Preview (shown while recording)
-
+
private var transcriptionPreview: some View {
Group {
- if contentState.isRecordingInExpandedMode && !contentState.transcriptionText.isEmpty {
+ if self.contentState.isRecordingInExpandedMode && !self.contentState.transcriptionText.isEmpty {
VStack(spacing: 2) {
- if !contentState.cachedLine1.isEmpty {
- Text(contentState.cachedLine1)
+ if !self.contentState.cachedLine1.isEmpty {
+ Text(self.contentState.cachedLine1)
.font(.system(size: 10, weight: .regular))
.foregroundStyle(.white.opacity(0.5))
.lineLimit(1)
}
- Text(contentState.cachedLine2)
+ Text(self.contentState.cachedLine2)
.font(.system(size: 11, weight: .medium))
.foregroundStyle(.white.opacity(0.75))
.lineLimit(1)
@@ -711,60 +723,60 @@ struct NotchCommandOutputExpandedView: View {
.frame(maxWidth: .infinity)
.padding(.horizontal, 12)
.padding(.vertical, 6)
- .background(commandRed.opacity(0.1))
+ .background(self.commandRed.opacity(0.1))
.transition(.opacity.combined(with: .scale(scale: 0.98)))
}
}
.animation(.easeInOut(duration: 0.2), value: contentState.isRecordingInExpandedMode)
.animation(.easeInOut(duration: 0.15), value: contentState.transcriptionText)
}
-
+
// MARK: - Conversation Area
-
+
private var conversationArea: some View {
ScrollViewReader { proxy in
ScrollView(.vertical, showsIndicators: true) {
LazyVStack(alignment: .leading, spacing: 8) {
- ForEach(contentState.commandConversationHistory) { message in
- messageView(for: message)
+ ForEach(self.contentState.commandConversationHistory) { message in
+ self.messageView(for: message)
.id(message.id)
}
-
+
// Streaming text (real-time)
- if !contentState.commandStreamingText.isEmpty {
- streamingMessageView
+ if !self.contentState.commandStreamingText.isEmpty {
+ self.streamingMessageView
.id("streaming")
}
-
+
// Processing indicator
- if contentState.isCommandProcessing && contentState.commandStreamingText.isEmpty {
- processingIndicator
+ if self.contentState.isCommandProcessing && self.contentState.commandStreamingText.isEmpty {
+ self.processingIndicator
.id("processing")
}
-
+
Color.clear.frame(height: 1).id("bottom")
}
.padding(.horizontal, 12)
.padding(.vertical, 8)
}
.onAppear {
- scrollProxy = proxy
+ self.scrollProxy = proxy
// Always scroll to bottom when view appears
- scrollToBottom(proxy, animated: false)
+ self.scrollToBottom(proxy, animated: false)
}
- .onChange(of: contentState.commandConversationHistory.count) { _, _ in
- scrollToBottom(proxy, animated: true)
+ .onChange(of: self.contentState.commandConversationHistory.count) { _, _ in
+ self.scrollToBottom(proxy, animated: true)
}
- .onChange(of: contentState.commandStreamingText) { _, _ in
- scrollToBottom(proxy, animated: true)
+ .onChange(of: self.contentState.commandStreamingText) { _, _ in
+ self.scrollToBottom(proxy, animated: true)
}
- .onChange(of: contentState.isCommandProcessing) { _, _ in
+ .onChange(of: self.contentState.isCommandProcessing) { _, _ in
// Scroll when processing state changes
- scrollToBottom(proxy, animated: true)
+ self.scrollToBottom(proxy, animated: true)
}
}
}
-
+
private func scrollToBottom(_ proxy: ScrollViewProxy, animated: Bool = true) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
if animated {
@@ -776,9 +788,9 @@ struct NotchCommandOutputExpandedView: View {
}
}
}
-
+
// MARK: - Message Views
-
+
private func messageView(for message: NotchContentState.CommandOutputMessage) -> some View {
HStack(alignment: .top, spacing: 6) {
switch message.role {
@@ -789,11 +801,11 @@ struct NotchCommandOutputExpandedView: View {
.foregroundStyle(.white.opacity(0.9))
.padding(.horizontal, 10)
.padding(.vertical, 6)
- .background(commandRed.opacity(0.25))
+ .background(self.commandRed.opacity(0.25))
.cornerRadius(8)
.frame(maxWidth: 280, alignment: .trailing)
.textSelection(.enabled)
-
+
case .assistant:
Text(message.content)
.font(.system(size: 11))
@@ -805,11 +817,11 @@ struct NotchCommandOutputExpandedView: View {
.frame(maxWidth: 320, alignment: .leading)
.textSelection(.enabled)
Spacer()
-
+
case .status:
HStack(spacing: 4) {
Circle()
- .fill(commandRed.opacity(0.6))
+ .fill(self.commandRed.opacity(0.6))
.frame(width: 4, height: 4)
Text(message.content)
.font(.system(size: 10, weight: .medium))
@@ -820,10 +832,10 @@ struct NotchCommandOutputExpandedView: View {
}
}
}
-
+
private var streamingMessageView: some View {
HStack(alignment: .top) {
- Text(contentState.commandStreamingText)
+ Text(self.contentState.commandStreamingText)
.font(.system(size: 11))
.foregroundStyle(.white.opacity(0.85))
.padding(.horizontal, 10)
@@ -831,37 +843,37 @@ struct NotchCommandOutputExpandedView: View {
.background(Color.white.opacity(0.08))
.cornerRadius(8)
.frame(maxWidth: 320, alignment: .leading)
- .drawingGroup() // Flatten to bitmap for faster streaming updates
- // textSelection disabled during streaming for performance
+ .drawingGroup() // Flatten to bitmap for faster streaming updates
+ // textSelection disabled during streaming for performance
Spacer()
}
}
-
+
private var processingIndicator: some View {
HStack(spacing: 6) {
ForEach(0..<3, id: \.self) { index in
Circle()
- .fill(commandRed.opacity(0.6))
+ .fill(self.commandRed.opacity(0.6))
.frame(width: 4, height: 4)
- .offset(y: processingOffset(for: index))
+ .offset(y: self.processingOffset(for: index))
}
}
.padding(.vertical, 4)
}
-
+
@State private var processingAnimation = false
-
+
private func processingOffset(for index: Int) -> CGFloat {
// Offset varies by index for staggered animation effect
- _ = Double(index) * 0.15 // Reserved for future animation timing
+ _ = Double(index) * 0.15 // Reserved for future animation timing
return processingAnimation ? -3 : 3
}
-
+
// MARK: - Input Area
-
+
private var inputArea: some View {
HStack(spacing: 8) {
- TextField("Ask follow-up...", text: $inputText)
+ TextField("Ask follow-up...", text: self.$inputText)
.textFieldStyle(.plain)
.font(.system(size: 11))
.foregroundStyle(.white)
@@ -869,31 +881,31 @@ struct NotchCommandOutputExpandedView: View {
.padding(.vertical, 6)
.background(Color.white.opacity(0.08))
.cornerRadius(8)
- .focused($isInputFocused)
+ .focused(self.$isInputFocused)
.onSubmit {
- submitFollowUp()
+ self.submitFollowUp()
}
-
- Button(action: submitFollowUp) {
+
+ Button(action: self.submitFollowUp) {
Image(systemName: "arrow.up.circle.fill")
.font(.system(size: 16))
- .foregroundStyle(inputText.isEmpty ? .white.opacity(0.3) : commandRed)
+ .foregroundStyle(self.inputText.isEmpty ? .white.opacity(0.3) : self.commandRed)
}
.buttonStyle(.plain)
- .disabled(inputText.isEmpty || contentState.isCommandProcessing)
+ .disabled(self.inputText.isEmpty || self.contentState.isCommandProcessing)
}
.padding(.horizontal, 12)
.padding(.vertical, 8)
.background(Color.white.opacity(0.03))
}
-
+
private func submitFollowUp() {
guard !inputText.isEmpty else { return }
let text = inputText
inputText = ""
-
+
Task {
- await onSubmit(text)
+ await self.onSubmit(text)
}
}
}
@@ -902,49 +914,50 @@ struct NotchCommandOutputExpandedView: View {
struct ExpandedModeWaveformView: View {
let color: Color
-
+
@ObservedObject private var contentState = NotchContentState.shared
@State private var barHeights: [CGFloat] = Array(repeating: 3, count: 5)
-
+
private let barCount = 5
private let barWidth: CGFloat = 3
private let barSpacing: CGFloat = 3
private let minHeight: CGFloat = 4
private let maxHeight: CGFloat = 16
private let noiseThreshold: CGFloat = 0.05
-
+
var body: some View {
HStack(spacing: barSpacing) {
- ForEach(0..<barCount, id: \.self) { index in
- RoundedRectangle(cornerRadius: barWidth / 2)
- .fill(color)
- .frame(width: barWidth, height: barHeights[index])
- .shadow(color: color.opacity(0.4), radius: 2, x: 0, y: 0)
+ ForEach(0..<self.barCount, id: \.self) { index in
+ RoundedRectangle(cornerRadius: self.barWidth / 2)
+ .fill(self.color)
+ .frame(width: self.barWidth, height: self.barHeights[index])
+ .shadow(color: self.color.opacity(0.4), radius: 2, x: 0, y: 0)
}
}
.onChange(of: contentState.expandedModeAudioLevel) { _, level in
- updateBars(level: level)
+ self.updateBars(level: level)
}
.onAppear {
- updateBars(level: contentState.expandedModeAudioLevel)
+ self.updateBars(level: self.contentState.expandedModeAudioLevel)
}
}
-
+
private func updateBars(level: CGFloat) {
let normalizedLevel = min(max(level, 0), 1)
let isActive = normalizedLevel > noiseThreshold
-
+
withAnimation(.spring(response: 0.12, dampingFraction: 0.6)) {
- for i in 0..<barCount {
- let centerDistance = abs(CGFloat(i) - CGFloat(barCount - 1) / 2)
- let centerFactor = 1.0 - (centerDistance / CGFloat(barCount / 2)) * 0.35
-
+ for i in 0..<self.barCount {
+ let centerDistance = abs(CGFloat(i) - CGFloat(self.barCount - 1) / 2)
+ let centerFactor = 1.0 - (centerDistance / CGFloat(self.barCount / 2)) * 0.35
+
if isActive {
- let adjustedLevel = (normalizedLevel - noiseThreshold) / (1.0 - noiseThreshold)
+ let adjustedLevel = (normalizedLevel - self.noiseThreshold) / (1.0 - self.noiseThreshold)
let randomVariation = CGFloat.random(in: 0.75...1.0)
- barHeights[i] = minHeight + (maxHeight - minHeight) * adjustedLevel * centerFactor * randomVariation
+ self.barHeights[i] = self
+ .minHeight + (self.maxHeight - self.minHeight) * adjustedLevel * centerFactor * randomVariation
} else {
- barHeights[i] = minHeight
+ self.barHeights[i] = self.minHeight
}
}
}
diff --git a/Sources/Fluid/Views/RewriteModeView.swift b/Sources/Fluid/Views/RewriteModeView.swift
index 09e5d459..6f1d2f71 100644
--- a/Sources/Fluid/Views/RewriteModeView.swift
+++ b/Sources/Fluid/Views/RewriteModeView.swift
@@ -7,15 +7,15 @@ struct RewriteModeView: View {
@ObservedObject var settings = SettingsStore.shared
@EnvironmentObject var menuBarManager: MenuBarManager
var onClose: (() -> Void)?
-
+
@State private var inputText: String = ""
@State private var showOriginal: Bool = true
@State private var showHowTo: Bool = false
@State private var isHoveringHowTo: Bool = false
-
+
// Local state for available models (derived from shared AI Settings pool)
@State private var availableModels: [String] = []
-
+
var body: some View {
VStack(spacing: 0) {
// Header - cleaner, just title and close
@@ -26,10 +26,10 @@ struct RewriteModeView: View {
Text("Write Mode")
.font(.title2)
.fontWeight(.bold)
-
+
Spacer()
-
- Button(action: { onClose?() }) {
+
+ Button(action: { self.onClose?() }) {
Image(systemName: "xmark.circle.fill")
.foregroundStyle(.secondary)
}
@@ -37,16 +37,16 @@ struct RewriteModeView: View {
}
.padding()
.background(Color(nsColor: .windowBackgroundColor))
-
+
// How To (collapsible)
- howToSection
-
+ self.howToSection
+
Divider()
-
+
ScrollView {
VStack(alignment: .leading, spacing: 16) {
// Original Text Section
- if !service.originalText.isEmpty {
+ if !self.service.originalText.isEmpty {
VStack(alignment: .leading, spacing: 8) {
HStack {
Text("Original Text")
@@ -54,17 +54,17 @@ struct RewriteModeView: View {
.fontWeight(.bold)
.foregroundStyle(.secondary)
Spacer()
- if !service.rewrittenText.isEmpty {
- Button(showOriginal ? "Hide" : "Show") {
- withAnimation { showOriginal.toggle() }
+ if !self.service.rewrittenText.isEmpty {
+ Button(self.showOriginal ? "Hide" : "Show") {
+ withAnimation { self.showOriginal.toggle() }
}
.font(.caption)
.buttonStyle(.link)
}
}
-
- if showOriginal {
- Text(service.originalText)
+
+ if self.showOriginal {
+ Text(self.service.originalText)
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color.gray.opacity(0.1))
@@ -83,7 +83,7 @@ struct RewriteModeView: View {
Text("Ask the AI to write anything for you - emails, replies, summaries, answers, and more.")
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
-
+
Text("Or select text first to rewrite existing content.")
.font(.caption)
.foregroundStyle(.tertiary)
@@ -93,33 +93,33 @@ struct RewriteModeView: View {
.frame(maxWidth: .infinity)
.padding(.vertical, 40)
}
-
+
// Rewritten Text Section
- if !service.rewrittenText.isEmpty {
+ if !self.service.rewrittenText.isEmpty {
VStack(alignment: .leading, spacing: 8) {
Text("Rewritten Text")
.font(.caption)
.fontWeight(.bold)
.foregroundStyle(.green)
-
- Text(service.rewrittenText)
+
+ Text(self.service.rewrittenText)
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color.green.opacity(0.1))
.cornerRadius(8)
.textSelection(.enabled)
-
+
HStack {
Button("Try Again") {
- service.rewrittenText = ""
+ self.service.rewrittenText = ""
}
.buttonStyle(.bordered)
-
+
Spacer()
-
+
Button("Replace Original") {
- service.acceptRewrite()
- onClose?()
+ self.service.acceptRewrite()
+ self.onClose?()
}
.buttonStyle(.borderedProminent)
.tint(.green)
@@ -128,9 +128,11 @@ struct RewriteModeView: View {
}
.transition(.move(edge: .bottom).combined(with: .opacity))
}
-
+
// Conversation History (optional, maybe just last error)
- if let lastMsg = service.conversationHistory.last, lastMsg.role == .assistant, service.rewrittenText.isEmpty {
+ if let lastMsg = service.conversationHistory.last, lastMsg.role == .assistant,
+ service.rewrittenText.isEmpty
+ {
Text(lastMsg.content) // Error message usually
.foregroundStyle(.red)
.padding()
@@ -140,16 +142,16 @@ struct RewriteModeView: View {
}
.padding()
}
-
+
Divider()
-
+
// Input Area with model selectors inline
HStack(spacing: 8) {
// Provider Selector (compact)
- Picker("", selection: $settings.rewriteModeSelectedProviderID) {
+ Picker("", selection: self.$settings.rewriteModeSelectedProviderID) {
Text("OpenAI").tag("openai")
Text("Groq").tag("groq")
-
+
// Apple Intelligence
if AppleIntelligenceService.isAvailable {
Text("Apple Intelligence").tag("apple-intelligence")
@@ -158,57 +160,65 @@ struct RewriteModeView: View {
.foregroundColor(.secondary)
.tag("apple-intelligence-disabled")
}
-
- ForEach(settings.savedProviders) { provider in
+
+ ForEach(self.settings.savedProviders) { provider in
Text(provider.name).tag(provider.id)
}
}
.frame(width: 110)
- .onChange(of: settings.rewriteModeSelectedProviderID) { _, newValue in
+ .onChange(of: self.settings.rewriteModeSelectedProviderID) { _, newValue in
// Prevent selecting disabled Apple Intelligence
if newValue == "apple-intelligence-disabled" {
- settings.rewriteModeSelectedProviderID = "openai"
+ self.settings.rewriteModeSelectedProviderID = "openai"
}
- updateAvailableModels()
+ self.updateAvailableModels()
}
-
+
// Model Selector (hidden for Apple Intelligence)
- if settings.rewriteModeSelectedProviderID != "apple-intelligence" {
- Picker("", selection: Binding(
- get: { settings.rewriteModeSelectedModel ?? availableModels.first ?? "gpt-4o" },
- set: { settings.rewriteModeSelectedModel = $0 }
- )) {
- ForEach(availableModels, id: \.self) { model in
+ if self.settings.rewriteModeSelectedProviderID != "apple-intelligence" {
+ Picker(
+ "",
+ selection: Binding(
+ get: {
+ self.settings.rewriteModeSelectedModel ?? self.availableModels
+ .first ?? "gpt-4o"
+ },
+ set: { self.settings.rewriteModeSelectedModel = $0 }
+ )
+ ) {
+ ForEach(self.availableModels, id: \.self) { model in
Text(model).tag(model)
}
}
.frame(width: 130)
}
-
+
// Input field (flexible)
- TextField(service.originalText.isEmpty
- ? "Ask me to write anything..."
- : "How should I rewrite this?",
- text: $inputText)
- .textFieldStyle(.roundedBorder)
- .onSubmit(submitRequest)
-
- Button(action: submitRequest) {
+ TextField(
+ self.service.originalText.isEmpty
+ ? "Ask me to write anything..."
+ : "How should I rewrite this?",
+ text: self.$inputText
+ )
+ .textFieldStyle(.roundedBorder)
+ .onSubmit(self.submitRequest)
+
+ Button(action: self.submitRequest) {
Image(systemName: "arrow.up.circle.fill")
.font(.title2)
}
.buttonStyle(.plain)
- .disabled(inputText.isEmpty || service.isProcessing)
-
+ .disabled(self.inputText.isEmpty || self.service.isProcessing)
+
// Voice Input
- Button(action: toggleRecording) {
- Image(systemName: asr.isRunning ? "stop.circle.fill" : "mic.circle.fill")
+ Button(action: self.toggleRecording) {
+ Image(systemName: self.asr.isRunning ? "stop.circle.fill" : "mic.circle.fill")
.font(.title2)
- .foregroundStyle(asr.isRunning ? Color.red : Color.accentColor)
+ .foregroundStyle(self.asr.isRunning ? Color.red : Color.accentColor)
}
.buttonStyle(.plain)
-
- if service.isProcessing {
+
+ if self.service.isProcessing {
ProgressView()
.controlSize(.small)
}
@@ -218,78 +228,78 @@ struct RewriteModeView: View {
}
.onChange(of: asr.finalText) { _, newText in
if !newText.isEmpty {
- inputText = newText
+ self.inputText = newText
}
}
.onExitCommand {
- onClose?()
+ self.onClose?()
}
.onAppear {
// Note: Overlay mode is now set centrally by ContentView.handleModeTransition()
- updateAvailableModels()
+ self.updateAvailableModels()
}
// Note: onDisappear overlay mode handling removed - now handled centrally by ContentView
}
-
+
private func toggleRecording() {
if asr.isRunning {
- Task { await asr.stop() }
+ Task { await self.asr.stop() }
} else {
asr.start()
}
}
-
+
private func submitRequest() {
guard !inputText.isEmpty else { return }
let prompt = inputText
inputText = ""
Task {
- await service.processRewriteRequest(prompt)
+ await self.service.processRewriteRequest(prompt)
}
}
-
+
// MARK: - Model Management (pulls from shared AI Settings pool)
-
+
private func updateAvailableModels() {
let currentProviderID = settings.rewriteModeSelectedProviderID
let currentModel = settings.rewriteModeSelectedModel ?? "gpt-4o"
-
+
// Apple Intelligence has only one model
if currentProviderID == "apple-intelligence" {
availableModels = ["System Model"]
return
}
-
+
// Pull models from the shared pool configured in AI Settings
let possibleKeys = providerKeys(for: currentProviderID)
let storedList = possibleKeys.lazy
.compactMap { SettingsStore.shared.availableModelsByProvider[$0] }
.first { !$0.isEmpty }
-
+
if let stored = storedList {
availableModels = stored
} else {
availableModels = defaultModels(for: currentProviderID)
}
-
+
// If current model not in list, select first available
if !availableModels.contains(currentModel) {
settings.rewriteModeSelectedModel = availableModels.first ?? "gpt-4o"
}
}
-
+
private func providerKeys(for providerID: String) -> [String] {
var keys: [String] = []
let trimmed = providerID.trimmingCharacters(in: .whitespacesAndNewlines)
-
+
if trimmed.isEmpty {
return [providerID]
}
-
+
if trimmed == "openai" || trimmed == "groq" {
return [trimmed]
}
-
+
if trimmed.hasPrefix("custom:") {
keys.append(trimmed)
keys.append(String(trimmed.dropFirst("custom:".count)))
@@ -297,10 +307,10 @@ struct RewriteModeView: View {
keys.append("custom:\(trimmed)")
keys.append(trimmed)
}
-
+
return Array(Set(keys))
}
-
+
private func defaultModels(for provider: String) -> [String] {
switch provider {
case "openai": return ["gpt-4.1"]
@@ -309,38 +319,38 @@ struct RewriteModeView: View {
default: return ["gpt-4.1"]
}
}
-
+
// MARK: - How To Section
-
+
private var shortcutDisplay: String {
settings.rewriteModeHotkeyShortcut.displayString
}
-
+
private var howToSection: some View {
VStack(spacing: 0) {
// Toggle button with hover effect
- Button(action: { withAnimation(.easeInOut(duration: 0.2)) { showHowTo.toggle() } }) {
+ Button(action: { withAnimation(.easeInOut(duration: 0.2)) { self.showHowTo.toggle() } }) {
HStack {
Image(systemName: "questionmark.circle")
.font(.caption)
Text("How to use")
.font(.caption)
Spacer()
- Image(systemName: showHowTo ? "chevron.up" : "chevron.down")
+ Image(systemName: self.showHowTo ? "chevron.up" : "chevron.down")
.font(.caption2)
}
- .foregroundStyle(isHoveringHowTo ? .primary : .secondary)
+ .foregroundStyle(self.isHoveringHowTo ? .primary : .secondary)
.padding(.horizontal, 16)
.padding(.vertical, 8)
- .background(isHoveringHowTo ? Color.primary.opacity(0.05) : Color.clear)
+ .background(self.isHoveringHowTo ? Color.primary.opacity(0.05) : Color.clear)
.cornerRadius(4)
}
.buttonStyle(.plain)
.onHover { hovering in
- withAnimation(.easeInOut(duration: 0.15)) { isHoveringHowTo = hovering }
+ withAnimation(.easeInOut(duration: 0.15)) { self.isHoveringHowTo = hovering }
}
-
- if showHowTo {
+
+ if self.showHowTo {
VStack(alignment: .leading, spacing: 12) {
// Write fresh
VStack(alignment: .leading, spacing: 4) {
@@ -348,11 +358,11 @@ struct RewriteModeView: View {
.font(.caption)
.fontWeight(.semibold)
.foregroundStyle(.secondary)
-
+
HStack(spacing: 4) {
Text("Press")
.font(.caption)
- Text(shortcutDisplay)
+ Text(self.shortcutDisplay)
.font(.caption)
.fontWeight(.medium)
.padding(.horizontal, 6)
@@ -363,22 +373,22 @@ struct RewriteModeView: View {
.font(.caption)
}
.foregroundStyle(.primary.opacity(0.8))
-
- howToItem("\"Write an email asking for time off\"")
- howToItem("\"Draft a thank you note\"")
+
+ self.howToItem("\"Write an email asking for time off\"")
+ self.howToItem("\"Draft a thank you note\"")
}
-
+
// Rewrite
VStack(alignment: .leading, spacing: 4) {
Text("To Rewrite/Edit")
.font(.caption)
.fontWeight(.semibold)
.foregroundStyle(.secondary)
-
+
HStack(spacing: 4) {
Text("Select text first, then press")
.font(.caption)
- Text(shortcutDisplay)
+ Text(self.shortcutDisplay)
.font(.caption)
.fontWeight(.medium)
.padding(.horizontal, 6)
@@ -389,10 +399,10 @@ struct RewriteModeView: View {
.font(.caption)
}
.foregroundStyle(.primary.opacity(0.8))
-
- howToItem("\"Make this more formal\"")
- howToItem("\"Fix grammar and spelling\"")
- howToItem("\"Summarize this\"")
+
+ self.howToItem("\"Make this more formal\"")
+ self.howToItem("\"Fix grammar and spelling\"")
+ self.howToItem("\"Summarize this\"")
}
}
.padding(.horizontal, 16)
@@ -402,7 +412,7 @@ struct RewriteModeView: View {
}
.background(Color(nsColor: .windowBackgroundColor).opacity(0.5))
}
-
+
private func howToItem(_ text: String) -> some View {
HStack(spacing: 6) {
Text("•")
diff --git a/Sources/Fluid/fluidApp.swift b/Sources/Fluid/fluidApp.swift
index bddd69f5..e1be3436 100644
--- a/Sources/Fluid/fluidApp.swift
+++ b/Sources/Fluid/fluidApp.swift
@@ -1,13 +1,6 @@
-//
-// fluidApp.swift
-// fluid
-//
-// Created by Barathwaj Anandan on 7/30/25.
-//
-
-import SwiftUI
import AppKit
import ApplicationServices
+import SwiftUI
@main
struct fluidApp: App {
@@ -19,9 +12,9 @@ struct fluidApp: App {
var body: some Scene {
WindowGroup(id: "main") {
ContentView()
- .environmentObject(menuBarManager)
- .environmentObject(appServices)
- .appTheme(theme)
+ .environmentObject(self.menuBarManager)
+ .environmentObject(self.appServices)
+ .appTheme(self.theme)
.preferredColorScheme(.dark)
}
.defaultSize(width: 1000, height: 700)