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
Initial commit: Clean Fluid dictation app structure
grohith32736f5d8e375cd
diff --git a/.gitignore b/.gitignorenew file mode 100644index 00000000..000d823b--- /dev/null+++ b/.gitignore@@ -0,0 +1,162 @@+# Xcode+#+# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore++## User settings+xcuserdata/++## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)+*.xcscmblueprint+*.xccheckout++## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)+build/+DerivedData/+*.moved-aside+*.pbxuser+!default.pbxuser+*.mode1v3+!default.mode1v3+*.mode2v3+!default.mode2v3+*.perspectivev3+!default.perspectivev3++## Gcc Patch+/*.gcno++## Build artifacts+*.app+*.ipa+*.xcarchive+*.dSYM.zip+*.dSYM++## Swift Package Manager+#+# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.+# Packages/+# Package.pins+# Package.resolved+# *.xcodeproj+# Xcode automatically generates this directory with a .gitignore file,+# so you don't have to add this. SwiftPM generates it at the root of your project.+# .swiftpm/++## Playgrounds+timeline.xctimeline+playground.xcuserstate++# CocoaPods+#+# We recommend against adding the Pods directory to your .gitignore. However+# you should judge for your own use case.+Pods/+# Add this line if you want to avoid checking in the Pods directory.+# Podfile.lock+# Pods/ to be committed as of CocoaPods 1.1.0++## Carthage+#+# Add this line if you use Carthage for managing dependencies.+Carthage/Checkouts+Carthage/Build/++# Accio dependency management+Dependencies/+.accio/++# fastlane+#+# It is recommended to not store the screenshots in the git repo.+# Instead, use fastlane to re-generate the screenshots when they are needed.+# For more information about the recommended setup visit:+# https://docs.github.com/app/beginning-to-use-github-pages/+# https://docs.github.com/en/developers/+fastlane/report.xml+fastlane/Preview.html+fastlane/screenshots/**/*.png+fastlane/test_output++# Code Injection+#+# After new CODEOWNERS file injection, we recommend to commit the code and disable injections.+iOSInjectionProject/++## Temporary files+*.tmp+*.temp+*.swp+*.swo+*~++## Environment variables and sensitive data+.env+.env.local+.env.development.local+.env.test.local+.env.production.local++## API Keys and Secrets+# Never commit actual API keys+*.key+*.pem+*.p12+secrets.json+config/secrets.yml++## Logs+*.log+logs/++## OS generated files+.DS_Store+.DS_Store?+._*+.Spotlight-V100+.Trashes+ehthumbs.db+Thumbs.db++## macOS+.AppleDouble+.LSOverride++# Icon must end with two \r+Icon++# Thumbnails+._*++# Files that might appear in the root of a volume+.DocumentRevisions-V100+.fseventsd+.Spotlight-V100+.TemporaryItems+.Trashes+.VolumeIcon.icns+.com.apple.timemachine.donotpresent++# Directories potentially created on remote AFP share+.AppleDB+.AppleDesktop+Network Trash Folder+Temporary Items+.apdisk++## Project specific++# Fluid app specific+error.log+*.xcuserstate++# Model cache (should be regenerated)+**/model_cache/+**/models/++# User-specific settings (will be regenerated)+SettingsStore.xcuserstate++# Temporary build files+**/tmp/+**/temp/diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 00000000..1f8242a4--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,107 @@+# Changelog++All notable changes to Fluid will be documented in this file.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),+and this project adheres to [Semantic Versioning](https://semverversioning.org/spec/v2.0.0.html).++## [Unreleased]++### Added+- Comprehensive documentation for all major classes and methods+- MIT license file+- Contributing guidelines for open source collaboration+- README with detailed setup and usage instructions+- .gitignore file for proper version control+- Custom model repository configuration options++### Changed+- Made hardcoded model repository configurable via constructor parameters+- Improved error handling with detailed documentation+- Enhanced code documentation throughout the codebase+- Updated project structure for better organization++### Fixed+- Removed hardcoded sensitive information (usernames, API endpoints)+- Added proper error handling for audio session failures+- Improved thread safety with @MainActor annotations++## [2.1.0] - 2025-01-XX++### Added+- Enhanced audio visualization with customizable noise thresholds+- Improved accessibility support with better keyboard navigation+- Advanced debugging capabilities with structured logging+- Performance optimizations for real-time audio processing++### Changed+- Refactored audio processing pipeline for better performance+- Updated UI components with modern SwiftUI patterns+- Improved model management with automatic caching++### Fixed+- Fixed memory leaks in audio processing+- Resolved accessibility permission handling issues+- Fixed transcription accuracy issues in noisy environments++## [2.0.0] - 2024-12-XX++### Added+- AI processing integration with OpenAI-compatible APIs+- Model management system with automatic downloads+- Advanced audio visualization with real-time feedback+- Global hotkey system with customizable shortcuts+- Settings management with persistent preferences++### Changed+- Complete rewrite of ASR service with modern architecture+- Improved UI with SwiftUI and modern design patterns+- Enhanced error handling and user feedback+- Updated to support latest macOS features++### Fixed+- Fixed audio device detection and switching+- Resolved memory management issues+- Improved transcription accuracy and reliability++## [1.0.0] - 2024-07-XX++### Added+- Basic dictation functionality with real-time transcription+- Menu bar integration+- Simple audio capture and processing+- Basic text insertion capabilities++## [0.1.0] - 2024-01-XX++### Added+- Initial prototype with basic speech recognition+- Proof of concept for macOS dictation+- Core audio processing framework integration++---++## Versioning++Fluid follows semantic versioning:++- **Major version** (x.0.0): Breaking changes or major new features+- **Minor version** (x.y.0): New features, backward compatible+- **Patch version** (x.y.z): Bug fixes, backward compatible++## Release Process++1. Update version number in project settings+2. Update this changelog with changes since last release+3. Tag the release with the version number+4. Create release notes with key features and fixes++## Contributing++When contributing to this project, please update the changelog with your changes:++- Add new features to the "Added" section+- Document breaking changes in "Changed" section+- List bug fixes in the "Fixed" section++For more details, see [CONTRIBUTING.md](CONTRIBUTING.md).diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 00000000..3db1bf1c--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,248 @@+# Contributing to Fluid++Thank you for your interest in contributing to Fluid! We welcome contributions from the community and are excited to collaborate with developers who share our passion for building exceptional macOS applications.++## 🚀 Quick Start++1. **Fork** the repository+2. **Clone** your fork: `git clone https://github.com/your-username/fluid-dictation.git`+3. **Create** a feature branch: `git checkout -b feature/amazing-feature`+4. **Make** your changes following our guidelines+5. **Test** your changes thoroughly+6. **Submit** a pull request++## 📋 Contribution Guidelines++### Code Standards++#### Swift Style Guide+- Follow [Swift API Design Guidelines](https://swift.org/documentation/api-design-guidelines/)+- Use descriptive variable and function names+- Prefer `let` over `var` when possible+- Add comprehensive documentation for public APIs+- Include error handling for all fallible operations++#### Naming Conventions+```swift+// ✅ Good+class SpeechRecognitionService {+ func transcribe(audioData: Data) async throws -> String+}++// ❌ Avoid+class SpeechService {+ func transcribeAudio(data: Data) -> String+}+```++#### Documentation+- Add documentation comments for all public classes, methods, and properties+- Use clear, concise language+- Include parameter descriptions and return value explanations+- Add examples when helpful++```swift+/// Handles speech recognition with real-time transcription capabilities.+/// - Parameter audioData: Raw audio data in PCM format+/// - Returns: Transcribed text from the audio+/// - Throws: `ASRServiceError` if transcription fails+public func transcribe(audioData: Data) async throws -> String+```++### Testing Requirements++#### Unit Tests+- Add unit tests for new functionality+- Test both success and error scenarios+- Mock external dependencies when possible+- Aim for 80%+ code coverage for new features++#### Integration Tests+- Test integration with system APIs (Accessibility, Audio)+- Verify functionality across different macOS versions+- Test with various input devices and configurations++#### Manual Testing Checklist+- [ ] Test with different microphones+- [ ] Verify global hotkey functionality+- [ ] Check text insertion in multiple applications+- [ ] Test AI integration (if applicable)+- [ ] Validate accessibility permissions+- [ ] Test with different audio environments (quiet/noisy)++### Pull Request Process++#### Before Submitting+1. **Test thoroughly** - Ensure your changes work as expected+2. **Update documentation** - Add or update README if needed+3. **Add tests** - Include unit and integration tests+4. **Check formatting** - Use consistent code style+5. **Review changes** - Double-check your implementation++#### PR Template+```markdown+## Description+[Brief description of changes]++## Type of Change+- [ ] Bug fix+- [ ] New feature+- [ ] Breaking change+- [ ] Documentation update++## Testing+- [ ] Added unit tests+- [ ] Tested manually on macOS [version]+- [ ] Verified with different input devices++## Screenshots+[Add screenshots if UI changes are involved]++## Related Issues+Closes #123++## Checklist+- [ ] Follows code style guidelines+- [ ] Tests added/updated+- [ ] Documentation updated+- [ ] Accessibility considered+- [ ] Performance impact assessed+```++### Development Workflow++#### Branch Naming+```+feature/descriptive-feature-name+bugfix/issue-number-description+hotfix/critical-fix-description+docs/update-documentation+```++#### Commit Messages+Use conventional commit format:+```+feat: add new speech recognition model support+fix: resolve crash when accessibility permissions denied+docs: update API documentation for AI providers+test: add unit tests for audio processing+```++## 🛠️ Development Setup++### Prerequisites+- **macOS 12.0+**+- **Xcode 14.0+**+- **Swift 5.7+**++### Local Development+1. Clone the repository+2. Open `dictate_v2.xcodeproj` in Xcode+3. Build the project (`Cmd + B`)+4. Run tests (`Cmd + U`)++### Debugging Tips+- Enable debug logging in Settings → Debug Settings+- Use Xcode's debugging tools (breakpoints, console)+- Check system logs for accessibility-related issues+- Test with different audio input sources++## 🎯 Feature Development++### Adding New AI Providers+1. Implement the `AIProvider` protocol+2. Add to the provider selection UI+3. Include configuration options+4. Add tests for the new provider++### Custom ASR Models+1. Update `HuggingFaceModelDownloader` configuration+2. Test model compatibility+3. Update documentation+4. Add fallback handling++### UI Enhancements+1. Follow SwiftUI design patterns+2. Consider accessibility features+3. Test on different screen sizes+4. Maintain consistent visual style++## 🔒 Security Considerations++### API Keys and Credentials+- Never commit API keys to the repository+- Use environment variables for sensitive data+- Document secure configuration procedures+- Validate input from external sources++### Privacy+- Respect user privacy preferences+- Handle personal data securely+- Follow macOS privacy guidelines+- Document data collection and usage++## 📱 macOS-Specific Guidelines++### Accessibility+- Use proper accessibility labels+- Support keyboard navigation+- Test with VoiceOver+- Follow Apple accessibility guidelines++### System Integration+- Handle permission requests gracefully+- Provide clear error messages+- Support system dark mode+- Follow macOS human interface guidelines++### Performance+- Minimize CPU usage during idle periods+- Efficient memory management+- Optimize audio processing+- Profile performance regularly++## 🤝 Code Review Process++### What We Look For+- **Code quality**: Clean, readable, maintainable code+- **Functionality**: Does it work as intended?+- **Testing**: Comprehensive test coverage+- **Documentation**: Clear and complete+- **Security**: No security vulnerabilities+- **Performance**: Efficient and optimized++### Review Checklist+- [ ] Code follows project style guidelines+- [ ] Functionality works as described+- [ ] Tests are included and passing+- [ ] Documentation is updated+- [ ] No breaking changes without discussion+- [ ] Performance impact assessed+- [ ] Security considerations addressed++## 📞 Communication++### Getting Help+- **Issues**: Use GitHub Issues for bug reports and feature requests+- **Discussions**: Use GitHub Discussions for questions and ideas+- **Email**: For private communications++### Response Times+- **Issues**: We aim to respond within 2-3 business days+- **Pull Requests**: Reviews typically completed within 1 week+- **Security Issues**: Addressed immediately++## 🎉 Recognition++We love to recognize our contributors! Contributors who make significant improvements will be:+- Mentioned in release notes+- Added to the acknowledgments section+- Featured in community updates++## 📄 License++By contributing to Fluid, you agree that your contributions will be licensed under the same license as the original project (MIT License).++---++Thank you for contributing to Fluid! Your efforts help make dictation technology more accessible and powerful for everyone. 🚀diff --git a/ERROR_HANDLING.md b/ERROR_HANDLING.mdnew file mode 100644index 00000000..9ef2f2f5--- /dev/null+++ b/ERROR_HANDLING.md@@ -0,0 +1,326 @@+# Error Handling Guide++This document outlines the comprehensive error handling strategy used in Fluid, ensuring robust operation across various failure scenarios.++## Overview++Fluid implements a multi-layered error handling approach:++1. **Silent Failures**: Non-critical operations that fail gracefully+2. **User Notifications**: Important errors that require user attention+3. **Debug Logging**: Detailed error information for troubleshooting+4. **Recovery Mechanisms**: Automatic error recovery where possible++## Error Categories++### 1. Permission Errors++#### Microphone Access+```swift+func requestMicAccess() {+ AVCaptureDevice.requestAccess(for: .audio) { [weak self] granted in+ Task { @MainActor in+ self?.micStatus = granted ? .authorized : .denied+ if !granted {+ // Show user notification about microphone access+ self?.showMicPermissionError()+ }+ }+ }+}+```++**Handling Strategy:**+- Request permission on first use+- Provide clear instructions for manual permission granting+- Gracefully disable features that require microphone access+- Show helpful error messages with links to System Settings++#### Accessibility Permissions+```swift+private func requestAccessibilityPermissions() {+ guard !AXIsProcessTrusted() else { return }++ let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary+ AXIsProcessTrustedWithOptions(options)++ // Deep link to Accessibility settings if still not trusted+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {+ guard !AXIsProcessTrusted(),+ let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")+ else { return }+ NSWorkspace.shared.open(url)+ }+}+```++**Handling Strategy:**+- Request permissions during app initialization+- Provide automatic deep-linking to System Settings+- Show clear error messages explaining why permissions are needed+- Disable hotkey functionality if permissions are denied++### 2. Audio Processing Errors++#### Audio Engine Failures+```swift+func startEngine() throws {+ var attempts = 0+ while attempts < 3 {+ do {+ try engine.start()+ return+ } catch {+ attempts += 1+ Thread.sleep(forTimeInterval: 0.1)+ engine.reset()+ }+ }+ throw NSError(domain: "ASRService", code: -1, userInfo: [NSLocalizedDescriptionKey: "Failed to start audio engine"])+}+```++**Handling Strategy:**+- Retry mechanism with exponential backoff+- Automatic engine reset on failures+- Clear error messages for user feedback+- Graceful degradation of functionality++#### Device Detection Errors+```swift+private func handleDefaultInputChanged() {+ if isRunning {+ removeEngineTap()+ engine.stop()+ do {+ try configureSession()+ try startEngine()+ setupEngineTap()+ } catch {+ // Log error but don't show to user - audio should continue working+ DebugLogger.shared.warning("Failed to restart audio engine after device change: \(error)", source: "ASRService")+ }+ }+}+```++**Handling Strategy:**+- Silent recovery attempts+- Detailed logging for debugging+- No user interruption during recovery++### 3. Model Management Errors++#### Download Failures+```swift+func ensureModelsPresent(at targetRoot: URL, onProgress: ((Double, String) -> Void)? = nil) async throws {+ try FileManager.default.createDirectory(at: targetRoot, withIntermediateDirectories: true)++ var pendingFiles: [String] = []+ for item in requiredItems() {+ // Check existing files and build download list+ // ... implementation details ...+ }++ // Download with progress tracking and error handling+ for (idx, rel) in pendingFiles.enumerated() {+ try await downloadFile(relativePath: rel, to: targetRoot.appendingPathComponent(rel)) { perFilePct in+ // Progress callback with error handling+ }+ }+}+```++**Handling Strategy:**+- Comprehensive progress tracking+- Detailed error reporting+- Automatic retry for network failures+- Clear user feedback about download status++#### Model Loading Errors+```swift+func ensureAsrReady() async throws {+ if isAsrReady == false {+ do {+ // Download models if needed+ let downloader = HuggingFaceModelDownloader()+ try await downloader.ensureModelsPresent(at: cacheDir) { progress, item in+ DispatchQueue.main.async {+ self.isDownloadingModel = progress < 1.0+ self.modelDownloadProgress = max(0.0, min(1.0, progress))+ }+ }++ // Load models with error handling+ let models = try await downloader.loadLocalAsrModels(from: cacheDir)++ if self.asrManager == nil {+ self.asrManager = AsrManager(config: ASRConfig(realtimeMode: false))+ }++ if let manager = self.asrManager {+ try await manager.initialize(models: models)+ }++ isAsrReady = true+ } catch {+ DebugLogger.shared.error("ASR initialization failed: \(error)", source: "ASRService")+ throw error+ }+ }+}+```++**Handling Strategy:**+- Detailed error logging with context+- Proper error propagation+- User-friendly error messages+- Graceful fallback when models can't be loaded++### 4. Text Injection Errors++#### Accessibility API Failures+```swift+private func tryAllTextInsertionMethods(_ element: AXUIElement, _ text: String) -> Bool {+ // Try multiple approaches for text insertion+ if setTextViaValue(element, text) {+ return true+ }++ if setTextViaSelection(element, text) {+ return true+ }++ if insertTextAtInsertionPoint(element, text) {+ return true+ }++ return false+}+```++**Handling Strategy:**+- Multiple fallback strategies+- Detailed logging for each attempt+- Graceful degradation when insertion fails+- User notification for repeated failures++#### CGEvent Failures+```swift+private func insertTextBulkInstant(_ text: String) -> Bool {+ guard let event = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true) else {+ DebugLogger.shared.error("Failed to create bulk CGEvent", source: "TypingService")+ return false+ }++ let utf16Array = Array(text.utf16)+ event.keyboardSetUnicodeString(stringLength: utf16Array.count, unicodeString: utf16Array)+ event.post(tap: .cghidEventTap)++ return true+}+```++**Handling Strategy:**+- Fallback to character-by-character typing+- Detailed error logging+- No user interruption for failed attempts++## Error Recovery Mechanisms++### Automatic Recovery+- **Audio Device Changes**: Automatic restart of audio engine+- **Network Failures**: Retry mechanism for model downloads+- **Permission Changes**: Automatic reinitialization when permissions granted++### User-Initiated Recovery+- **Retry Buttons**: For failed operations+- **Manual Configuration**: Settings for troubleshooting+- **Diagnostic Tools**: Debug mode with detailed logging++## User Feedback Strategy++### Error Messages+```swift+// Example error message format+"Unable to access microphone. Please grant microphone permission in System Settings → Privacy & Security → Microphone, then restart Fluid."+```++### Visual Indicators+- **Progress Bars**: For long-running operations+- **Status Icons**: Color-coded status indicators+- **Toast Notifications**: Non-intrusive error messages+- **Loading States**: Clear indication of operation status++### Debug Information+- **Console Logs**: Detailed technical information+- **Debug Settings**: Enable/disable debug features+- **Export Logs**: Ability to export logs for support++## Best Practices++### 1. Fail Gracefully+```swift+do {+ try riskyOperation()+} catch {+ // Log detailed error information+ DebugLogger.shared.error("Operation failed: \(error)", source: "Component")++ // Show user-friendly message+ showUserFriendlyError()++ // Attempt recovery if possible+ attemptRecovery()+}+```++### 2. Provide Context+```swift+DebugLogger.shared.error("ASR transcription failed during model initialization", source: "ASRService")+```++### 3. Use Appropriate Error Levels+- **Debug**: Detailed technical information+- **Info**: General operational information+- **Warning**: Non-critical issues that should be addressed+- **Error**: Critical failures requiring attention++### 4. Recovery Mechanisms+```swift+func attemptRecovery() {+ // Retry with backoff+ // Fallback to alternative approach+ // Disable problematic features gracefully+}+```++## Testing Error Scenarios++### Unit Tests+- Test error handling for all major components+- Verify recovery mechanisms work correctly+- Test with mocked dependencies++### Integration Tests+- Test with real hardware (microphones, displays)+- Verify accessibility API behavior+- Test network failure scenarios++### Manual Testing+- Test with denied permissions+- Simulate network failures+- Test with various audio environments+- Verify error messages are helpful++## Conclusion++Fluid's error handling strategy ensures a robust, user-friendly experience by:++1. **Graceful Degradation**: Features fail gracefully without crashing+2. **Clear Communication**: Users understand what went wrong and how to fix it+3. **Automatic Recovery**: Many issues resolve themselves automatically+4. **Detailed Debugging**: Developers have comprehensive information for troubleshooting+5. **User Control**: Advanced users can access diagnostic tools and detailed logs++This approach balances technical robustness with user experience, making Fluid reliable for both casual and professional users.diff --git a/Fluid.entitlements b/Fluid.entitlementsnew file mode 100644index 00000000..2115f611--- /dev/null+++ b/Fluid.entitlements@@ -0,0 +1,18 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.security.automation.apple-events</key>+ <true/>+ <key>com.apple.security.get-task-allow</key>+ <true/>+ <key>com.apple.security.temporary-exception.apple-events</key>+ <array>+ <string>com.apple.systemevents</string>+ </array>+ <key>com.apple.security.temporary-exception.shared-preference-read</key>+ <array>+ <string>com.apple.loginitems</string>+ </array>+</dict>+</plist>diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxprojnew file mode 100644index 00000000..7474f4f9--- /dev/null+++ b/Fluid.xcodeproj/project.pbxproj@@ -0,0 +1,415 @@+// !$*UTF8*$!+{+ archiveVersion = 1;+ classes = {+ };+ objectVersion = 77;+ objects = {++/* Begin PBXBuildFile section */+ 7C078DA52E3B386A00FB7CAC /* FluidAudio in Frameworks */ = {isa = PBXBuildFile; productRef = 7C078DA42E3B386A00FB7CAC /* FluidAudio */; };+/* End PBXBuildFile section */++/* Begin PBXFileReference section */+ 7C078D8F2E3B339200FB7CAC /* Fluid.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Fluid.app; sourceTree = BUILT_PRODUCTS_DIR; };+/* End PBXFileReference section */++/* Begin PBXFileSystemSynchronizedRootGroup section */+ 7C078D912E3B339200FB7CAC /* Fluid */ = {+ isa = PBXFileSystemSynchronizedRootGroup;+ path = "Sources/Fluid";+ sourceTree = "<group>";+ };+/* End PBXFileSystemSynchronizedRootGroup section */++/* Begin PBXFrameworksBuildPhase section */+ 7C078D8C2E3B339200FB7CAC /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 7C078DA52E3B386A00FB7CAC /* FluidAudio in Frameworks */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXFrameworksBuildPhase section */++/* Begin PBXGroup section */+ 7C078D862E3B339200FB7CAC = {+ isa = PBXGroup;+ children = (+ 7C078D912E3B339200FB7CAC /* Fluid */,+ 7C078D902E3B339200FB7CAC /* Products */,+ );+ sourceTree = "<group>";+ };+ 7C078D902E3B339200FB7CAC /* Products */ = {+ isa = PBXGroup;+ children = (+ 7C078D8F2E3B339200FB7CAC /* Fluid.app */,+ );+ name = Products;+ sourceTree = "<group>";+ };+/* End PBXGroup section */++/* Begin PBXNativeTarget section */+ 7C078D8E2E3B339200FB7CAC /* fluid */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = 7C078D9A2E3B339300FB7CAC /* Build configuration list for PBXNativeTarget "fluid" */;+ buildPhases = (+ 7C078D8B2E3B339200FB7CAC /* Sources */,+ 7C078D8C2E3B339200FB7CAC /* Frameworks */,+ 7C078D8D2E3B339200FB7CAC /* Resources */,+ );+ buildRules = (+ );+ dependencies = (+ );+ fileSystemSynchronizedGroups = (+ 7C078D912E3B339200FB7CAC /* Fluid */,+ );+ name = fluid;+ packageProductDependencies = (+ 7C078DA42E3B386A00FB7CAC /* FluidAudio */,+ );+ productName = Fluid;+ productReference = 7C078D8F2E3B339200FB7CAC /* Fluid.app */;+ productType = "com.apple.product-type.application";+ };+/* End PBXNativeTarget section */++/* Begin PBXProject section */+ 7C078D872E3B339200FB7CAC /* Project object */ = {+ isa = PBXProject;+ attributes = {+ BuildIndependentTargetsInParallel = 1;+ LastSwiftUpdateCheck = 2600;+ LastUpgradeCheck = 2600;+ TargetAttributes = {+ 7C078D8E2E3B339200FB7CAC = {+ CreatedOnToolsVersion = 26.0;+ };+ };+ };+ buildConfigurationList = 7C078D8A2E3B339200FB7CAC /* Build configuration list for PBXProject "Fluid" */;+ developmentRegion = en;+ hasScannedForEncodings = 0;+ knownRegions = (+ en,+ Base,+ );+ mainGroup = 7C078D862E3B339200FB7CAC;+ minimizedProjectReferenceProxies = 1;+ packageReferences = (+ 7C078DA32E3B386A00FB7CAC /* XCRemoteSwiftPackageReference "FluidAudio" */,+ );+ preferredProjectObjectVersion = 77;+ productRefGroup = 7C078D902E3B339200FB7CAC /* Products */;+ projectDirPath = "";+ projectRoot = "";+ targets = (+ 7C078D8E2E3B339200FB7CAC /* fluid */,+ );+ };+/* End PBXProject section */++/* Begin PBXResourcesBuildPhase section */+ 7C078D8D2E3B339200FB7CAC /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXResourcesBuildPhase section */++/* Begin PBXSourcesBuildPhase section */+ 7C078D8B2E3B339200FB7CAC /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXSourcesBuildPhase section */++/* Begin XCBuildConfiguration section */+ 7C078D982E3B339300FB7CAC /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ ARCHS = arm64;+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_ENABLE_OBJC_WEAK = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ COPY_PHASE_STRIP = NO;+ DEBUG_INFORMATION_FORMAT = dwarf;+ DEVELOPMENT_TEAM = V4J43B279J;+ ENABLE_CODE_COVERAGE = NO;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_TESTABILITY = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = YES;+ EXCLUDED_ARCHS = x86_64;+ GCC_C_LANGUAGE_STANDARD = gnu17;+ GCC_DYNAMIC_NO_PIC = NO;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_OPTIMIZATION_LEVEL = 0;+ GCC_PREPROCESSOR_DEFINITIONS = (+ "DEBUG=1",+ "$(inherited)",+ );+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;+ MACOSX_DEPLOYMENT_TARGET = 14.0;+ MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;+ MTL_FAST_MATH = YES;+ ONLY_ACTIVE_ARCH = YES;+ SDKROOT = macosx;+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";+ };+ name = Debug;+ };+ 7C078D992E3B339300FB7CAC /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ ARCHS = arm64;+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_ENABLE_OBJC_WEAK = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ COPY_PHASE_STRIP = NO;+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";+ DEVELOPMENT_TEAM = V4J43B279J;+ ENABLE_CODE_COVERAGE = NO;+ ENABLE_NS_ASSERTIONS = NO;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = YES;+ EXCLUDED_ARCHS = x86_64;+ GCC_C_LANGUAGE_STANDARD = gnu17;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;+ MACOSX_DEPLOYMENT_TARGET = 14.0;+ MTL_ENABLE_DEBUG_INFO = NO;+ MTL_FAST_MATH = YES;+ ONLY_ACTIVE_ARCH = YES;+ SDKROOT = macosx;+ SWIFT_COMPILATION_MODE = wholemodule;+ };+ name = Release;+ };+ 7C078D9B2E3B339300FB7CAC /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ARCHS = "$(ARCHS_STANDARD)";+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;+ CODE_SIGN_ENTITLEMENTS = Fluid.entitlements;+ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";+ CODE_SIGN_STYLE = Automatic;+ COMBINE_HIDPI_IMAGES = YES;+ CURRENT_PROJECT_VERSION = 1;+ DEVELOPMENT_TEAM = V4J43B279J;+ ENABLE_APP_SANDBOX = NO;+ ENABLE_CODE_COVERAGE = NO;+ ENABLE_FILE_ACCESS_DOWNLOADS_FOLDER = readwrite;+ ENABLE_HARDENED_RUNTIME = YES;+ ENABLE_INCOMING_NETWORK_CONNECTIONS = YES;+ ENABLE_OUTGOING_NETWORK_CONNECTIONS = YES;+ ENABLE_PREVIEWS = YES;+ ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;+ ENABLE_RESOURCE_ACCESS_BLUETOOTH = YES;+ ENABLE_RESOURCE_ACCESS_CALENDARS = YES;+ ENABLE_RESOURCE_ACCESS_CAMERA = YES;+ ENABLE_RESOURCE_ACCESS_CONTACTS = YES;+ ENABLE_RESOURCE_ACCESS_LOCATION = YES;+ ENABLE_RESOURCE_ACCESS_PRINTING = YES;+ ENABLE_RESOURCE_ACCESS_USB = YES;+ ENABLE_USER_SELECTED_FILES = readwrite;+ EXCLUDED_ARCHS = x86_64;+ GENERATE_INFOPLIST_FILE = YES;+ "INFOPLIST_FILE[sdk=*]" = "$(SRCROOT)/Info.plist";+ INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity";+ INFOPLIST_KEY_NSHumanReadableCopyright = "";+ INFOPLIST_KEY_NSMicrophoneUsageDescription = "Transcribe speech from microphone";+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/../Frameworks",+ );+ MACOSX_DEPLOYMENT_TARGET = 14.0;+ MARKETING_VERSION = 1.0;+ PRODUCT_BUNDLE_IDENTIFIER = com.FluidApp.app;+ PRODUCT_NAME = Fluid;+ REGISTER_APP_GROUPS = YES;+ STRING_CATALOG_GENERATE_SYMBOLS = YES;+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) ARCH_ARM64";+ SWIFT_APPROACHABLE_CONCURRENCY = YES;+ SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;+ SWIFT_EMIT_LOC_STRINGS = YES;+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;+ SWIFT_VERSION = 5.0;+ VALID_ARCHS = arm64;+ };+ name = Debug;+ };+ 7C078D9C2E3B339300FB7CAC /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ARCHS = "$(ARCHS_STANDARD)";+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;+ CODE_SIGN_ENTITLEMENTS = Fluid.entitlements;+ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";+ CODE_SIGN_STYLE = Automatic;+ COMBINE_HIDPI_IMAGES = YES;+ CURRENT_PROJECT_VERSION = 1;+ DEVELOPMENT_TEAM = V4J43B279J;+ ENABLE_APP_SANDBOX = NO;+ ENABLE_CODE_COVERAGE = NO;+ ENABLE_FILE_ACCESS_DOWNLOADS_FOLDER = readwrite;+ ENABLE_HARDENED_RUNTIME = YES;+ ENABLE_INCOMING_NETWORK_CONNECTIONS = YES;+ ENABLE_OUTGOING_NETWORK_CONNECTIONS = YES;+ ENABLE_PREVIEWS = YES;+ ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;+ ENABLE_RESOURCE_ACCESS_BLUETOOTH = YES;+ ENABLE_RESOURCE_ACCESS_CALENDARS = YES;+ ENABLE_RESOURCE_ACCESS_CAMERA = YES;+ ENABLE_RESOURCE_ACCESS_CONTACTS = YES;+ ENABLE_RESOURCE_ACCESS_LOCATION = YES;+ ENABLE_RESOURCE_ACCESS_PRINTING = YES;+ ENABLE_RESOURCE_ACCESS_USB = YES;+ ENABLE_USER_SELECTED_FILES = readwrite;+ EXCLUDED_ARCHS = x86_64;+ GENERATE_INFOPLIST_FILE = YES;+ "INFOPLIST_FILE[sdk=*]" = "$(SRCROOT)/Info.plist";+ INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity";+ INFOPLIST_KEY_NSHumanReadableCopyright = "";+ INFOPLIST_KEY_NSMicrophoneUsageDescription = "Transcribe speech from microphone";+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/../Frameworks",+ );+ MACOSX_DEPLOYMENT_TARGET = 14.0;+ MARKETING_VERSION = 1.0;+ PRODUCT_BUNDLE_IDENTIFIER = com.FluidApp.app;+ PRODUCT_NAME = Fluid;+ REGISTER_APP_GROUPS = YES;+ STRING_CATALOG_GENERATE_SYMBOLS = YES;+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) ARCH_ARM64";+ SWIFT_APPROACHABLE_CONCURRENCY = YES;+ SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;+ SWIFT_EMIT_LOC_STRINGS = YES;+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;+ SWIFT_VERSION = 5.0;+ VALID_ARCHS = arm64;+ };+ name = Release;+ };+/* End XCBuildConfiguration section */++/* Begin XCConfigurationList section */+ 7C078D8A2E3B339200FB7CAC /* Build configuration list for PBXProject "Fluid" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ 7C078D982E3B339300FB7CAC /* Debug */,+ 7C078D992E3B339300FB7CAC /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+ 7C078D9A2E3B339300FB7CAC /* Build configuration list for PBXNativeTarget "fluid" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ 7C078D9B2E3B339300FB7CAC /* Debug */,+ 7C078D9C2E3B339300FB7CAC /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+/* End XCConfigurationList section */++/* Begin XCRemoteSwiftPackageReference section */+ 7C078DA32E3B386A00FB7CAC /* XCRemoteSwiftPackageReference "FluidAudio" */ = {+ isa = XCRemoteSwiftPackageReference;+ repositoryURL = "https://github.com/FluidInference/FluidAudio.git";+ requirement = {+ branch = main;+ kind = branch;+ };+ };+/* End XCRemoteSwiftPackageReference section */++/* Begin XCSwiftPackageProductDependency section */+ 7C078DA42E3B386A00FB7CAC /* FluidAudio */ = {+ isa = XCSwiftPackageProductDependency;+ package = 7C078DA32E3B386A00FB7CAC /* XCRemoteSwiftPackageReference "FluidAudio" */;+ productName = FluidAudio;+ };+/* End XCSwiftPackageProductDependency section */+ };+ rootObject = 7C078D872E3B339200FB7CAC /* Project object */;+}diff --git a/Fluid.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Fluid.xcodeproj/project.xcworkspace/contents.xcworkspacedatanew file mode 100644index 00000000..919434a6--- /dev/null+++ b/Fluid.xcodeproj/project.xcworkspace/contents.xcworkspacedata@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="UTF-8"?>+<Workspace+ version = "1.0">+ <FileRef+ location = "self:">+ </FileRef>+</Workspace>diff --git a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvednew file mode 100644index 00000000..eef45a3e--- /dev/null+++ b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -0,0 +1,15 @@+{+ "originHash" : "d526b956b2941e51520eb1a181d281939054defb03feb9302533a12952391e2e",+ "pins" : [+ {+ "identity" : "fluidaudio",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/FluidInference/FluidAudio.git",+ "state" : {+ "branch" : "main",+ "revision" : "2de87c32c320e2f28839c3a9682bc7bd0ea45be7"+ }+ }+ ],+ "version" : 3+}diff --git a/Fluid.xcodeproj/xcshareddata/xcschemes/Fluid.xcscheme b/Fluid.xcodeproj/xcshareddata/xcschemes/Fluid.xcschemenew file mode 100644index 00000000..5bc3f1ef--- /dev/null+++ b/Fluid.xcodeproj/xcshareddata/xcschemes/Fluid.xcscheme@@ -0,0 +1,79 @@+<?xml version="1.0" encoding="UTF-8"?>+<Scheme+ LastUpgradeVersion = "2600"+ version = "1.7">+ <BuildAction+ parallelizeBuildables = "YES"+ buildImplicitDependencies = "YES"+ buildArchitectures = "Automatic">+ <BuildActionEntries>+ <BuildActionEntry+ buildForTesting = "YES"+ buildForRunning = "YES"+ buildForProfiling = "YES"+ buildForArchiving = "YES"+ buildForAnalyzing = "YES">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "7C078D8E2E3B339200FB7CAC"+ BuildableName = "Fluid.app"+ BlueprintName = "fluid"+ ReferencedContainer = "container:Fluid.xcodeproj">+ </BuildableReference>+ </BuildActionEntry>+ </BuildActionEntries>+ </BuildAction>+ <TestAction+ buildConfiguration = "Debug"+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"+ shouldUseLaunchSchemeArgsEnv = "YES"+ shouldAutocreateTestPlan = "YES">+ </TestAction>+ <LaunchAction+ buildConfiguration = "Release"+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"+ launchStyle = "0"+ useCustomWorkingDirectory = "NO"+ ignoresPersistentStateOnLaunch = "NO"+ debugDocumentVersioning = "YES"+ debugServiceExtension = "internal"+ allowLocationSimulation = "YES">+ <BuildableProductRunnable+ runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "7C078D8E2E3B339200FB7CAC"+ BuildableName = "Fluid.app"+ BlueprintName = "fluid"+ ReferencedContainer = "container:Fluid.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ </LaunchAction>+ <ProfileAction+ buildConfiguration = "Release"+ shouldUseLaunchSchemeArgsEnv = "YES"+ savedToolIdentifier = ""+ useCustomWorkingDirectory = "NO"+ debugDocumentVersioning = "YES">+ <BuildableProductRunnable+ runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "7C078D8E2E3B339200FB7CAC"+ BuildableName = "Fluid.app"+ BlueprintName = "fluid"+ ReferencedContainer = "container:Fluid.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ </ProfileAction>+ <AnalyzeAction+ buildConfiguration = "Debug">+ </AnalyzeAction>+ <ArchiveAction+ buildConfiguration = "Release"+ customArchiveName = "Fluid"+ revealArchiveInOrganizer = "YES">+ </ArchiveAction>+</Scheme>diff --git a/LICENSE b/LICENSEnew file mode 100644index 00000000..c50ad7e4--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2025 Fluid App++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 00000000..65ffcbd4--- /dev/null+++ b/README.md@@ -0,0 +1,267 @@+# Fluid - Advanced macOS Dictation App++[](https://opensource.org/licenses/MIT)+[](https://developer.apple.com/macos/)++Fluid is a sophisticated macOS dictation application that transforms speech into text with real-time transcription capabilities. Built with Swift and SwiftUI, it provides professional-grade speech recognition with AI enhancement features.++## ✨ Features++- **Real-time Speech Recognition**: Instant transcription with minimal latency+- **Global Hotkey Support**: Start/stop recording with customizable keyboard shortcuts+- **AI Processing**: Enhance transcriptions with OpenAI-compatible APIs+- **Audio Visualization**: Real-time visual feedback during recording+- **Multi-App Support**: Seamlessly type into any application+- **Model Management**: Automatic downloading and management of ASR models+- **Accessibility Integration**: Full support for macOS accessibility features+- **Menu Bar Integration**: Non-intrusive menubar app design++## 🚀 Installation++### Prerequisites++- **macOS 12.0** or later+- **Xcode 14.0** or later+- **Swift 5.7** or later+- **Developer Tools** (install via Xcode)++### Build Instructions++1. **Clone the repository**+ ```bash+ git clone <repository-url>+ cd fluid-dictation+ ```++2. **Install dependencies**+ ```bash+ # The project uses Swift Package Manager+ # Dependencies are automatically resolved by Xcode+ ```++3. **Open in Xcode**+ ```bash+ open Fluid.xcodeproj+ ```++4. **Build and Run**+ - Select the `Fluid` scheme+ - Build with `Cmd + B`+ - Run with `Cmd + R`++## ⚙️ Configuration++### Model Repository++By default, Fluid uses optimized ASR models from Hugging Face. You can customize the model repository:++```swift+let downloader = HuggingFaceModelDownloader(+ owner: "your-username",+ repo: "your-model-repository",+ revision: "main"+)+```++### API Configuration++Configure AI providers in the settings:++1. Open Fluid+2. Go to Settings → AI Prompts+3. Add your API credentials for supported providers++**Supported Providers:**+- OpenAI (GPT-4, GPT-3.5)+- OpenAI-compatible APIs (Azure OpenAI, Local models, etc.)+- Custom endpoints++### Global Hotkey++Set up a global keyboard shortcut:++1. Open Fluid+2. Go to Settings → General+3. Click "Record Shortcut" and press your desired key combination+4. Default: `Right Option` key++## 🎯 Usage++### Basic Dictation++1. **Start Recording**: Press your configured global hotkey or use the menu bar+2. **Speak**: The app will show visual feedback and transcribe your speech+3. **Stop Recording**: Press the hotkey again or use the menu bar+4. **Text Insertion**: Transcribed text is automatically typed into the focused application++### AI Enhancement++Enable AI processing to enhance your transcriptions:++1. Enable "AI Processing" in Settings+2. Configure your AI provider and API key+3. Create custom prompts for different use cases+4. Transcribed text will be processed through your AI model before insertion++### Audio Settings++Adjust audio processing parameters:++- **Input Device**: Choose your microphone+- **Noise Threshold**: Adjust sensitivity for audio visualization+- **Audio Visualization**: Customize the visual feedback display++## 🏗️ Architecture++### Core Components++- **ASRService**: Handles speech recognition and model management+- **TypingService**: Manages text insertion across applications+- **GlobalHotkeyManager**: Manages system-wide keyboard shortcuts+- **MenuBarManager**: Controls the menubar integration+- **SettingsStore**: Persists user preferences and configuration+- **DebugLogger**: Provides structured logging for troubleshooting++### Key Technologies++- **FluidAudio**: Advanced speech recognition framework+- **CoreML**: On-device machine learning for model inference+- **AVFoundation**: Audio capture and processing+- **Accessibility API**: System integration for text insertion+- **SwiftUI**: Modern user interface framework++## 🔧 Development++### Project Structure++```+fluid-dictation/+├── Sources/Fluid/ # Main application source code+│ ├── Assets.xcassets/ # App icons and resources+│ ├── Services/ # Core service classes+│ │ ├── ASRService.swift # Speech recognition service+│ │ ├── TypingService.swift # Text insertion service+│ │ ├── GlobalHotkeyManager.swift+│ │ └── ...+│ ├── Networking/ # API and model management+│ │ ├── AIProvider.swift # AI integration protocols+│ │ └── ModelDownloader.swift # Hugging Face model management+│ ├── Persistence/ # Data persistence+│ │ └── SettingsStore.swift # User preferences+│ ├── Models/ # Data models+│ │ └── HotkeyShortcut.swift # Keyboard shortcut model+│ ├── UI/ # User interface components+│ ├── ContentView.swift # Main application view+│ └── fluidApp.swift # App entry point+├── Fluid.xcodeproj/ # Xcode project+├── LICENSE # MIT license+├── README.md # This file+├── CONTRIBUTING.md # Contribution guidelines+└── ERROR_HANDLING.md # Error handling documentation+```++### Building Custom Models++To use custom ASR models:++1. Upload your model to Hugging Face+2. Update the repository configuration in `ModelDownloader.swift`+3. The app will automatically download and use your custom models++### Debugging++Enable debug logging for development:++1. Go to Settings → Debug Settings+2. Enable "Debug Logging"+3. Check the console for detailed logs++## 🧪 Testing++### Unit Tests++```bash+# Run tests in Xcode+# Product → Test (Cmd + U)+```++### Manual Testing++- Test with different audio input devices+- Verify global hotkey functionality+- Test AI integration with various providers+- Validate text insertion across different applications++## 🤝 Contributing++We welcome contributions! Please see our [Contributing Guidelines](CONTRIBUTING.md) for details.++### Development Setup++1. Fork the repository+2. Create a feature branch+3. Make your changes+4. Add tests for new functionality+5. Submit a pull request++### Code Style++- Follow Swift API Design Guidelines+- Use meaningful variable and function names+- Add comprehensive documentation+- Include error handling for all operations++## 📝 License++This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.++## 🙏 Acknowledgments++- **FluidAudio** framework for advanced speech recognition+- **Apple** for macOS accessibility APIs+- **OpenAI** for AI integration standards+- **Hugging Face** for model hosting infrastructure++## 🐛 Troubleshooting++### Common Issues++**Accessibility permissions not granted:**+- Go to System Settings → Privacy & Security → Accessibility+- Enable Fluid in the list of allowed applications++**Microphone not detected:**+- Check System Settings → Privacy & Security → Microphone+- Ensure Fluid has microphone access++**AI processing not working:**+- Verify API key is correctly configured+- Check network connectivity+- Validate provider endpoint URL++**Global hotkey not responding:**+- Ensure no other application is using the same shortcut+- Check accessibility permissions+- Try restarting the application++### Getting Help++- Check the debug logs (Settings → Debug Settings)+- Review the troubleshooting section+- Create an issue on GitHub with detailed information++## 🔄 Updates++### Version History++- **v1.0**: Initial release with basic dictation+- **v2.0**: Added AI processing and model management+- **v2.1**: Enhanced audio visualization and accessibility++### Release Notes++For detailed release information, see [CHANGELOG.md](CHANGELOG.md).++---++**Made with ❤️ for the macOS community**diff --git a/Sources/Fluid/Assets.xcassets/AccentColor.colorset/Contents.json b/Sources/Fluid/Assets.xcassets/AccentColor.colorset/Contents.jsonnew file mode 100644index 00000000..eb878970--- /dev/null+++ b/Sources/Fluid/Assets.xcassets/AccentColor.colorset/Contents.json@@ -0,0 +1,11 @@+{+ "colors" : [+ {+ "idiom" : "universal"+ }+ ],+ "info" : {+ "author" : "xcode",+ "version" : 1+ }+}diff --git a/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/Contents.json b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/Contents.jsonnew file mode 100644index 00000000..6b098ee0--- /dev/null+++ b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/Contents.json@@ -0,0 +1,68 @@+{+ "images" : [+ {+ "filename" : "[email protected]",+ "idiom" : "mac",+ "scale" : "1x",+ "size" : "16x16"+ },+ {+ "filename" : "[email protected]",+ "idiom" : "mac",+ "scale" : "2x",+ "size" : "16x16"+ },+ {+ "filename" : "[email protected]",+ "idiom" : "mac",+ "scale" : "1x",+ "size" : "32x32"+ },+ {+ "filename" : "[email protected]",+ "idiom" : "mac",+ "scale" : "2x",+ "size" : "32x32"+ },+ {+ "filename" : "[email protected]",+ "idiom" : "mac",+ "scale" : "1x",+ "size" : "128x128"+ },+ {+ "filename" : "[email protected]",+ "idiom" : "mac",+ "scale" : "2x",+ "size" : "128x128"+ },+ {+ "filename" : "[email protected]",+ "idiom" : "mac",+ "scale" : "1x",+ "size" : "256x256"+ },+ {+ "filename" : "[email protected]",+ "idiom" : "mac",+ "scale" : "2x",+ "size" : "256x256"+ },+ {+ "filename" : "[email protected]",+ "idiom" : "mac",+ "scale" : "1x",+ "size" : "512x512"+ },+ {+ "filename" : "[email protected]",+ "idiom" : "mac",+ "scale" : "2x",+ "size" : "512x512"+ }+ ],+ "info" : {+ "author" : "xcode",+ "version" : 1+ }+}diff --git a/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/Untitled.icon/Assets/[email protected] b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/Untitled.icon/Assets/[email protected]new file mode 100644index 00000000..fe5ffc26Binary files /dev/null and b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/Untitled.icon/Assets/[email protected] differdiff --git a/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/Untitled.icon/icon.json b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/Untitled.icon/icon.jsonnew file mode 100644index 00000000..3796eb01--- /dev/null+++ b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/Untitled.icon/icon.json@@ -0,0 +1,36 @@+{+ "fill" : {+ "automatic-gradient" : "extended-srgb:0.00000,0.53333,1.00000,1.00000"+ },+ "groups" : [+ {+ "layers" : [+ {+ "image-name" : "[email protected]",+ "name" : "icon-512@2x",+ "position" : {+ "scale" : 1,+ "translation-in-points" : [+ 0.3980199799449622,+ -2.4518805534498966+ ]+ }+ }+ ],+ "shadow" : {+ "kind" : "neutral",+ "opacity" : 0.5+ },+ "translucency" : {+ "enabled" : true,+ "value" : 0.5+ }+ }+ ],+ "supported-platforms" : {+ "circles" : [+ "watchOS"+ ],+ "squares" : "shared"+ }+}\ No newline at end of filediff --git a/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 00000000..eceaec54Binary files /dev/null and b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 00000000..d149a60fBinary files /dev/null and b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 00000000..6fb9c223Binary files /dev/null and b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 00000000..11c2628bBinary files /dev/null and b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 00000000..d149a60fBinary files /dev/null and b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 00000000..db29efc3Binary files /dev/null and b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 00000000..11c2628bBinary files /dev/null and b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 00000000..acd81e63Binary files /dev/null and b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 00000000..db29efc3Binary files /dev/null and b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 00000000..20d9c9c7Binary files /dev/null and b/Sources/Fluid/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/Sources/Fluid/Assets.xcassets/BrandWordmark.imageset/BrandWordmark.png b/Sources/Fluid/Assets.xcassets/BrandWordmark.imageset/BrandWordmark.pngnew file mode 100644index 00000000..55d0bdf4Binary files /dev/null and b/Sources/Fluid/Assets.xcassets/BrandWordmark.imageset/BrandWordmark.png differdiff --git a/Sources/Fluid/Assets.xcassets/BrandWordmark.imageset/[email protected] b/Sources/Fluid/Assets.xcassets/BrandWordmark.imageset/[email protected]new file mode 100644index 00000000..55d0bdf4Binary files /dev/null and b/Sources/Fluid/Assets.xcassets/BrandWordmark.imageset/[email protected] differdiff --git a/Sources/Fluid/Assets.xcassets/BrandWordmark.imageset/Contents.json b/Sources/Fluid/Assets.xcassets/BrandWordmark.imageset/Contents.jsonnew file mode 100644index 00000000..3f8b1dc0--- /dev/null+++ b/Sources/Fluid/Assets.xcassets/BrandWordmark.imageset/Contents.json@@ -0,0 +1,21 @@+{+ "images" : [+ {+ "idiom" : "mac",+ "filename" : "BrandWordmark.png",+ "scale" : "1x"+ },+ {+ "idiom" : "mac",+ "filename" : "[email protected]",+ "scale" : "2x"+ }+ ],+ "info" : {+ "author" : "xcode",+ "version" : 1+ }+}+++diff --git a/Sources/Fluid/Assets.xcassets/Contents.json b/Sources/Fluid/Assets.xcassets/Contents.jsonnew file mode 100644index 00000000..73c00596--- /dev/null+++ b/Sources/Fluid/Assets.xcassets/Contents.json@@ -0,0 +1,6 @@+{+ "info" : {+ "author" : "xcode",+ "version" : 1+ }+}diff --git a/Sources/Fluid/Assets.xcassets/MenuBarIcon.imageset/Contents.json b/Sources/Fluid/Assets.xcassets/MenuBarIcon.imageset/Contents.jsonnew file mode 100644index 00000000..b2add4b1--- /dev/null+++ b/Sources/Fluid/Assets.xcassets/MenuBarIcon.imageset/Contents.json@@ -0,0 +1,26 @@+{+ "images" : [+ {+ "filename" : "menubar-icon.png",+ "idiom" : "universal",+ "scale" : "1x"+ },+ {+ "filename" : "[email protected]",+ "idiom" : "universal",+ "scale" : "2x"+ },+ {+ "filename" : "[email protected]",+ "idiom" : "universal",+ "scale" : "3x"+ }+ ],+ "info" : {+ "author" : "xcode",+ "version" : 1+ },+ "properties" : {+ "template-rendering-intent" : "template"+ }+}\ No newline at end of filediff --git a/Sources/Fluid/Assets.xcassets/MenuBarIcon.imageset/menubar-icon.png b/Sources/Fluid/Assets.xcassets/MenuBarIcon.imageset/menubar-icon.pngnew file mode 100644index 00000000..b3fab730Binary files /dev/null and b/Sources/Fluid/Assets.xcassets/MenuBarIcon.imageset/menubar-icon.png differdiff --git a/Sources/Fluid/Assets.xcassets/MenuBarIcon.imageset/[email protected] b/Sources/Fluid/Assets.xcassets/MenuBarIcon.imageset/[email protected]new file mode 100644index 00000000..d469a538Binary files /dev/null and b/Sources/Fluid/Assets.xcassets/MenuBarIcon.imageset/[email protected] differdiff --git a/Sources/Fluid/Assets.xcassets/MenuBarIcon.imageset/[email protected] b/Sources/Fluid/Assets.xcassets/MenuBarIcon.imageset/[email protected]new file mode 100644index 00000000..90eddceaBinary files /dev/null and b/Sources/Fluid/Assets.xcassets/MenuBarIcon.imageset/[email protected] differdiff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swiftnew file mode 100644index 00000000..a53c26ff--- /dev/null+++ b/Sources/Fluid/ContentView.swift@@ -0,0 +1,3728 @@+//+// ContentView.swift+// fluid+//+// Created by Barathwaj Anandan on 7/30/25.+//++import SwiftUI+import AppKit+import AVFoundation+import Combine+import CoreAudio+import CoreGraphics++// Visualization types moved to UI/Visualization++// Removed inline default animations (now modular)++// Import the talking animations from TalkingAnimations.swift+// The TalkingAudioVisualizationView is now defined in TalkingAnimations.swift++// MARK: - Listening Overlay View (using modular components)+struct ListeningOverlayView: View+{+ var audioLevelPublisher: AnyPublisher<CGFloat, Never>?++ var body: some View+ {+ TalkingListeningOverlayView(+ audioLevelPublisher: audioLevelPublisher ?? Empty().eraseToAnyPublisher()+ )+ }+}++// MARK: - Example of switching animation styles+/*+// To use a different animation, simply replace the ListeningOverlayView implementation:++struct PulseListeningOverlayView: View {+ let audioLevelPublisher: AnyPublisher<CGFloat, Never>++ var body: some View {+ PulseAudioVisualizationView(+ audioLevelPublisher: audioLevelPublisher ?? Empty().eraseToAnyPublisher(),+ config: PulseAnimationConfig()+ )+ }+}++// Then update ContentView to use PulseListeningOverlayView instead of ListeningOverlayView+// in the .onChange modifier where the overlay is shown.+*/++// ListeningOverlayController moved to Services/++// HotkeyShortcut moved to Models/++// GlobalHotkeyManager moved to Services/++// MARK: - Minimal FluidAudio ASR Service (finalized text, macOS)++// MARK: - Saved Provider Model+// Removed deprecated inline service and model++struct ContentView: View {+ @StateObject private var audioObserver = AudioHardwareObserver()+ @StateObject private var asr = ASRService()+ @StateObject private var mouseTracker = MousePositionTracker()+ @EnvironmentObject private var menuBarManager: MenuBarManager+ @State private var hotkeyManager: GlobalHotkeyManager? = nil+ @State private var hotkeyManagerInitialized: Bool = false+ @State private var overlay: ListeningOverlayController? = nil++ @State private var appear = false+ @State private var accessibilityEnabled = false+ @State private var hotkeyShortcut: HotkeyShortcut = SettingsStore.shared.hotkeyShortcut+ @State private var isRecordingShortcut = false+ @FocusState private var isTranscriptionFocused: Bool++ @State private var overlayVisible: Bool = false+ @State private var overlayAudioLevelThrottled: Any? = nil++ @State private var selectedSidebarItem: SidebarItem? = .welcome+ @State private var playgroundUsed: Bool = false+ @State private var recordingAppInfo: (name: String, bundleId: String, windowTitle: String)? = nil++ // Audio Settings Tab State+ @State private var visualizerNoiseThreshold: Double = SettingsStore.shared.visualizerNoiseThreshold+ @State private var inputDevices: [AudioDevice.Device] = []+ @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"++ // MARK: - AI Enhancement checkbox state+ @State private var enableAIProcessing: Bool = false+ @State private var enableDebugLogs: Bool = SettingsStore.shared.enableDebugLogs++ // Preferences Tab State+ @State private var launchAtStartup: Bool = SettingsStore.shared.launchAtStartup+ @State private var showInDock: Bool = SettingsStore.shared.showInDock+ @State private var showRestartPrompt: Bool = false+ @State private var didOpenAccessibilityPane: Bool = false+ private let accessibilityRestartFlagKey = "Fluid_AccessibilityRestartPending"++ // MARK: - Voice Recognition Model Management+ // Models scoped by provider (name -> [models])+ @State private var availableModelsByProvider: [String: [String]] = [:]+ @State private var selectedModelByProvider: [String: String] = [:]+ @State private var availableModels: [String] = ["gpt-4.1"] // derived from currentProvider+ @State private var selectedModel: String = "gpt-4.1" // derived from currentProvider+ @State private var showingAddModel: Bool = false+ @State private var newModelName: String = ""++ // MARK: - Provider Management+ @State private var providerAPIKeys: [String: String] = [:] // [providerKey: apiKey]+ @State private var currentProvider: String = "openai" // canonical key: "openai" | "groq" | "custom:<id>"++ // API Connection Testing States+ @State private var isTestingConnection: Bool = false+ @State private var connectionStatus: ConnectionStatus = .unknown+ @State private var connectionErrorMessage: String = ""+ @State private var showHelp: Bool = false++ enum ConnectionStatus {+ case unknown, testing, success, failed+ }+ @State private var savedProviders: [SettingsStore.SavedProvider] = []+ @State private var selectedProviderID: String = "openai"+ @State private var showingSaveProvider: Bool = false+ @State private var newProviderName: String = ""+ @State private var newProviderModels: String = ""+ @State private var newProviderApiKey: String = ""+ @State private var showAPIKeyEditor: Bool = false+ @State private var newProviderBaseURL: String = ""+ @State private var keyJustSaved: Bool = false++ var body: some View {+ NavigationSplitView {+ sidebarView+ .environmentObject(mouseTracker)+ .navigationSplitViewColumnWidth(min: 220, ideal: 250, max: 300)+ } detail: {+ detailView+ .environmentObject(mouseTracker)+ }+ .withMouseTracking(mouseTracker)+ .environmentObject(mouseTracker)+ .onAppear {+ appear = true+ accessibilityEnabled = checkAccessibilityPermissions()+ // 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+ }+ // Ensure no restart UI shows if we already have trust+ if accessibilityEnabled { showRestartPrompt = false }++ // Configure menu bar manager with ASR service+ menuBarManager.configure(asrService: asr)++ // Initialize hotkey manager with improved timing and validation+ initializeHotkeyManagerIfNeeded()+ if overlay == nil {+ overlay = ListeningOverlayController(asrService: asr)+ }++ if overlayAudioLevelThrottled == nil {+ overlayAudioLevelThrottled = asr.audioLevelPublisher as Any+ }+ // Load devices and defaults+ refreshDevices()+ if selectedInputUID.isEmpty, let defIn = AudioDevice.getDefaultInputDevice()?.uid { selectedInputUID = defIn }+ if selectedOutputUID.isEmpty, let defOut = AudioDevice.getDefaultOutputDevice()?.uid { selectedOutputUID = defOut }+ // Apply saved preferences if present and available+ if let prefIn = SettingsStore.shared.preferredInputDeviceUID,+ prefIn.isEmpty == false,+ inputDevices.first(where: { $0.uid == prefIn }) != nil,+ prefIn != AudioDevice.getDefaultInputDevice()?.uid+ {+ _ = AudioDevice.setDefaultInputDevice(uid: prefIn)+ selectedInputUID = prefIn+ }+ if let prefOut = SettingsStore.shared.preferredOutputDeviceUID,+ prefOut.isEmpty == false,+ outputDevices.first(where: { $0.uid == prefOut }) != nil,+ prefOut != AudioDevice.getDefaultOutputDevice()?.uid+ {+ _ = AudioDevice.setDefaultOutputDevice(uid: prefOut)+ selectedOutputUID = prefOut+ }++ // 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()+ }++ NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .flagsChanged]) { event in+ let eventModifiers = event.modifierFlags.intersection([.command, .option, .control, .shift])+ let shortcutModifiers = hotkeyShortcut.modifierFlags.intersection([.command, .option, .control, .shift])++ DebugLogger.shared.debug("NSEvent monitor - type: \(event.type), keyCode: \(event.keyCode), eventModifiers: \(eventModifiers), hotkeyShortcut: \(hotkeyShortcut.displayString), isRecordingShortcut: \(isRecordingShortcut)", 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")+ return event+ }++ guard isRecordingShortcut else {+ DebugLogger.shared.debug("NSEvent monitor: Not recording shortcut, forwarding event", source: "ContentView")+ return event+ }++ let keyCode = event.keyCode+ if keyCode == 53 {+ DebugLogger.shared.debug("NSEvent monitor: Escape pressed, cancelling shortcut recording", source: "ContentView")+ isRecordingShortcut = false+ return nil+ }+ let newShortcut = HotkeyShortcut(keyCode: keyCode, modifierFlags: eventModifiers)+ DebugLogger.shared.debug("NSEvent monitor: Recording new shortcut: \(newShortcut.displayString)", source: "ContentView")+ hotkeyShortcut = newShortcut+ SettingsStore.shared.hotkeyShortcut = newShortcut+ hotkeyManager?.updateShortcut(newShortcut)+ isRecordingShortcut = false+ DebugLogger.shared.debug("NSEvent monitor: Finished recording shortcut, isRecordingShortcut set to false", source: "ContentView")+ return nil+ } else if event.type == .flagsChanged {+ if 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")+ return event+ }+ }++ guard isRecordingShortcut else {+ DebugLogger.shared.debug("NSEvent monitor: Not recording shortcut (modifier), forwarding event", source: "ContentView")+ return event+ }+ let keyCode = event.keyCode+ let isModifierKeyPressed = eventModifiers.isEmpty == false+ if isModifierKeyPressed {+ // Map the actual key codes for modifier keys+ var actualKeyCode = keyCode+ if eventModifiers.contains(.command) {+ // Determine if it's left or right command based on key code+ actualKeyCode = (keyCode == 55) ? 55 : 54 // 55 = left cmd, 54 = right cmd+ } else if eventModifiers.contains(.option) {+ actualKeyCode = (keyCode == 58) ? 58 : 61 // 58 = left opt, 61 = right opt+ } else if eventModifiers.contains(.control) {+ actualKeyCode = (keyCode == 59) ? 59 : 62 // 59 = left ctrl, 62 = right ctrl+ } else if eventModifiers.contains(.shift) {+ actualKeyCode = (keyCode == 56) ? 56 : 60 // 56 = left shift, 60 = right shift+ }++ let newShortcut = HotkeyShortcut(keyCode: actualKeyCode, modifierFlags: [])+ DebugLogger.shared.debug("NSEvent monitor: Recording new shortcut (modifier only): \(newShortcut.displayString), original keyCode: \(keyCode), mapped keyCode: \(actualKeyCode)", source: "ContentView")+ hotkeyShortcut = newShortcut+ SettingsStore.shared.hotkeyShortcut = newShortcut+ hotkeyManager?.updateShortcut(newShortcut)+ isRecordingShortcut = false+ DebugLogger.shared.debug("NSEvent monitor: Finished recording modifier shortcut, isRecordingShortcut set to false", source: "ContentView")+ return nil+ }+ }++ return event+ }+ }+ .onChange(of: accessibilityEnabled) { _, enabled in+ if enabled && hotkeyManager != nil && !hotkeyManagerInitialized {+ DebugLogger.shared.debug("Accessibility enabled, reinitializing hotkey manager", source: "ContentView")+ hotkeyManager?.reinitialize()+ }+ }+ .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in+ let trusted = AXIsProcessTrusted()+ if trusted != accessibilityEnabled {+ accessibilityEnabled = trusted+ }+ }+ .overlay(alignment: .center) {+ }+ .onReceive(audioObserver.changePublisher) { _ in+ // Hardware change detected → refresh lists and apply preferences if available+ refreshDevices()++ // Input: prefer saved device if present, else mirror system default+ if let prefIn = SettingsStore.shared.preferredInputDeviceUID,+ prefIn.isEmpty == false,+ inputDevices.first(where: { $0.uid == prefIn }) != nil,+ prefIn != AudioDevice.getDefaultInputDevice()?.uid+ {+ _ = AudioDevice.setDefaultInputDevice(uid: prefIn)+ selectedInputUID = prefIn+ }+ else if let sysIn = AudioDevice.getDefaultInputDevice()?.uid+ {+ selectedInputUID = sysIn+ }++ // Output: prefer saved device if present, else mirror system default+ if let prefOut = SettingsStore.shared.preferredOutputDeviceUID,+ prefOut.isEmpty == false,+ outputDevices.first(where: { $0.uid == prefOut }) != nil,+ prefOut != AudioDevice.getDefaultOutputDevice()?.uid+ {+ _ = AudioDevice.setDefaultOutputDevice(uid: prefOut)+ selectedOutputUID = prefOut+ }+ else if let sysOut = AudioDevice.getDefaultOutputDevice()?.uid+ {+ selectedOutputUID = sysOut+ }+ }+ .onDisappear {+ asr.stopWithoutTranscription()+ overlay?.hide()+ }+ .onChange(of: hotkeyShortcut) { oldValue, newValue in+ DebugLogger.shared.debug("Hotkey shortcut changed from \(oldValue.displayString) to \(newValue.displayString)", source: "ContentView")+ 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")+ }+ }+ .onChange(of: asr.isRunning) { _, running in+ // Prevent rapid state changes that could cause cycles+ guard overlayVisible != running else { return }++ let delay: DispatchTimeInterval = .milliseconds(150)+ if running {+ overlayVisible = true+ DispatchQueue.main.asyncAfter(deadline: .now() + delay) {+ guard self.overlayVisible else { return }+ let hosting = NSHostingView(rootView: ListeningOverlayView(audioLevelPublisher: self.asr.audioLevelPublisher))+ hosting.wantsLayer = true+ hosting.layer?.cornerRadius = 20+ hosting.layer?.masksToBounds = true+ self.overlay?.show(with: hosting)+ }+ } else {+ overlayVisible = false+ DispatchQueue.main.asyncAfter(deadline: .now() + delay) {+ guard !self.overlayVisible else { return }+ self.overlay?.hide()+ }+ }+ }+ }++ private var sidebarView: some View {+ List(selection: $selectedSidebarItem) {+ NavigationLink(value: SidebarItem.welcome) {+ Label("Welcome", systemImage: "house.fill")+ .font(.system(size: 15, weight: .medium))+ }+ .listRowBackground(sidebarRowBackground)++ NavigationLink(value: SidebarItem.recording) {+ Label("Recording", systemImage: "mic.fill")+ .font(.system(size: 15, weight: .medium))+ }+ .listRowBackground(sidebarRowBackground)++ NavigationLink(value: SidebarItem.aiProcessing) {+ Label("AI Processing", systemImage: "sparkles")+ .font(.system(size: 15, weight: .medium))+ }+ .listRowBackground(sidebarRowBackground)++ NavigationLink(value: SidebarItem.audio) {+ Label("Audio", systemImage: "speaker.wave.2.fill")+ .font(.system(size: 15, weight: .medium))+ }+ .listRowBackground(sidebarRowBackground)++ NavigationLink(value: SidebarItem.settings) {+ Label("Settings", systemImage: "gearshape.fill")+ .font(.system(size: 15, weight: .medium))+ }+ .listRowBackground(sidebarRowBackground)++ NavigationLink(value: SidebarItem.meetingTools) {+ Label("Meeting Tools", systemImage: "person.2.wave.2.fill")+ .font(.system(size: 15, weight: .medium))+ }+ .listRowBackground(sidebarRowBackground)+ }+ .listStyle(.sidebar)+ .navigationTitle("Fluid")+ .background(sidebarBackground)+ .scrollContentBackground(.hidden)+ }++ private var sidebarRowBackground: some View {+ RoundedRectangle(cornerRadius: 8)+ .fill(.ultraThinMaterial.opacity(0.8))+ .background(+ RoundedRectangle(cornerRadius: 8)+ .fill(+ LinearGradient(+ colors: [+ Color(red: 0.10, green: 0.12, blue: 0.20).opacity(0.3), // Deep blue tint+ Color(red: 0.06, green: 0.08, blue: 0.15).opacity(0.2), // Blue-charcoal+ Color(red: 0.04, green: 0.05, blue: 0.10).opacity(0.1) // Dark blue+ ],+ startPoint: .top,+ endPoint: .bottom+ )+ )+ )+ .overlay(+ RoundedRectangle(cornerRadius: 8)+ .stroke(Color.white.opacity(0.25), lineWidth: 0.5)+ )+ }++ private var sidebarBackground: some View {+ LinearGradient(+ colors: [+ Color(red: 0.10, green: 0.12, blue: 0.22), // Deep blue-charcoal (more blue at top)+ Color(red: 0.06, green: 0.08, blue: 0.16), // Rich blue-black+ Color(red: 0.04, green: 0.05, blue: 0.10), // Ultra dark blue+ Color(red: 0.02, green: 0.03, blue: 0.06) // Deepest blue+ ],+ startPoint: .top,+ endPoint: .bottom+ )+ }++ private var detailView: some View {+ ZStack {+ // Tech blue gradient background+ ZStack {+ // Base dark blue layer+ Color(red: 0.04, green: 0.05, blue: 0.09)++ // Tech blue gradient overlay+ LinearGradient(+ colors: [+ Color(red: 0.08, green: 0.10, blue: 0.18).opacity(0.8), // Deep tech blue (more blue)+ Color(red: 0.05, green: 0.07, blue: 0.14).opacity(0.6), // Rich blue-black+ Color(red: 0.06, green: 0.06, blue: 0.12).opacity(0.7), // Blue-charcoal+ Color(red: 0.04, green: 0.05, blue: 0.10).opacity(0.5) // Base dark blue+ ],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )++ // Subtle radial gradient for depth+ RadialGradient(+ colors: [+ Color.clear,+ Color(red: 0.02, green: 0.03, blue: 0.06).opacity(0.3)+ ],+ center: .center,+ startRadius: 100,+ endRadius: 400+ )+ }+ .ignoresSafeArea()++ Group {+ switch selectedSidebarItem ?? .welcome {+ case .welcome:+ welcomeView+ case .recording:+ recordingView+ case .aiProcessing:+ aiProcessingView+ case .audio:+ audioView+ case .settings:+ settingsView+ case .meetingTools:+ meetingToolsView+ }+ }+ }+ }++ // MARK: - Welcome Guide+ private var welcomeView: some View {+ ScrollView {+ VStack(alignment: .leading, spacing: 20) {+ // Header+ VStack(alignment: .leading, spacing: 8) {+ HStack {+ Image(systemName: "book.fill")+ .font(.system(size: 32))+ .foregroundStyle(.blue)+ VStack(alignment: .leading) {+ Text("Welcome to Fluid")+ .font(.system(size: 28, weight: .bold))+ Text("Your AI-powered voice transcription assistant")+ .font(.system(size: 16))+ .foregroundStyle(.secondary)+ }+ }+ Text("Follow this quick setup to start using Fluid.")+ .font(.system(size: 14))+ .foregroundStyle(.secondary)+ .padding(.top, 4)+ }+ .padding(.bottom, 8)++ // Quick Setup Checklist+ HoverableGlossyCard {+ VStack(alignment: .leading, spacing: 16) {+ HStack {+ Image(systemName: "checkmark.circle.fill")+ .foregroundStyle(.blue)+ Text("Quick Setup")+ .font(.headline)+ }++ VStack(alignment: .leading, spacing: 12) {+ SetupStepView(+ step: 1,+ title: "Grant Microphone Permission",+ description: "Allow Fluid to access your microphone for voice input",+ status: asr.micStatus == .authorized ? .completed : .pending,+ action: {+ selectedSidebarItem = .recording+ }+ )++ SetupStepView(+ step: 2,+ title: "Enable Accessibility",+ description: "Grant accessibility permission to type text into other apps",+ status: accessibilityEnabled ? .completed : .pending,+ action: {+ selectedSidebarItem = .recording+ }+ )++ SetupStepView(+ step: 3,+ title: "Set Up AI Enhancement (Optional)",+ description: "Configure API keys for AI-powered text enhancement",+ status: (providerAPIKeys[currentProvider]?.isEmpty == false && availableModels.contains(selectedModel)) ? .completed : .pending,+ action: {+ selectedSidebarItem = .aiProcessing+ }+ )++ SetupStepView(+ step: 4,+ title: "Test Your Setup below",+ description: "Try the playground below to test your complete setup",+ status: playgroundUsed ? .completed : .pending,+ action: {+ // No action needed - playground is right below+ },+ showConfigureButton: false+ )+ }+ }+ .padding(20)+ }++ // Test Playground - Right after setup checklist+ HoverableGlossyCard(excludeInteractiveElements: true) {+ VStack(alignment: .leading, spacing: 16) {+ HStack {+ Image(systemName: "text.bubble")+ .font(.title2)+ .foregroundStyle(.white)+ Text("Test Playground")+ .font(.title3)+ .fontWeight(.semibold)++ Spacer()++ if !asr.finalText.isEmpty {+ Button(action: {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(asr.finalText, forType: .string)+ }) {+ HStack {+ Image(systemName: "doc.on.doc")+ Text("Copy")+ }+ }+ .buttonStyle(InlineButtonStyle())+ .buttonHoverEffect()+ }+ }++ VStack(alignment: .leading, spacing: 12) {+ HStack {+ VStack(alignment: .leading, spacing: 4) {+ Text("Test your voice transcription here!")+ .font(.subheadline)+ .fontWeight(.medium)+ .foregroundStyle(.secondary)++ Text("• Click 'Start Recording' or use hotkey (Right Option/Alt)")+ .font(.caption)+ .foregroundStyle(.secondary)++ Text("• Speak naturally - words appear in real-time")+ .font(.caption)+ .foregroundStyle(.secondary)++ Text("• Click 'Stop Recording' when finished")+ .font(.caption)+ .foregroundStyle(.secondary)+ }++ Spacer()++ VStack(alignment: .trailing, spacing: 4) {+ if asr.isRunning {+ HStack {+ Image(systemName: "waveform")+ .foregroundStyle(.red)+ Text("Recording...")+ .font(.caption)+ .foregroundStyle(.red)+ }+ } else if !asr.finalText.isEmpty {+ Text("\(asr.finalText.count) characters")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ }+ }++ // Recording Controls+ HStack(spacing: 16) {+ if asr.isRunning {+ Button(action: {+ Task {+ await stopAndProcessTranscription()+ }+ }) {+ HStack(spacing: 8) {+ Image(systemName: "stop.fill")+ .foregroundStyle(.red)+ Text("Stop Recording")+ .fontWeight(.medium)+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 8)+ .background(Color.red.opacity(0.1))+ .clipShape(RoundedRectangle(cornerRadius: 8))+ }+ } else {+ Button(action: {+ startRecording()+ }) {+ HStack(spacing: 8) {+ Image(systemName: "mic.fill")+ .foregroundStyle(.green)+ Text("Start Recording")+ .fontWeight(.medium)+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 8)+ .background(Color.green.opacity(0.1))+ .clipShape(RoundedRectangle(cornerRadius: 8))+ }+ }++ if !asr.isRunning && !asr.finalText.isEmpty {+ Button("Clear Results") {+ asr.finalText = ""+ }+ .buttonStyle(.bordered)+ .controlSize(.small)+ }+ }++ // TRANSCRIPTION TEXT AREA - ACTUAL TEXT FIELD+ VStack(alignment: .leading, spacing: 12) {+ HStack {+ Text("Transcription Playground")+ .font(.headline)+ .fontWeight(.semibold)++ Spacer()++ if !asr.finalText.isEmpty {+ Text("\(asr.finalText.count) characters")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ }++ // REAL TEXT EDITOR - Can receive focus and display transcription+ TextEditor(text: $asr.finalText)+ .font(.system(size: 16))+ .focused($isTranscriptionFocused)+ .frame(height: 200)+ .padding(16)+ .background(+ RoundedRectangle(cornerRadius: 12)+ .fill(asr.isRunning ? Color.blue.opacity(0.05) : Color.gray.opacity(0.05))+ .overlay(+ RoundedRectangle(cornerRadius: 12)+ .stroke(asr.isRunning ? Color.blue.opacity(0.3) : Color.gray.opacity(0.2), lineWidth: asr.isRunning ? 2 : 1)+ )+ )+ .overlay(+ VStack {+ if asr.isRunning {+ VStack(spacing: 12) {+ // Animated recording indicator overlay+ HStack(spacing: 8) {+ Image(systemName: "waveform")+ .font(.system(size: 24))+ .foregroundStyle(.blue)+ .scaleEffect(1.0)+ .animation(.easeInOut(duration: 0.8).repeatForever(), value: asr.isRunning)++ Image(systemName: "waveform")+ .font(.system(size: 20))+ .foregroundStyle(.blue.opacity(0.7))+ .scaleEffect(1.0)+ .animation(.easeInOut(duration: 0.6).repeatForever(), value: asr.isRunning)++ Image(systemName: "waveform")+ .font(.system(size: 16))+ .foregroundStyle(.blue.opacity(0.5))+ .scaleEffect(1.0)+ .animation(.easeInOut(duration: 0.4).repeatForever(), value: asr.isRunning)+ }++ VStack(spacing: 4) {+ Text("Listening... Speak now!")+ .font(.title3)+ .fontWeight(.semibold)+ .foregroundStyle(.blue)++ Text("Your words will appear here in real-time")+ .font(.subheadline)+ .foregroundStyle(.blue.opacity(0.8))+ }+ }+ } else if asr.finalText.isEmpty {+ VStack(spacing: 12) {+ Image(systemName: "text.bubble")+ .font(.system(size: 32))+ .foregroundStyle(.secondary.opacity(0.6))++ VStack(spacing: 4) {+ Text("Ready to test!")+ .font(.title3)+ .fontWeight(.semibold)+ .foregroundStyle(.primary)++ Text("Click 'Start Recording' or press your hotkey")+ .font(.subheadline)+ .foregroundStyle(.secondary)+ }+ }+ }+ }+ .allowsHitTesting(false) // Don't block text editor interaction+ )++ // Quick Action Buttons+ if !asr.finalText.isEmpty {+ HStack(spacing: 12) {+ Button(action: {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(asr.finalText, forType: .string)+ }) {+ HStack(spacing: 6) {+ Image(systemName: "doc.on.doc")+ Text("Copy Text")+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 8)+ .background(Color.blue.opacity(0.1))+ .foregroundStyle(.blue)+ .cornerRadius(8)+ }++ Button("Clear & Test Again") {+ asr.finalText = ""+ }+ .buttonStyle(.bordered)+ .controlSize(.regular)++ Spacer()+ }+ .padding(.top, 8)+ }+ }+ }+ }+ .padding(20)+ }++ // How to Use+ HoverableGlossyCard {+ VStack(alignment: .leading, spacing: 16) {+ HStack {+ Image(systemName: "play.fill")+ .foregroundStyle(.green)+ Text("How to Use")+ .font(.headline)+ }++ VStack(alignment: .leading, spacing: 16) {+ InstructionStep(+ number: 1,+ title: "Start Recording",+ description: "Use your hotkey (default: Right Option/Alt) or click the record button in the main window"+ )++ InstructionStep(+ number: 2,+ title: "Speak Clearly",+ description: "Speak your text naturally. The app works best in quiet environments"+ )++ InstructionStep(+ number: 3,+ title: "AI Enhancement",+ description: "Your speech is transcribed, then enhanced by AI for better grammar and clarity"+ )++ InstructionStep(+ number: 4,+ title: "Auto-Type Result",+ description: "The enhanced text is automatically typed into your focused application"+ )+ }+ }+ .padding(20)+ }++ // API Configuration Guide+ HoverableGlossyCard {+ VStack(alignment: .leading, spacing: 16) {+ HStack {+ Image(systemName: "key.fill")+ .foregroundStyle(.purple)+ Text("Get API Keys")+ .font(.headline)+ }++ VStack(alignment: .leading, spacing: 16) {+ Text("Choose your AI provider:")+ .font(.subheadline)+ .foregroundStyle(.secondary)++ ProviderGuide(+ name: "OpenAI",+ url: "https://platform.openai.com/api-keys",+ description: "Most popular choice with GPT-4.1 models",+ baseURL: "https://api.openai.com/v1",+ keyPrefix: "sk-"+ )++ ProviderGuide(+ name: "Groq",+ url: "https://console.groq.com/keys",+ description: "Fast inference with Llama and Mixtral models",+ baseURL: "https://api.groq.com/openai/v1",+ keyPrefix: "gsk_"+ )+++ // Local Models Coming Soon+ HoverableGlossyCard(excludeInteractiveElements: true) {+ VStack(alignment: .leading, spacing: 8) {+ HStack {+ Text("Local Models")+ .font(.system(size: 14, weight: .semibold))+ .foregroundStyle(.secondary)++ Spacer()++ Text("Coming Soon")+ .font(.system(size: 12))+ .foregroundStyle(.orange)+ .padding(.horizontal, 8)+ .padding(.vertical, 2)+ .background(Color.orange.opacity(0.1))+ .cornerRadius(8)+ }++ Text("Run models locally for privacy and offline use")+ .font(.system(size: 13))+ .foregroundStyle(.secondary)+ }+ .padding(12)+ }+ }+ }+ .padding(20)+ }+++ }+ .padding(20)+ }+ }++ // MARK: - Getting Started Helper Views++ private struct SetupStepView: View {+ let step: Int+ let title: String+ let description: String+ let status: SetupStatus+ let action: () -> Void+ var showConfigureButton: Bool = true++ enum SetupStatus {+ case pending, completed, inProgress+ }++ var body: some View {+ HStack(alignment: .top, spacing: 12) {+ ZStack {+ Circle()+ .fill(statusColor.opacity(0.2))+ .frame(width: 32, height: 32)++ if status == .completed {+ Image(systemName: "checkmark")+ .foregroundStyle(statusColor)+ .font(.system(size: 14, weight: .bold))+ } else {+ Text("\(step)")+ .font(.system(size: 14, weight: .semibold))+ .foregroundStyle(statusColor)+ }+ }++ VStack(alignment: .leading, spacing: 4) {+ HStack {+ Text(title)+ .font(.system(size: 14, weight: .semibold))++ Spacer()++ if status != .completed && showConfigureButton {+ Button("Configure") {+ action()+ }+ .font(.system(size: 12))+ .buttonStyle(.bordered)+ .controlSize(.small)+ }+ }++ Text(description)+ .font(.system(size: 13))+ .foregroundStyle(.secondary)+ }+ }+ .padding(.vertical, 8)+ }++ private var statusColor: Color {+ switch status {+ case .completed: return .green+ case .inProgress: return .blue+ case .pending: return .secondary+ }+ }+ }++++ private struct InstructionStep: View {+ let number: Int+ let title: String+ let description: String++ var body: some View {+ HStack(alignment: .top, spacing: 12) {+ ZStack {+ Circle()+ .fill(Color.blue.opacity(0.2))+ .frame(width: 28, height: 28)++ Text("\(number)")+ .font(.system(size: 14, weight: .semibold))+ .foregroundStyle(.blue)+ }++ VStack(alignment: .leading, spacing: 2) {+ Text(title)+ .font(.system(size: 14, weight: .semibold))++ Text(description)+ .font(.system(size: 13))+ .foregroundStyle(.secondary)+ .lineLimit(2)+ }+ }+ }+ }++ private struct ProviderGuide: View {+ let name: String+ let url: String+ let description: String+ let baseURL: String+ let keyPrefix: String++ var body: some View {+ HoverableGlossyCard(excludeInteractiveElements: true) {+ VStack(alignment: .leading, spacing: 8) {+ HStack {+ Text(name)+ .font(.system(size: 14, weight: .semibold))++ Spacer()++ if !url.isEmpty {+ Button("Get API Key") {+ if let url = URL(string: url) {+ NSWorkspace.shared.open(url)+ }+ }+ .font(.system(size: 12))+ .buttonStyle(.bordered)+ .controlSize(.small)+ }+ }++ Text(description)+ .font(.system(size: 13))+ .foregroundStyle(.secondary)++ VStack(alignment: .leading, spacing: 4) {+ HStack {+ Text("Base URL:")+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(.secondary)+ Text(baseURL)+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(.primary)+ .textSelection(.enabled)+ }++ HStack {+ Text("Key Format:")+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(.secondary)+ Text(keyPrefix == "not-needed" ? "Not required" : "Starts with: \(keyPrefix)")+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(.primary)+ }+ }+ .padding(.top, 4)+ }+ .padding(12)+ }+ }+ }++++ private var microphonePermissionView: some View {+ VStack(alignment: .leading, spacing: 12) {+ HStack(spacing: 12) {+ // Status indicator+ Circle()+ .fill(asr.micStatus == .authorized ? .green : .red)+ .frame(width: 10, height: 10)++ VStack(alignment: .leading, spacing: 4) {+ Text(labelFor(status: asr.micStatus))+ .fontWeight(.medium)+ .foregroundStyle(asr.micStatus == .authorized ? .primary : Color.red)++ if asr.micStatus != .authorized {+ Text("Microphone access is required for voice recording")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ }+ Spacer()++ microphoneActionButton+ }++ // Step-by-step instructions when microphone is not authorized+ if asr.micStatus != .authorized {+ microphoneInstructionsView+ }+ }+ }++ private var microphoneActionButton: some View {+ Group {+ if asr.micStatus == .notDetermined {+ Button {+ asr.requestMicAccess()+ } label: {+ HStack(spacing: 6) {+ Image(systemName: "mic.fill")+ Text("Grant Access")+ .fontWeight(.medium)+ }+ }+ .buttonStyle(GlassButtonStyle())+ .buttonHoverEffect()+ } else if asr.micStatus == .denied {+ Button {+ asr.openSystemSettingsForMic()+ } label: {+ HStack(spacing: 6) {+ Image(systemName: "gear")+ Text("Open Settings")+ .fontWeight(.medium)+ }+ }+ .buttonStyle(GlassButtonStyle())+ .buttonHoverEffect()+ }+ }+ }++ private var microphoneInstructionsView: some View {+ VStack(alignment: .leading, spacing: 8) {+ HStack(spacing: 8) {+ Image(systemName: "info.circle.fill")+ .foregroundStyle(.blue)+ .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 **Fluid** in the microphone list")+ instructionStep(number: "3", text: "Toggle **Fluid ON** to allow access")+ }+ }+ .padding(.leading, 4)+ }+ .padding(12)+ .background(Color.blue.opacity(0.1))+ .cornerRadius(8)+ }++ private func instructionStep(number: String, text: String) -> some View {+ HStack(spacing: 8) {+ Text(number + ".")+ .font(.caption2)+ .foregroundStyle(.blue)+ .fontWeight(.semibold)+ .frame(width: 16)+ Text(text)+ .font(.caption)+ .foregroundStyle(.primary)+ }+ }++ // MARK: - Settings View+ private var settingsView: some View {+ ScrollView(.vertical, showsIndicators: false) {+ VStack(spacing: 24) {+ // Header+ HoverableGlossyCard {+ VStack(spacing: 16) {+ HStack {+ Image(systemName: "gear")+ .font(.system(size: 32))+ .foregroundStyle(.white)++ VStack(alignment: .leading, spacing: 4) {+ Text("Settings")+ .font(.title2)+ .fontWeight(.bold)+ Text("App behavior and preferences")+ .font(.subheadline)+ .foregroundStyle(.secondary)+ }++ Spacer()+ }+ }+ .padding(24)+ }++ // Settings Card+ HoverableGlossyCard {+ VStack(alignment: .leading, spacing: 16) {+ HStack {+ Image(systemName: "power")+ .font(.title2)+ .foregroundStyle(.white)+ Text("App Settings")+ .font(.title3)+ .fontWeight(.semibold)+ }++ VStack(spacing: 16) {+ Toggle(isOn: Binding(+ get: { SettingsStore.shared.launchAtStartup },+ set: { SettingsStore.shared.launchAtStartup = $0 }+ )) {+ VStack(alignment: .leading, spacing: 4) {+ Text("Launch at startup")+ .font(.headline)+ Text("Automatically start Fluid when you log in")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ }+ .toggleStyle(.switch)++ Text("Note: Requires app to be signed for this to work.")+ .font(.caption2)+ .foregroundStyle(.secondary.opacity(0.7))++ Divider()++ Toggle(isOn: Binding(+ get: { SettingsStore.shared.showInDock },+ set: { SettingsStore.shared.showInDock = $0 }+ )) {+ VStack(alignment: .leading, spacing: 4) {+ Text("Show in Dock")+ .font(.headline)+ Text("Display Fluid icon in the Dock")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ }+ .toggleStyle(.switch)++ Text("Note: May require app restart to take effect.")+ .font(.caption2)+ .foregroundStyle(.secondary.opacity(0.7))+ }+ }+ .padding(24)+ }+ }+ .padding(24)+ }+ }++ private var recordingView: some View {+ ScrollView(.vertical, showsIndicators: false) {+ VStack(spacing: 24) {+ // Hero Header Card+ HoverableGlossyCard {+ VStack(spacing: 16) {+ HStack {+ Image(systemName: "waveform.circle.fill")+ .font(.system(size: 32))+ .foregroundStyle(.white)++ VStack(alignment: .leading, spacing: 4) {+ Text("Voice Dictation")+ .font(.title2)+ .fontWeight(.bold)+ Text("AI-powered speech recognition")+ .font(.subheadline)+ .foregroundStyle(.secondary)+ }++ Spacer()+ }++ // Status and Recording Control+ VStack(spacing: 12) {+ // Status indicator+ HStack {+ Circle()+ .fill(asr.isRunning ? .red : asr.isAsrReady ? .green : .secondary)+ .frame(width: 8, height: 8)++ Text(asr.isRunning ? "Recording..." : asr.isAsrReady ? "Ready to record" : "Model not ready")+ .font(.subheadline)+ .foregroundStyle(asr.isRunning ? .red : asr.isAsrReady ? .green : .secondary)+ }++ // Recording Control (Single Toggle Button)+ Button(action: {+ if asr.isRunning {+ Task {+ await stopAndProcessTranscription()+ }+ } else {+ startRecording()+ }+ }) {+ HStack {+ Image(systemName: asr.isRunning ? "stop.fill" : "mic.fill")+ .font(.system(size: 16, weight: .semibold))+ Text(asr.isRunning ? "Stop Recording" : "Start Recording")+ }+ .frame(maxWidth: .infinity)+ }+ .buttonStyle(PremiumButtonStyle(isRecording: asr.isRunning))+ .buttonHoverEffect()+ .scaleEffect(asr.isRunning ? 1.05 : 1.0)+ .animation(.spring(response: 0.3), value: asr.isRunning)+ .disabled(!asr.isAsrReady && !asr.isRunning)+ }+ }+ .padding(24)+ }+ .modifier(CardAppearAnimation(delay: 0.1, appear: $appear))++ // Permissions Card+ HoverableGlossyCard {+ VStack(alignment: .leading, spacing: 16) {+ HStack {+ Image(systemName: "shield.checkered")+ .font(.title2)+ .foregroundStyle(.white)+ Text("Permissions")+ .font(.title3)+ .fontWeight(.semibold)+ }++ microphonePermissionView+ }+ .padding(24)+ }+ .modifier(CardAppearAnimation(delay: 0.2, appear: $appear))++ // Model Configuration Card (disable hover transforms to avoid AppKit constraint logs)+ HoverableGlossyCard(excludeInteractiveElements: true) {+ VStack(alignment: .leading, spacing: 16) {+ HStack {+ Image(systemName: "brain.head.profile")+ .font(.title2)+ .foregroundStyle(.white)+ Text("Voice to Text Model")+ .font(.title3)+ .fontWeight(.semibold)+ }++ VStack(alignment: .leading, spacing: 12) {+ HStack(spacing: 12) {+ Text("Model")+ .fontWeight(.medium)+ Spacer()+ Menu(asr.selectedModel.displayName) {+ ForEach(ASRService.ModelOption.allCases) { option in+ Button(option.displayName) { asr.selectedModel = option }+ }+ }+ .disabled(asr.isRunning)+ }++ Text(getModelStatusText())+ .font(.caption)+ .foregroundStyle(asr.isAsrReady ? .white : .secondary)+ .padding(.leading, 4)++ // Model status indicator (non-clickable)+ HStack {+ if asr.isDownloadingModel {+ VStack(alignment: .leading, spacing: 4) {+ ProgressView(value: max(0.0, min(1.0, asr.modelDownloadProgress)))+ .frame(width: 160)+ Text(String(format: "Downloading Model… %d%%", Int(asr.modelDownloadProgress * 100)))+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ } else if asr.isAsrReady {+ Image(systemName: "checkmark.circle.fill")+ .foregroundStyle(.green)+ Text("Model Ready")+ .font(.caption)+ .fontWeight(.medium)+ .foregroundStyle(.white)+ } else {+ Image(systemName: "arrow.down.circle")+ .foregroundStyle(.orange)+ Text("Model will download when needed")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ }+ .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)+ )+ )+ }+ }+ .padding(24)+ }+ .modifier(CardAppearAnimation(delay: 0.3, appear: $appear))+++ // Global Hotkey Card+ HoverableGlossyCard {+ VStack(alignment: .leading, spacing: 16) {+ HStack {+ Image(systemName: "keyboard")+ .font(.title2)+ .foregroundStyle(.white)+ Text("Global Hotkey")+ .font(.title3)+ .fontWeight(.semibold)+ }++ if accessibilityEnabled {+ VStack(alignment: .leading, spacing: 16) {+ // Current Hotkey Display+ VStack(alignment: .leading, spacing: 8) {+ Text("Current Hotkey")+ .font(.subheadline)+ .fontWeight(.medium)+ .foregroundStyle(.secondary)++ // Hotkey Display Row+ HStack(spacing: 16) {+ // Clean Hotkey Display+ HStack(spacing: 8) {+ Text(hotkeyShortcut.displayString)+ .font(.system(size: 16, weight: .semibold, design: .monospaced))+ .foregroundStyle(.primary)+ .padding(.horizontal, 12)+ .padding(.vertical, 6)+ .background(+ RoundedRectangle(cornerRadius: 8)+ .fill(.quaternary.opacity(0.5))+ .overlay(+ RoundedRectangle(cornerRadius: 8)+ .stroke(.primary.opacity(0.2), lineWidth: 1)+ )+ )+ }++ Spacer()++ // Enhanced Change Button+ Button {+ DebugLogger.shared.debug("Starting to record new shortcut", source: "ContentView")+ isRecordingShortcut = true+ } label: {+ HStack(spacing: 8) {+ Image(systemName: "pencil")+ .font(.system(size: 13, weight: .semibold))+ Text("Change")+ .fontWeight(.semibold)+ }+ }+ .buttonStyle(GlassButtonStyle())+ .buttonHoverEffect()++ // Restart button for accessibility changes+ if !hotkeyManagerInitialized && accessibilityEnabled {+ Button {+ DebugLogger.shared.debug("User requested app restart for accessibility changes", source: "ContentView")+ restartApp()+ } label: {+ HStack(spacing: 6) {+ Image(systemName: "arrow.clockwise.circle")+ .font(.system(size: 12, weight: .semibold))+ Text("Restart")+ .font(.system(size: 12, weight: .semibold))+ }+ }+ .buttonStyle(InlineButtonStyle())+ .buttonHoverEffect()+ }+ }+ }++ // Enhanced Status/Instruction Text+ HStack(spacing: 10) {+ if isRecordingShortcut {+ Image(systemName: "hand.point.up.left.fill")+ .foregroundStyle(.white)+ .font(.system(size: 16, weight: .medium))+ Text("Press your new hotkey combination now...")+ .font(.system(.subheadline, weight: .medium))+ .foregroundStyle(.white)+ } else if hotkeyManagerInitialized {+ Image(systemName: "checkmark.circle.fill")+ .foregroundStyle(.green)+ .font(.system(size: 16))+ VStack(alignment: .leading, spacing: 2) {+ Text("Global Shortcut Active")+ .font(.system(.caption, weight: .semibold))+ .foregroundStyle(.white)+ Text("Press \(hotkeyShortcut.displayString) anywhere to start/stop recording")+ .font(.system(.caption))+ .foregroundStyle(.secondary)+ }+ } else {+ ProgressView()+ .scaleEffect(0.8)+ .frame(width: 16, height: 16)+ .foregroundStyle(.orange)+ VStack(alignment: .leading, spacing: 2) {+ Text("Hotkey Initializing...")+ .font(.system(.caption, weight: .semibold))+ .foregroundStyle(.orange)+ Text("Please wait while the global hotkey system starts up")+ .font(.system(.caption))+ .foregroundStyle(.secondary)+ }+ }+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 8)+ .background(+ RoundedRectangle(cornerRadius: 8)+ .fill(.ultraThinMaterial.opacity(0.5))+ .overlay(+ RoundedRectangle(cornerRadius: 8)+ .stroke(.white.opacity(0.1), lineWidth: 1)+ )+ )+ }+ } else {+ VStack(alignment: .leading, spacing: 16) {+ HStack(spacing: 12) {+ // Status indicator+ Circle()+ .fill(.red)+ .frame(width: 10, height: 10)++ VStack(alignment: .leading, spacing: 4) {+ HStack {+ Image(systemName: "exclamationmark.triangle.fill")+ .foregroundStyle(.orange)+ Text("Accessibility permissions required")+ .fontWeight(.medium)+ .foregroundStyle(Color.red)+ }+ Text("Required for global hotkey functionality")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ Spacer()++ Button("Open Accessibility Settings") {+ openAccessibilitySettings()+ }+ .buttonStyle(GlassButtonStyle())+ .buttonHoverEffect()+ }++ // Prominent step-by-step instructions+ VStack(alignment: .leading, spacing: 12) {+ HStack(spacing: 8) {+ Image(systemName: "info.circle.fill")+ .foregroundStyle(.blue)+ .font(.caption)+ Text("Follow these steps to enable Accessibility:")+ .font(.caption)+ .fontWeight(.medium)+ .foregroundStyle(.secondary)+ }++ VStack(alignment: .leading, spacing: 8) {+ HStack(spacing: 8) {+ Text("1.")+ .font(.caption2)+ .foregroundStyle(.blue)+ .fontWeight(.semibold)+ .frame(width: 16)+ Text("Click **Open Accessibility Settings** above")+ .font(.caption)+ .foregroundStyle(.primary)+ }+ HStack(spacing: 8) {+ Text("2.")+ .font(.caption2)+ .foregroundStyle(.blue)+ .fontWeight(.semibold)+ .frame(width: 16)+ Text("In the Accessibility window, click the **+ button**")+ .font(.caption)+ .foregroundStyle(.primary)+ }+ HStack(spacing: 8) {+ Text("3.")+ .font(.caption2)+ .foregroundStyle(.blue)+ .fontWeight(.semibold)+ .frame(width: 16)+ Text("Navigate to Applications and select **Fluid**")+ .font(.caption)+ .foregroundStyle(.primary)+ }+ HStack(spacing: 8) {+ Text("4.")+ .font(.caption2)+ .foregroundStyle(.blue)+ .fontWeight(.semibold)+ .frame(width: 16)+ Text("Click **Open**, then toggle **Fluid ON** in the list")+ .font(.caption)+ .foregroundStyle(.primary)+ }+ }+ .padding(.leading, 4)++ // Helper buttons+ HStack(spacing: 12) {+ Button("Reveal Fluid in Finder") {+ revealAppInFinder()+ }+ .buttonStyle(InlineButtonStyle())+ .buttonHoverEffect()++ Button("Open Applications Folder") {+ openApplicationsFolder()+ }+ .buttonStyle(InlineButtonStyle())+ .buttonHoverEffect()+ }+ }+ .padding(12)+ .background(Color.orange.opacity(0.1))+ .cornerRadius(8)+ }+ }+ }+ .padding(24)+ }+ .modifier(CardAppearAnimation(delay: 0.5, appear: $appear))++ // Debug Settings Card+ HoverableGlossyCard {+ VStack(alignment: .leading, spacing: 16) {+ HStack {+ Image(systemName: "ladybug.fill")+ .font(.title2)+ .foregroundStyle(.white)+ Text("Debug Settings")+ .font(.title3)+ .fontWeight(.semibold)+ }++ VStack(alignment: .leading, spacing: 12) {+ HStack(spacing: 12) {+ Toggle("Enable Debug Logging", isOn: Binding(+ get: { SettingsStore.shared.enableDebugLogs },+ set: { SettingsStore.shared.enableDebugLogs = $0 }+ ))+ .toggleStyle(GlassToggleStyle())++ Text("⚠️")+ .font(.caption)+ .foregroundStyle(.orange)+ }++ Text("Enable debug logging to see detailed information about app operations. This can help with troubleshooting but may impact performance. Error and warning messages are always shown regardless of this setting.")+ .font(.caption)+ .foregroundStyle(.secondary)+ .padding(.leading, 4)+ }+ }+ }+ .padding(24)+ .modifier(CardAppearAnimation(delay: 0.6, appear: $appear))++ }+ .padding(24)+ }+ }++ // MARK: - AI Prompts Tab+ private var aiProcessingView: some View {+ VStack(alignment: .leading, spacing: 20) {+ // Header Section+ VStack(alignment: .leading, spacing: 8) {+ HStack {+ Image(systemName: "sparkles")+ .font(.title2)+ .foregroundStyle(.blue)+ Text("AI Post-Processing")+ .font(.title2)+ .fontWeight(.bold)+ Spacer()+ Button(action: { showHelp.toggle() }) {+ Image(systemName: "questionmark.circle")+ .font(.title3)+ .foregroundStyle(.blue.opacity(0.7))+ }+ .buttonStyle(.plain)+ .buttonHoverEffect()+ }++ Text("Enhance your transcriptions with AI. Configure your API, test prompts, and see how AI improves punctuation, grammar, and formatting.")+ .foregroundColor(.secondary)+ .lineLimit(2)++ // AI Enhancement Toggle+ HStack(spacing: 16) {+ Toggle("Enable AI Enhancement", isOn: $enableAIProcessing)+ .toggleStyle(GlassToggleStyle())+ .onChange(of: enableAIProcessing) { _, newValue in+ SettingsStore.shared.enableAIProcessing = newValue+ }++ Spacer()++ if enableAIProcessing && (providerAPIKeys[currentProvider] ?? "").trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty {+ HStack {+ Image(systemName: "exclamationmark.triangle.fill")+ .foregroundStyle(.orange)+ Text("API Key required")+ .font(.caption)+ .foregroundStyle(.orange)+ }+ .padding(.horizontal, 8)+ .padding(.vertical, 4)+ .background(.orange.opacity(0.1))+ .clipShape(RoundedRectangle(cornerRadius: 6))+ }+ }+ .padding(.vertical, 8)+ .onAppear {+ // Ensure the toggle reflects persisted value when navigating between tabs+ enableAIProcessing = SettingsStore.shared.enableAIProcessing+ }++ // Help Section+ if showHelp {+ VStack(alignment: .leading, spacing: 12) {+ HStack {+ Image(systemName: "lightbulb.fill")+ .foregroundStyle(.yellow)+ Text("Quick Start Guide")+ .font(.subheadline)+ .fontWeight(.semibold)+ }++ VStack(alignment: .leading, spacing: 8) {+ HStack(alignment: .top, spacing: 8) {+ Text("1.")+ .font(.caption)+ .fontWeight(.semibold)+ Text("Add your API key and test the connection")+ .font(.caption)+ .foregroundStyle(.secondary)+ }++ HStack(alignment: .top, spacing: 8) {+ Text("2.")+ .font(.caption)+ .fontWeight(.semibold)+ Text("Choose an AI model for post-processing")+ .font(.caption)+ .foregroundStyle(.secondary)+ }++ HStack(alignment: .top, spacing: 8) {+ Text("3.")+ .font(.caption)+ .fontWeight(.semibold)+ Text("Test prompts to see how AI improves transcriptions")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ }++ Divider()++ HStack {+ Image(systemName: "star.fill")+ .foregroundStyle(.orange)+ Text("Pro Tips")+ .font(.caption)+ .fontWeight(.semibold)+ }++ VStack(alignment: .leading, spacing: 4) {+ Text("• Test with actual transcription samples for best results")+ .font(.caption)+ .foregroundStyle(.secondary)+ Text("• Include context about your typical speaking style")+ .font(.caption)+ .foregroundStyle(.secondary)+ Text("• Experiment with different AI models for various improvements")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ }+ .padding(16)+ .background(Color.blue.opacity(0.05))+ .cornerRadius(12)+ .overlay(+ RoundedRectangle(cornerRadius: 12)+ .stroke(Color.blue.opacity(0.2), lineWidth: 1)+ )+ .transition(.opacity)+ }+ }+ .padding(.bottom, 8)++ // Status Overview+ HoverableGlossyCard {+ VStack(alignment: .leading, spacing: 12) {+ HStack {+ Image(systemName: "info.circle.fill")+ .font(.title3)+ .foregroundStyle(.blue)+ Text("Setup Status")+ .font(.headline)+ .fontWeight(.semibold)+ }++ // Status indicators+ HStack(spacing: 16) {+ // API Key status+ HStack(spacing: 4) {+ Image(systemName: (providerAPIKeys[currentProvider] ?? "").isEmpty ? "xmark.circle.fill" : "checkmark.circle.fill")+ .foregroundStyle((providerAPIKeys[currentProvider] ?? "").isEmpty ? .red : .green)+ .font(.caption)+ Text("API Key")+ .font(.caption)+ .foregroundStyle((providerAPIKeys[currentProvider] ?? "").isEmpty ? .red : .green)+ }++ // Connection status+ HStack(spacing: 4) {+ Image(systemName: connectionStatus == .success ? "checkmark.circle.fill" : "circle")+ .foregroundStyle(connectionStatus == .success ? .green : .secondary)+ .font(.caption)+ Text("Connection")+ .font(.caption)+ .foregroundStyle(connectionStatus == .success ? .green : .secondary)+ }++ // Model status+ HStack(spacing: 4) {+ Image(systemName: availableModels.contains(selectedModel) ? "checkmark.circle.fill" : "circle")+ .foregroundStyle(availableModels.contains(selectedModel) ? .green : .secondary)+ .font(.caption)+ Text("Model")+ .font(.caption)+ .foregroundStyle(availableModels.contains(selectedModel) ? .green : .secondary)+ }+ }+ }+ .padding(16)+ }+ .modifier(CardAppearAnimation(delay: 0.05, appear: $appear))++ // API Configuration Section+ HoverableGlossyCard {+ VStack(alignment: .leading, spacing: 16) {+ HStack {+ Image(systemName: "key.fill")+ .font(.title3)+ .foregroundStyle(.blue)+ Text("API Configuration")+ .font(.headline)+ .fontWeight(.semibold)+ }++ // Saved Providers Dropdown+ // Provider Selection+ HStack(spacing: 8) {+ Text("Provider:")+ Picker("Provider", selection: $selectedProviderID) {+ // Built-in providers+ Text("OpenAI").tag("openai")+ Text("Groq").tag("groq")++ if !savedProviders.isEmpty {+ Divider()+ ForEach(savedProviders) { provider in+ Text(provider.name).tag(provider.id)+ }+ }+ }+ .pickerStyle(.menu)+ .frame(width: 180, alignment: .leading)+ .layoutPriority(1)+ .onChange(of: selectedProviderID) { _, newValue in+ switch newValue {+ case "openai":+ openAIBaseURL = "https://api.openai.com/v1"+ updateCurrentProvider()+ let key = "openai"+ if let stored = availableModelsByProvider[key], !stored.isEmpty { availableModels = stored }+ else { availableModels = defaultModels(for: key) }+ if let sel = selectedModelByProvider[key], availableModels.contains(sel) { selectedModel = sel }+ else { selectedModel = availableModels.first ?? selectedModel }+ case "groq":+ openAIBaseURL = "https://api.groq.com/openai/v1"+ updateCurrentProvider()+ let key = "groq"+ if let stored = availableModelsByProvider[key], !stored.isEmpty { availableModels = stored }+ else { availableModels = defaultModels(for: key) }+ if let sel = selectedModelByProvider[key], availableModels.contains(sel) { selectedModel = sel }+ else { selectedModel = availableModels.first ?? selectedModel }+ default:+ if let provider = savedProviders.first(where: { $0.id == newValue }) {+ openAIBaseURL = provider.baseURL+ updateCurrentProvider()+ // Load the saved API key for this provider+ providerAPIKeys[currentProvider] = provider.apiKey+ saveProviderAPIKeys()+ // Load provider-specific models+ let key = providerKey(for: newValue)+ availableModels = provider.models.isEmpty ? (availableModelsByProvider[key] ?? defaultModels(for: key)) : provider.models+ if let sel = selectedModelByProvider[key], availableModels.contains(sel) { selectedModel = sel }+ else { selectedModel = availableModels.first ?? selectedModel }+ }+ }+ }++ Button("+ Add Provider") {+ showingSaveProvider = true+ newProviderName = ""+ newProviderBaseURL = ""+ newProviderApiKey = ""+ newProviderModels = ""+ }+ .buttonStyle(GlassButtonStyle())+ .buttonHoverEffect()+ }++ // Provider model catalogs quick links+ HStack(spacing: 6) {+ Image(systemName: "link")+ .font(.caption)+ .foregroundStyle(.secondary)+ Text("Model catalogs:")+ .font(.caption)+ .foregroundStyle(.secondary)++ if selectedProviderID == "openai" {+ Link("OpenAI", destination: URL(string: "https://platform.openai.com/docs/models")!)+ .font(.caption)+ Text("·").font(.caption).foregroundStyle(.secondary)+ Link("Groq", destination: URL(string: "https://console.groq.com/docs/models")!)+ .font(.caption)+ .foregroundStyle(.secondary)+ } else if selectedProviderID == "groq" {+ Link("Groq", destination: URL(string: "https://console.groq.com/docs/models")!)+ .font(.caption)+ Text("·").font(.caption).foregroundStyle(.secondary)+ Link("OpenAI", destination: URL(string: "https://platform.openai.com/docs/models")!)+ .font(.caption)+ .foregroundStyle(.secondary)+ } else {+ Link("OpenAI", destination: URL(string: "https://platform.openai.com/docs/models")!)+ .font(.caption)+ Text("·").font(.caption).foregroundStyle(.secondary)+ Link("Groq", destination: URL(string: "https://console.groq.com/docs/models")!)+ .font(.caption)+ }+ }+ .padding(.top, 2)++ HStack(spacing: 8) {+ Button(action: {+ newProviderApiKey = providerAPIKeys[currentProvider] ?? ""+ showAPIKeyEditor = true+ }) {+ Label("Add or Modify API Key", systemImage: "key.fill")+ .labelStyle(.titleAndIcon)+ .font(.caption)+ }+ .buttonStyle(GlassButtonStyle())+ .buttonHoverEffect()++++ Spacer(minLength: 8)++ // Connection Test Button+ Button(action: {+ DebugLogger.shared.info("=== TEST CONNECTION BUTTON PRESSED ===", source: "ContentView")+ Task { await testAPIConnection() }+ }) {+ HStack(spacing: 4) {+ if isTestingConnection {+ ProgressView()+ .frame(width: 12, height: 12)+ } else {+ Image(systemName: "network")+ .font(.caption)+ }+ Text(isTestingConnection ? "Testing..." : "Test")+ .font(.caption)+ }+ .foregroundStyle(.blue)+ .padding(.horizontal, 8)+ .padding(.vertical, 4)+ .background(Color.blue.opacity(0.1))+ .clipShape(RoundedRectangle(cornerRadius: 6))+ }+ .buttonStyle(.plain)+ .disabled(isTestingConnection || (providerAPIKeys[currentProvider] ?? "").isEmpty)+ .buttonHoverEffect()++ Text("(\(currentProvider.capitalized))")+ .font(.caption)+ .foregroundColor(.secondary)+ }++ .sheet(isPresented: $showAPIKeyEditor) {+ VStack(spacing: 16) {+ Text("Enter \(currentProvider.capitalized) API Key")+ .font(.headline)++ SecureField("API Key", text: $newProviderApiKey)+ .textFieldStyle(.roundedBorder)+ .frame(width: 300)++ HStack(spacing: 12) {+ Button("Cancel") {+ showAPIKeyEditor = false+ }+ .buttonStyle(.bordered)++ Button("OK") {+ let trimmedKey = newProviderApiKey.trimmingCharacters(in: .whitespacesAndNewlines)+ providerAPIKeys[currentProvider] = trimmedKey+ saveProviderAPIKeys()+ if connectionStatus != .unknown {+ connectionStatus = .unknown+ connectionErrorMessage = ""+ }+ showAPIKeyEditor = false+ }+ .buttonStyle(.borderedProminent)+ .disabled(newProviderApiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ }+ }+ .padding()+ .frame(minWidth: 350, minHeight: 150)+ }++ // Connection Status Display+ HStack(spacing: 8) {+ // Real-time validation indicator+ if (providerAPIKeys[currentProvider] ?? "").isEmpty {+ Image(systemName: "exclamationmark.triangle.fill")+ .foregroundStyle(.orange)+ .font(.caption)+ Text("API key required")+ .font(.caption)+ .foregroundStyle(.orange)+ } else if connectionStatus == .success {+ Image(systemName: "checkmark.circle.fill")+ .foregroundStyle(.green)+ .font(.caption)+ Text("Ready to test")+ .font(.caption)+ .foregroundStyle(.green)+ } else if connectionStatus == .failed {+ 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)+ }+ }+ } else if connectionStatus == .testing {+ ProgressView()+ .frame(width: 16, height: 16)+ Text("Testing...")+ .font(.caption)+ .foregroundStyle(.blue)+ } else {+ Image(systemName: "network")+ .foregroundStyle(.secondary)+ .font(.caption)+ Text("Test connection to verify setup")+ .font(.caption)+ .foregroundStyle(.secondary)+ }++ Spacer()+ }+ .padding(.top, 6)++ // Show Base URL only for custom providers (not built-in ones)+ if !["openai", "groq"].contains(selectedProviderID) {+ HStack(spacing: 8) {+ TextField("Base URL (e.g., http://localhost:11434/v1)", text: $openAIBaseURL)+ .textFieldStyle(.roundedBorder)+ .frame(width: 350)+ .layoutPriority(1)+ .onChange(of: openAIBaseURL) { _, _ in+ updateCurrentProvider()+ }+ }+ }++ // Add Provider Modal+ if showingSaveProvider {+ VStack(spacing: 12) {+ HStack(spacing: 8) {+ TextField("Provider name (e.g., Local Ollama)", text: $newProviderName)+ .textFieldStyle(.roundedBorder)+ .frame(width: 250)+ TextField("Base URL (e.g., http://localhost:11434/v1)", text: $newProviderBaseURL)+ .textFieldStyle(.roundedBorder)+ .frame(width: 300)+ }++ HStack(spacing: 8) {+ SecureField("API Key", text: $newProviderApiKey)+ .textFieldStyle(.roundedBorder)+ .frame(width: 300)+ TextField("Available models (comma-separated)", text: $newProviderModels)+ .textFieldStyle(.roundedBorder)+ .frame(width: 300)+ }++ Text("Example: llama-3.1-8b, codellama-13b, mistral-7b")+ .font(.caption)+ .foregroundStyle(.secondary)++ HStack(spacing: 8) {+ Button("Save Provider") {+ let name = newProviderName.trimmingCharacters(in: .whitespacesAndNewlines)+ let base = newProviderBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)+ let api = newProviderApiKey.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !name.isEmpty, !base.isEmpty, !api.isEmpty else { return }++ 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,+ apiKey: api,+ models: models+ )++ // upsert by name+ savedProviders.removeAll { $0.name.lowercased() == name.lowercased() }+ savedProviders.append(newProvider)+ saveSavedProviders()++ // bind API key and models to canonical key+ let key = providerKey(for: newProvider.id)+ providerAPIKeys[key] = api+ availableModelsByProvider[key] = models+ selectedModelByProvider[key] = models.first ?? selectedModel+ SettingsStore.shared.providerAPIKeys = providerAPIKeys+ SettingsStore.shared.availableModelsByProvider = availableModelsByProvider+ SettingsStore.shared.selectedModelByProvider = selectedModelByProvider++ // switch selection to the new provider+ selectedProviderID = newProvider.id+ openAIBaseURL = base+ updateCurrentProvider()+ availableModels = models+ selectedModel = models.first ?? selectedModel++ showingSaveProvider = false+ newProviderName = ""; newProviderBaseURL = ""; newProviderApiKey = ""; newProviderModels = ""+ }+ .buttonStyle(GlassButtonStyle())+ .buttonHoverEffect()+ .disabled(newProviderName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||+ newProviderBaseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||+ newProviderApiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)++ Button("Cancel") {+ showingSaveProvider = false+ newProviderName = ""; newProviderBaseURL = ""; newProviderApiKey = ""; newProviderModels = ""+ }+ .buttonStyle(GlassButtonStyle())+ .buttonHoverEffect()+ }+ }+ .transition(.opacity)+ }++ }+ .padding(20)+ }+ .modifier(CardAppearAnimation(delay: 0.1, appear: $appear))++ // Model Configuration Section+ HoverableGlossyCard {+ VStack(alignment: .leading, spacing: 16) {+ HStack {+ Image(systemName: "brain.head.profile")+ .font(.title3)+ .foregroundStyle(.purple)+ Text("Model Configuration")+ .font(.headline)+ .fontWeight(.semibold)+ }++ // Model Selection with Validation+ HStack(spacing: 8) {+ HStack(spacing: 4) {+ Text("Model:")+ if availableModels.isEmpty {+ Image(systemName: "exclamationmark.triangle.fill")+ .foregroundStyle(.orange)+ .font(.caption)+ } else if !availableModels.isEmpty && availableModels.contains(selectedModel) {+ Image(systemName: "checkmark.circle.fill")+ .foregroundStyle(.green)+ .font(.caption)+ }+ }+ Menu {+ ForEach(availableModels, id: \.self) { model in+ Button(action: {+ selectedModel = model+ }) {+ HStack {+ Text(model)+ Spacer()+ if selectedModel == model {+ Image(systemName: "checkmark")+ .foregroundStyle(.blue)+ }+ }+ }+ }++ Divider()++ Button("Add Model...") {+ showingAddModel = true+ newModelName = ""+ }+ } label: {+ HStack {+ Text(selectedModel)+ Spacer()+ Image(systemName: "chevron.down")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ .padding(.horizontal, 8)+ .padding(.vertical, 4)+ .background(.quaternary)+ .cornerRadius(6)+ }+ .frame(width: 220, alignment: .leading)+ .layoutPriority(1)+ }++ // Add Model Input (shown when plus button is clicked)+ if showingAddModel {+ HStack(spacing: 8) {+ TextField("Enter model name (e.g., gpt-4.1-nano)", text: $newModelName)+ .textFieldStyle(.roundedBorder)+ .frame(width: 250)+ .layoutPriority(1)++ Button("Add") {+ if !newModelName.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty {+ let modelName = newModelName.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)+ // Append to current provider's list only+ let key = providerKey(for: selectedProviderID)+ var list = availableModelsByProvider[key] ?? availableModels+ if !list.contains(modelName) { list.append(modelName) }+ availableModelsByProvider[key] = list+ SettingsStore.shared.availableModelsByProvider = availableModelsByProvider+ // Reflect in UI list+ availableModels = list+ selectedModel = modelName+ selectedModelByProvider[key] = modelName+ SettingsStore.shared.selectedModelByProvider = selectedModelByProvider+ showingAddModel = false+ newModelName = ""+ }+ }+ .buttonStyle(GlassButtonStyle())+ .buttonHoverEffect()+ .buttonHoverEffect()+ .disabled(newModelName.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty)++ Button("Cancel") {+ showingAddModel = false+ newModelName = ""+ }+ .buttonStyle(GlassButtonStyle())+ .buttonHoverEffect()+ .buttonHoverEffect()+ }+ .transition(.opacity)+ }++ // Manage Models List+ VStack(alignment: .leading, spacing: 8) {+ Text("Models for this provider")+ .font(.caption)+ .foregroundStyle(.secondary)++ ForEach(availableModels, id: \.self) { model in+ HStack {+ Text(model)+ Spacer()+ if isCustomModel(model) {+ Button(action: { removeModel(model) }) {+ Image(systemName: "xmark.circle.fill")+ .foregroundStyle(.red)+ }+ .buttonStyle(.plain)+ } else {+ Image(systemName: "lock.fill")+ .foregroundStyle(.secondary)+ }+ }+ .padding(.vertical, 4)+ }++ HStack {+ Button("Reset to defaults") {+ // Clear stored list for this provider and show defaults+ availableModelsByProvider[currentProvider] = []+ SettingsStore.shared.availableModelsByProvider = availableModelsByProvider+ availableModels = defaultModels(for: providerKey(for: selectedProviderID))+ selectedModel = availableModels.first ?? selectedModel+ selectedModelByProvider[currentProvider] = selectedModel+ SettingsStore.shared.selectedModelByProvider = selectedModelByProvider+ }+ .buttonStyle(GlassButtonStyle())+ .buttonHoverEffect()+ }+ }++ }+ .padding(20)+ }+ .modifier(CardAppearAnimation(delay: 0.2, appear: $appear))++++ Spacer()+ }+ .padding(20)+ .onAppear {+ // Establish provider context first+ updateCurrentProvider()++ enableAIProcessing = SettingsStore.shared.enableAIProcessing+ enableDebugLogs = SettingsStore.shared.enableDebugLogs+ availableModelsByProvider = SettingsStore.shared.availableModelsByProvider+ selectedModelByProvider = SettingsStore.shared.selectedModelByProvider+ providerAPIKeys = SettingsStore.shared.providerAPIKeys+ savedProviders = SettingsStore.shared.savedProviders++ // Migration & cleanup: normalize provider keys and drop legacy flat lists+ var normalized: [String: [String]] = [:]+ for (key, models) in availableModelsByProvider {+ let lower = key.lowercased()+ let newKey: String+ if lower == "openai" || lower == "groq" { newKey = lower }+ else { newKey = key.hasPrefix("custom:") ? key : "custom:\\(key)" }+ // Keep only unique, trimmed models+ let clean = Array(Set(models.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) })).sorted()+ if !clean.isEmpty { normalized[newKey] = clean }+ }+ availableModelsByProvider = normalized+ SettingsStore.shared.availableModelsByProvider = normalized++ // Normalize selectedModelByProvider keys similarly and drop invalid selections+ 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)")+ if let list = normalized[newKey], list.contains(model) { normalizedSel[newKey] = model }+ }+ 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+ providerAPIKeys[currentProvider] = saved.apiKey+ } else if let stored = availableModelsByProvider[currentProvider], !stored.isEmpty {+ // Use provider-specific stored list if present+ availableModels = stored+ } else {+ // Built-in defaults+ availableModels = defaultModels(for: providerKey(for: selectedProviderID))+ }++ // Restore previously selected model if valid+ if let sel = selectedModelByProvider[currentProvider], availableModels.contains(sel) {+ selectedModel = sel+ } else if let first = availableModels.first {+ selectedModel = first+ }+ }+ .onChange(of: asr.isRunning) { _, newValue in+ // Mark playground as used when user starts recording+ if newValue && !playgroundUsed {+ playgroundUsed = true+ }+ }+ .onChange(of: asr.finalText) { _, newValue in+ // Also mark as used when text appears in playground+ if !newValue.isEmpty && !playgroundUsed {+ playgroundUsed = true+ }+ }+ .onChange(of: enableAIProcessing) { _, newValue in+ SettingsStore.shared.enableAIProcessing = newValue+ // Sync to menu bar immediately+ menuBarManager.aiProcessingEnabled = newValue+ }+ .onChange(of: selectedModel) { _, newValue in+ if newValue != "__ADD_MODEL__" {+ selectedModelByProvider[currentProvider] = newValue+ SettingsStore.shared.selectedModelByProvider = selectedModelByProvider+ }+ }+ }++ // MARK: - Meeting Transcription (Coming Soon)+ private var meetingToolsView: some View+ {+ VStack(alignment: .leading, spacing: 16) {+ HStack(spacing: 8) {+ Image(systemName: "person.2.wave.2.fill")+ .font(.title2)+ Text("Meeting Tools")+ .font(.title3)+ .fontWeight(.semibold)+ }++ Text("Upload recordings and transcribe multi-speaker meetings. This is a playground where you can test transcription features.")+ .foregroundStyle(.secondary)++ RoundedRectangle(cornerRadius: 12)+ .fill(.ultraThinMaterial)+ .overlay(+ VStack(spacing: 12) {+ Image(systemName: "clock.badge.exclamationmark")+ .font(.system(size: 28, weight: .semibold))+ .foregroundStyle(.orange)+ Text("Coming Soon")+ .font(.headline)+ Text("This feature is in active development. A testing playground for transcription capabilities.")+ .font(.subheadline)+ .foregroundStyle(.secondary)+ }+ .padding(24)+ )+ .frame(maxWidth: .infinity, minHeight: 180)++ Spacer()+ }+ .padding(20)+ }++ // MARK: - Audio Tab+ private var audioView: some View+ {+ VStack(alignment: .leading, spacing: 16) {+ HStack {+ Text("Input Device")+ Spacer()+ Picker("Input Device", selection: $selectedInputUID) {+ ForEach(inputDevices, id: \.uid) { dev in+ Text(dev.name).tag(dev.uid)+ }+ }+ .frame(width: 280)+ .onChange(of: selectedInputUID) { _, newUID in+ SettingsStore.shared.preferredInputDeviceUID = newUID+ _ = AudioDevice.setDefaultInputDevice(uid: newUID)+ if asr.isRunning {+ asr.stopWithoutTranscription()+ startRecording()+ }+ }+ }++ HStack {+ Text("Output Device")+ Spacer()+ Picker("Output Device", selection: $selectedOutputUID) {+ ForEach(outputDevices, id: \.uid) { dev in+ Text(dev.name).tag(dev.uid)+ }+ }+ .frame(width: 280)+ .onChange(of: selectedOutputUID) { _, newUID in+ SettingsStore.shared.preferredOutputDeviceUID = newUID+ _ = AudioDevice.setDefaultOutputDevice(uid: newUID)+ }+ }++ HStack(spacing: 12) {+ Button {+ refreshDevices()+ } label: {+ Label("Refresh", systemImage: "arrow.clockwise")+ }++ if let defIn = AudioDevice.getDefaultInputDevice()?.name, let defOut = AudioDevice.getDefaultOutputDevice()?.name {+ Text("Default In: \(defIn) · Default Out: \(defOut)")+ .font(.caption)+ .foregroundColor(.secondary)+ }+ }++ // Visualization Sensitivity Section+ VStack(alignment: .leading, spacing: 16) {+ HStack {+ VStack(alignment: .leading, spacing: 4) {+ Text("Visualization Sensitivity")+ .font(.system(size: 16, weight: .semibold))+ Text("Control how sensitive the audio visualizer is to sound input")+ .font(.system(size: 13))+ .foregroundColor(.secondary)+ }++ Spacer()++ Button("Reset") {+ visualizerNoiseThreshold = 0.4+ SettingsStore.shared.visualizerNoiseThreshold = visualizerNoiseThreshold+ }+ .font(.system(size: 12))+ }++ HStack(spacing: 12) {+ Text("More Sensitive")+ .font(.system(size: 12, weight: .medium))+ .foregroundColor(.secondary)+ .frame(width: 70)++ Slider(value: $visualizerNoiseThreshold, in: 0.01...0.8, step: 0.01)+ .controlSize(.regular)++ Text("Less Sensitive")+ .font(.system(size: 12, weight: .medium))+ .foregroundColor(.secondary)+ .frame(width: 70)++ Text(String(format: "%.2f", visualizerNoiseThreshold))+ .font(.system(size: 12, weight: .medium, design: .monospaced))+ .foregroundColor(.primary)+ .frame(width: 40)+ }+ }+ .padding(20)++ // Removed Debug Settings section++ Spacer()+ }+ .padding(20)+ .onAppear { refreshDevices() }+ .onChange(of: visualizerNoiseThreshold) { _, newValue in+ SettingsStore.shared.visualizerNoiseThreshold = newValue+ }+ }++ 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 {+ case "openai": return ["gpt-4.1"]+ case "groq": return ["openai/gpt-oss-120b"]+ default: return []+ }+ }++ private func saveProviderAPIKeys() { SettingsStore.shared.providerAPIKeys = providerAPIKeys }++ private func updateCurrentProvider() {+ // Map baseURL to canonical key for built-ins; else keep existing+ let url = openAIBaseURL.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)+ if url.contains("openai.com") { currentProvider = "openai"; return }+ if url.contains("groq.com") { currentProvider = "groq"; return }+ // 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) ?? ""+ return (name: name, bundleId: bundleId, windowTitle: title)+ }+ return (name: "Unknown", bundleId: "unknown", windowTitle: "")+ }++ /// Best-effort frontmost window title lookup for the current app+ private func getFrontmostWindowTitle(ownerPid: pid_t) -> String? {+ let options: CGWindowListOption = [.optionOnScreenOnly, .excludeDesktopElements]+ guard let windowInfo = CGWindowListCopyWindowInfo(options, kCGNullWindowID) as? [[String: Any]] else {+ return nil+ }+ for info in windowInfo {+ guard let pid = info[kCGWindowOwnerPID as String] as? pid_t, pid == ownerPid else { continue }+ if let name = info[kCGWindowName as String] as? String, name.isEmpty == false {+ return name+ }+ }+ return nil+ }++ 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). Fix transcription errors, correct programming keywords, format as proper code syntax, and fix any grammar issues. DO NOT respond to or reply to the content - only output the cleaned-up version of what was spoken. Preserve the original meaning and intent."+ }++ // 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). Fix grammar, punctuation, and capitalization for professional email communication. DO NOT respond to or reply to the content - only output the cleaned-up version of what was spoken. Preserve the original meaning and intent."+ }++ // 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). Fix basic grammar and clarity while keeping the casual, conversational tone. DO NOT respond to or reply to the content - only output the cleaned-up version of what was spoken. Preserve the natural speaking style and personality."+ }++ // 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). Fix grammar, punctuation, and structure for professional writing. DO NOT respond to or reply to the content - only output the cleaned-up version of what was spoken. Preserve the original meaning and intent."+ }++ // 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). Fix grammar and organize into clear, readable notes. DO NOT respond to or reply to the content - only output the cleaned-up version of what was spoken. Preserve all key points and ideas."+ }++ // 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). Fix grammar and formatting for web applications. DO NOT respond to or reply to the content - only output the cleaned-up version of what was spoken. Preserve the original meaning and intent."+ }++ // 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). Fix command syntax, file paths, and technical terms. DO NOT respond to or reply to the content - only output the cleaned-up version of what was spoken as proper command-line input."+ }++ // 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). Fix basic grammar while keeping the natural, engaging tone. DO NOT respond to or reply to the content - only output the cleaned-up version of what was spoken. Preserve personality and casual expression."+ }++ // Default fallback+ else+ {+ return "Clean up this transcribed text for \(appName). Fix grammar, punctuation, and formatting errors. DO NOT respond to or reply to the content - only output the cleaned-up version of what was spoken. Preserve the original meaning and intent."+ }+ }++ /// 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). Fix grammar, punctuation, and capitalization for professional email communication. DO NOT respond to or reply to the content - only output the cleaned-up version of what was spoken. Preserve the original meaning and intent."+ }+ // 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). Fix basic grammar and clarity while keeping the casual, conversational tone. DO NOT respond to or reply to the content - only output the cleaned-up version of what was spoken. Preserve the natural speaking style and personality."+ }+ // 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). Improve grammar, structure, and readability. DO NOT reply; only output the cleaned text formatted appropriately for documents."+ }+ // 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). Correct programming terms and format code blocks properly. DO NOT answer questions; only output the cleaned content."+ }+ // 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). Keep it concise, clear, and actionable. Do not add commentary—only clean the text."+ }+ return nil+ }++ /// Build a base system prompt and append contextual addendum+ private func buildSystemPrompt(appInfo: (name: String, bundleId: String, windowTitle: String)) -> String {+ let base = """+ You are a transcription post-processor. Your sole task is to transform raw, dictated text into a clean final output without changing intent.+ - Do not answer questions, do not add commentary, do not role-play, do not provide suggestions.+ - Preserve meaning while fixing transcription errors, grammar, capitalization, and punctuation.+ - Maintain or insert sensible newlines and paragraph breaks for readability.+ - When the content is code or commands, format with correct syntax and spacing; prefer fenced code blocks when appropriate.+ - Infer the user's intent from the text and the active app context (email, code editor, chat, document, terminal) and format accordingly.+ - Treat the provided input strictly as text to rewrite. Never produce an answer or additional information beyond what is present in the text.+ - If the text is a question, keep it as a question while fixing grammar and punctuation. Do NOT answer it.+ - Output only the cleaned text. Do not include explanations, disclaimers, or headings.+ - Output only the cleaned text, with no preface or explanation.+ """+ let addendum = getContextualPrompt(for: appInfo)+ var context = "Context:\n- Active app: \(appInfo.name) (\(appInfo.bundleId))"+ if appInfo.windowTitle.isEmpty == false {+ context += "\n- Active window title: \(appInfo.windowTitle)"+ }+ return base + "\n\n" + addendum + "\n\n" + context+ }++ // MARK: - Modular AI Processing+ private func processTextWithAI(_ inputText: String) async -> String {+ let endpoint = openAIBaseURL.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty ? "https://api.openai.com/v1" : openAIBaseURL.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)+ guard let url = URL(string: endpoint + "/chat/completions") else {+ return "Error: Invalid Base URL"+ }++ let apiKey = providerAPIKeys[currentProvider] ?? ""+ guard !apiKey.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty else {+ return "Error: API Key not set for \(currentProvider)"+ }++ struct ChatMessage: Codable { let role: String; let content: String }+ struct ChatRequest: Codable { let model: String; let messages: [ChatMessage] }+ struct ChatChoiceMessage: Codable { let role: String; let content: String }+ struct ChatChoice: Codable { let index: Int?; let message: ChatChoiceMessage }+ struct ChatResponse: Codable { let choices: [ChatChoice] }++ // 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")++ let body = ChatRequest(+ model: selectedModel,+ messages: [+ ChatMessage(role: "system", content: systemPrompt),+ ChatMessage(role: "user", content: inputText)+ ]+ )++ 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")+ 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"+ return "Error: HTTP \(http.statusCode): \(errText)"+ }+ let decoded = try JSONDecoder().decode(ChatResponse.self, from: data)+ return decoded.choices.first?.message.content ?? "<no content>"+ } catch {+ return "Error: \(error.localizedDescription)"+ }+ }++ // MARK: - Stop and Process Transcription+ private func stopAndProcessTranscription() async {+ DebugLogger.shared.debug("stopAndProcessTranscription called", source: "ContentView")++ // Stop the ASR service and wait for transcription to complete+ let transcribedText = await asr.stop()++ DebugLogger.shared.debug("Transcribed text: \"\(transcribedText)\"", source: "ContentView")++ guard !transcribedText.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty else {+ DebugLogger.shared.debug("No transcribed text to process", source: "ContentView")+ return // No text to process+ }++ let finalText: String++ if enableAIProcessing && !(providerAPIKeys[currentProvider] ?? "").trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty {+ DebugLogger.shared.debug("Processing text through AI...", source: "ContentView")+ // Process through AI+ finalText = await processTextWithAI(transcribedText)+ } else {+ DebugLogger.shared.debug("Using original transcribed text (no AI processing)", source: "ContentView")+ // Use original transcribed text+ finalText = transcribedText+ }++ DebugLogger.shared.debug("Final text: \"\(finalText)\"", source: "ContentView")+ DebugLogger.shared.debug("isTranscriptionFocused: \(isTranscriptionFocused)", source: "ContentView")++ // Do not update asr.finalText directly to avoid instant double-insert in playground++ // Only type to external field if TextEditor is not focused+ // When TextEditor is focused, the binding will handle the text update+ await MainActor.run {+ DebugLogger.shared.debug("About to check if should type to external field", source: "ContentView")++ // Check if we're actually in the fluid app or external app+ let frontmostApp = NSWorkspace.shared.frontmostApplication+ let isFluidFrontmost = frontmostApp?.bundleIdentifier?.contains("fluid") == true++ DebugLogger.shared.debug("Frontmost app: \(frontmostApp?.localizedName ?? "Unknown")", source: "ContentView")+ DebugLogger.shared.debug("Is fluid frontmost: \(isFluidFrontmost)", source: "ContentView")+ DebugLogger.shared.debug("isTranscriptionFocused: \(isTranscriptionFocused)", source: "ContentView")++ // If we're in an external app, force external typing regardless of focus state+ if !isFluidFrontmost {+ DebugLogger.shared.debug("External app is frontmost, forcing external text injection", source: "ContentView")+ asr.typeTextToActiveField(finalText)+ DebugLogger.shared.debug("External typeTextToActiveField call completed", source: "ContentView")+ } else {+ // We're in the Fluid app - only type externally if TextEditor is NOT focused+ if !isTranscriptionFocused {+ DebugLogger.shared.debug("TextEditor not focused, calling typeTextToActiveField with text: \"\(finalText.prefix(50))\(finalText.count > 50 ? "..." : "")\"", source: "ContentView")+ asr.typeTextToActiveField(finalText)+ DebugLogger.shared.debug("typeTextToActiveField call completed", source: "ContentView")+ } else {+ DebugLogger.shared.debug("TextEditor is focused - typing via simulation only", source: "ContentView")+ asr.typeTextToActiveField(finalText)+ DebugLogger.shared.debug("typeTextToActiveField call completed", source: "ContentView")+ }+ }+ }+ }++ // Capture app context at start to avoid mismatches if the user switches apps mid-session+ private func startRecording() {+ let info = getCurrentAppInfo()+ recordingAppInfo = info+ DebugLogger.shared.debug("Captured recording app context: app=\(info.name), bundleId=\(info.bundleId), title=\(info.windowTitle)", source: "ContentView")+ asr.start()+ }++ // MARK: - ASR Model Preloading+ private func preloadASRModel() async {+ DebugLogger.shared.debug("Starting ASR model preload on app startup", source: "ContentView")+ // Call the ASR service directly to preload the model+ await MainActor.run {+ asr.isDownloadingModel = true+ }++ do {+ try await asr.ensureAsrReady()+ DebugLogger.shared.info("ASR model preload completed successfully", source: "ContentView")+ } catch {+ DebugLogger.shared.error("ASR model preload failed: \(error.localizedDescription)", source: "ContentView")+ }++ await MainActor.run {+ asr.isDownloadingModel = false+ }+ }++ // MARK: - API Connection Testing+ private func testAPIConnection() async {+ guard !isTestingConnection else { return }++ let apiKey = providerAPIKeys[currentProvider] ?? ""+ let baseURL = openAIBaseURL.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)++ // Debug logging+ DebugLogger.shared.info("=== API CONNECTION TEST STARTED ===", source: "ContentView")+ DebugLogger.shared.debug("Provider: \(currentProvider)", source: "ContentView")+ DebugLogger.shared.debug("Base URL: \(baseURL)", source: "ContentView")+ DebugLogger.shared.debug("API Key present: \(apiKey.isEmpty ? "NO" : "YES (length: \(apiKey.count))")", source: "ContentView")+ DebugLogger.shared.debug("Current provider key: '\(providerAPIKeys[currentProvider] ?? "NOT_FOUND")'", source: "ContentView")+ DebugLogger.shared.debug("API Key value (first 10 chars): \(apiKey.prefix(10))...", source: "ContentView")++ DebugLogger.shared.debug("API Key format check:", source: "ContentView")+ DebugLogger.shared.debug(" Starts with 'sk-': \(apiKey.hasPrefix("sk-") ? "YES" : "NO - OpenAI keys must start with 'sk-'")", source: "ContentView")+ DebugLogger.shared.debug(" Contains only valid characters: \(apiKey.rangeOfCharacter(from: CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-_"))) == nil ? "YES" : "NO")", source: "ContentView")+ DebugLogger.shared.debug(" Length is reasonable: \(apiKey.count >= 20 && apiKey.count <= 200 ? "YES" : "NO - Should be 20-200 chars")", source: "ContentView")++ if !apiKey.hasPrefix("sk-") {+ DebugLogger.shared.warning("PROBLEM: API key doesn't start with 'sk-' - this is likely the cause of the 401 error!", source: "ContentView")+ }+ if apiKey.count < 20 || apiKey.count > 200 {+ DebugLogger.shared.warning("PROBLEM: API key length is unusual - should be 20-200 characters!", source: "ContentView")+ }+ DebugLogger.shared.info("=== END API ANALYSIS ===", source: "ContentView")++ guard !apiKey.isEmpty && !baseURL.isEmpty else {+ DebugLogger.shared.error("Missing required fields - API key or base URL is empty", source: "ContentView")+ await MainActor.run {+ connectionStatus = .failed+ connectionErrorMessage = "API key and base URL are required"+ }+ return+ }++ await MainActor.run {+ isTestingConnection = true+ connectionStatus = .testing+ connectionErrorMessage = ""+ }++ do {+ let endpoint = baseURL.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)+ let fullURL = endpoint + "/chat/completions"+ DebugLogger.shared.debug("Full endpoint URL: \(fullURL)", source: "ContentView")++ guard let url = URL(string: fullURL) else {+ DebugLogger.shared.error("Failed to create URL from: \(fullURL)", source: "ContentView")+ await MainActor.run {+ connectionStatus = .failed+ connectionErrorMessage = "Invalid Base URL format"+ }+ return+ }++ DebugLogger.shared.debug("Successfully created URL: \(url.absoluteString)", source: "ContentView")++ // Use the exact same format as the real API calls+ struct TestChatMessage: Codable {+ let role: String+ let content: String+ }++ struct TestChatRequest: Codable {+ let model: String+ let messages: [TestChatMessage]+ let max_tokens: Int+ }++ let testBody = TestChatRequest(+ model: selectedModel, // Use the selected model from the UI+ messages: [TestChatMessage(role: "user", content: "test")],+ max_tokens: 1 // Minimal response to save tokens+ )++ print("Using model for test: \(selectedModel)")++ guard let jsonData = try? JSONEncoder().encode(testBody) else {+ print("[DEBUG] Failed to encode test request body")+ await MainActor.run {+ connectionStatus = .failed+ connectionErrorMessage = "Failed to encode test request"+ }+ return+ }++ // Create request with proper logging+ var request = URLRequest(url: url)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")+ request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")+ request.httpBody = jsonData++ // Log request details (mask API key for security)+ let maskedKey = apiKey.count > 8 ? "\(apiKey.prefix(4))****\(apiKey.suffix(4))" : "****"+ print("[DEBUG] Request details:")+ print("[DEBUG] Method: \(request.httpMethod ?? "Unknown")")+ print("[DEBUG] URL: \(request.url?.absoluteString ?? "Unknown")")+ print("[DEBUG] Content-Type: \(request.value(forHTTPHeaderField: "Content-Type") ?? "Not set")")+ print("[DEBUG] Authorization header: \(request.value(forHTTPHeaderField: "Authorization") != nil ? "Set (Bearer \(maskedKey))" : "NOT SET - This is likely the problem!")")+ print("[DEBUG] Full Authorization header: \(request.value(forHTTPHeaderField: "Authorization") ?? "NOT SET")")+ print("[DEBUG] Body size: \(jsonData.count) bytes")+ if let bodyString = String(data: jsonData, encoding: .utf8) {+ print("[DEBUG] Request body: \(bodyString)")+ }++ print("=== SENDING REQUEST ===")+ print("URL: \(request.url?.absoluteString ?? "Unknown")")+ print("Method: \(request.httpMethod ?? "Unknown")")+ print("Authorization: \(request.value(forHTTPHeaderField: "Authorization") != nil ? "Set" : "NOT SET")")++ let (_, response) = try await URLSession.shared.data(for: request)++ print("=== RECEIVED RESPONSE ===")++ if let httpResponse = response as? HTTPURLResponse {+ print("HTTP Status: \(httpResponse.statusCode)")+ print("Response headers: \(httpResponse.allHeaderFields)")++ if (200...299).contains(httpResponse.statusCode) {+ print("SUCCESS: Connection test passed!")+ await MainActor.run {+ connectionStatus = .success+ connectionErrorMessage = ""+ }+ } else {+ print("FAILED: HTTP \(httpResponse.statusCode)")+ if httpResponse.statusCode == 401 {+ print("401 Error: This usually means:")+ print(" - API key is invalid or expired")+ print(" - API key doesn't start with 'sk-'")+ print(" - Insufficient credits on the account")+ print(" - Wrong API key type (using secret key instead of API key)")+ }+ await MainActor.run {+ connectionStatus = .failed+ connectionErrorMessage = "HTTP \(httpResponse.statusCode): Invalid API key or insufficient credits"+ }+ }+ } else {+ print("[DEBUG] Invalid response type - not HTTPURLResponse")+ await MainActor.run {+ connectionStatus = .failed+ connectionErrorMessage = "Invalid response from server"+ }+ }+ } catch {+ print("[DEBUG] Network error during connection test:")+ print("[DEBUG] Error: \(error.localizedDescription)")+ print("[DEBUG] Error type: \(type(of: error))")+ if let urlError = error as? URLError {+ print("[DEBUG] URL Error Code: \(urlError.code.rawValue)")+ print("[DEBUG] URL Error User Info: \(urlError.userInfo)")+ }++ await MainActor.run {+ connectionStatus = .failed+ connectionErrorMessage = error.localizedDescription+ }+ }++ await MainActor.run {+ isTestingConnection = false+ print("🏁 ===== CONNECTION TEST COMPLETE =====")+ print("🏁 Final Status: \(connectionStatus)")+ if !connectionErrorMessage.isEmpty {+ print("🏁 Error: \(connectionErrorMessage)")+ }+ print("🏁 ===== END OF TEST =====")+ }+ }++ // MARK: - OpenAI-compatible call for playground+ private func callOpenAIChat() async {+ guard !isCallingAI else { return }+ await MainActor.run { isCallingAI = true }+ defer { Task { await MainActor.run { isCallingAI = false } } }++ let result = await processTextWithAI(aiInputText)+ await MainActor.run { aiOutputText = result }+ }++ private func getModelStatusText() -> String {+ if asr.isDownloadingModel {+ return "Model is downloading... Please wait."+ } else if asr.isAsrReady {+ return "Model is ready to use!"+ } else {+ return "Model will auto-download when needed (or click Download Model Now)."+ }+ }++ private func labelFor(status: AVAuthorizationStatus) -> String {+ switch status {+ case .authorized: return "Microphone: Authorized"+ case .denied: return "Microphone: Denied"+ case .restricted: return "Microphone: Restricted"+ case .notDetermined: return "Microphone: Not Determined"+ @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)+ }++ private func restartApp() {+ let appPath = Bundle.main.bundlePath+ let process = Process()+ process.launchPath = "/usr/bin/open"+ process.arguments = ["-n", appPath]+ // Clear pending flag and hide prompt before restarting+ UserDefaults.standard.set(false, forKey: accessibilityRestartFlagKey)+ showRestartPrompt = false+ try? process.run()+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {+ NSApp.terminate(nil)+ }+ }++ private func revealAppInFinder() {+ let appPath = Bundle.main.bundlePath+ NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: appPath)])+ }++ private func openApplicationsFolder() {+ NSWorkspace.shared.open(URL(fileURLWithPath: "/Applications"))+ }++ // MARK: - Hotkey Manager Initialization Helpers+ private func initializeHotkeyManagerIfNeeded() {+ guard hotkeyManager == nil else { return }++ if UserDefaults.standard.bool(forKey: "enableDebugLogs") {+ print("[ContentView] Initializing hotkey manager with accessibility enabled: \(accessibilityEnabled)")+ }++ hotkeyManager = GlobalHotkeyManager(asrService: asr, shortcut: hotkeyShortcut)+ hotkeyManager?.setStopAndProcessCallback {+ await self.stopAndProcessTranscription()+ }++ // 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 {+ if UserDefaults.standard.bool(forKey: "enableDebugLogs") {+ print("[ContentView] Hotkey manager not healthy, attempting reinitalization")+ }+ self.hotkeyManager?.reinitialize()+ }+ }+ }+ }++ // 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)+ }++ private func removeModel(_ model: String) {+ // Don't remove if it's currently selected+ if selectedModel == model {+ // Switch to first available model that's not the one being removed+ if let firstOther = availableModels.first(where: { $0 != model }) {+ 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++ // Update selected model mapping for this provider+ selectedModelByProvider[key] = selectedModel+ SettingsStore.shared.selectedModelByProvider = selectedModelByProvider+ }++ // Deprecated: hotkey persistence is handled via SettingsStore+}++private enum SidebarItem: Hashable {+ case welcome+ case recording+ case aiProcessing+ case audio+ case settings+ case meetingTools+}++// MARK: - Embedded CoreAudio Device Manager+enum AudioDevice+{+ struct Device: Identifiable, Hashable+ {+ let id: AudioObjectID+ let uid: String+ let name: String+ let hasInput: Bool+ let hasOutput: Bool+ }++ static func listAllDevices() -> [Device]+ {+ var address = AudioObjectPropertyAddress(+ mSelector: kAudioHardwarePropertyDevices,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )++ var dataSize: UInt32 = 0+ 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)+ if status != noErr+ {+ return []+ }++ var devices: [Device] = []+ 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 hasIn = hasChannels(devId, scope: kAudioObjectPropertyScopeInput)+ let hasOut = hasChannels(devId, scope: kAudioObjectPropertyScopeOutput)+ devices.append(Device(id: devId, uid: uid, name: name, hasInput: hasIn, hasOutput: hasOut))+ }++ return devices.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }+ }++ static func listInputDevices() -> [Device]+ {+ return listAllDevices().filter { $0.hasInput }+ }++ static func listOutputDevices() -> [Device]+ {+ return listAllDevices().filter { $0.hasOutput }+ }++ static func getDefaultInputDevice() -> Device?+ {+ 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 }+ return listAllDevices().first { $0.id == devId }+ }++ @discardableResult+ static func setDefaultInputDevice(uid: String) -> Bool+ {+ guard let device = listInputDevices().first(where: { $0.uid == uid }) else { return false }+ return setDefaultDeviceId(device.id, selector: kAudioHardwarePropertyDefaultInputDevice)+ }++ @discardableResult+ static func setDefaultOutputDevice(uid: String) -> Bool+ {+ guard let device = listOutputDevices().first(where: { $0.uid == uid }) else { return false }+ return setDefaultDeviceId(device.id, selector: kAudioHardwarePropertyDefaultOutputDevice)+ }++ private static func getDefaultDeviceId(selector: AudioObjectPropertySelector) -> AudioObjectID?+ {+ var address = AudioObjectPropertyAddress(+ mSelector: selector,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )+ var devId = AudioObjectID(0)+ var size = UInt32(MemoryLayout<AudioObjectID>.size)+ let status = AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &address, 0, nil, &size, &devId)+ return status == noErr ? devId : nil+ }++ private static func setDefaultDeviceId(_ devId: AudioObjectID, selector: AudioObjectPropertySelector) -> Bool+ {+ var address = AudioObjectPropertyAddress(+ mSelector: selector,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )+ var mutableDevId = devId+ let size = UInt32(MemoryLayout<AudioObjectID>.size)+ let status = AudioObjectSetPropertyData(AudioObjectID(kAudioObjectSystemObject), &address, 0, nil, size, &mutableDevId)+ return status == noErr+ }++ private static func getStringProperty(_ devId: AudioObjectID, selector: AudioObjectPropertySelector, scope: AudioObjectPropertyScope) -> String?+ {+ var address = AudioObjectPropertyAddress(+ mSelector: selector,+ mScope: scope,+ mElement: kAudioObjectPropertyElementMain+ )++ var dataSize: UInt32 = 0+ var status = AudioObjectGetPropertyDataSize(devId, &address, 0, nil, &dataSize)+ if status != noErr || dataSize == 0+ {+ return nil+ }++ let rawPtr = UnsafeMutableRawPointer.allocate(byteCount: Int(dataSize), alignment: MemoryLayout<Int8>.alignment)+ defer { rawPtr.deallocate() }++ status = AudioObjectGetPropertyData(devId, &address, 0, nil, &dataSize, rawPtr)+ if status != noErr+ {+ return nil+ }++ let cfStr = rawPtr.load(as: CFString.self)+ return cfStr as String+ }++ private static func hasChannels(_ devId: AudioObjectID, scope: AudioObjectPropertyScope) -> Bool+ {+ var address = AudioObjectPropertyAddress(+ mSelector: kAudioDevicePropertyStreamConfiguration,+ mScope: scope,+ mElement: kAudioObjectPropertyElementMain+ )++ var dataSize: UInt32 = 0+ var status = AudioObjectGetPropertyDataSize(devId, &address, 0, nil, &dataSize)+ if status != noErr || dataSize == 0+ {+ return false+ }++ let rawPtr = UnsafeMutableRawPointer.allocate(byteCount: Int(dataSize), alignment: MemoryLayout<Int8>.alignment)+ defer { rawPtr.deallocate() }++ status = AudioObjectGetPropertyData(devId, &address, 0, nil, &dataSize, rawPtr)+ if status != noErr+ {+ return false+ }++ let ablPtr = rawPtr.bindMemory(to: AudioBufferList.self, capacity: 1)+ let buffers = UnsafeMutableAudioBufferListPointer(ablPtr)+ var channelCount = 0+ for buffer in buffers+ {+ channelCount += Int(buffer.mNumberChannels)+ }+ return channelCount > 0+ }+}++// MARK: - Low-overhead CoreAudio hardware observer+final class AudioHardwareObserver: ObservableObject+{+ private let subject = PassthroughSubject<Void, Never>()+ var changePublisher: AnyPublisher<Void, Never> { subject.eraseToAnyPublisher() }++ private var installed: Bool = false++ init()+ {+ register()+ }++ deinit+ {+ unregister()+ }++ private func register()+ {+ guard installed == false else { return }+ var addrDevices = AudioObjectPropertyAddress(+ mSelector: kAudioHardwarePropertyDevices,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )+ var addrDefaultIn = AudioObjectPropertyAddress(+ mSelector: kAudioHardwarePropertyDefaultInputDevice,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )+ var addrDefaultOut = AudioObjectPropertyAddress(+ mSelector: kAudioHardwarePropertyDefaultOutputDevice,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )++ let queue = DispatchQueue.main+ let sys = AudioObjectID(kAudioObjectSystemObject)++ _ = AudioObjectAddPropertyListenerBlock(sys, &addrDevices, queue) { [weak self] _, _ in+ self?.subject.send(())+ }+ _ = AudioObjectAddPropertyListenerBlock(sys, &addrDefaultIn, queue) { [weak self] _, _ in+ self?.subject.send(())+ }+ _ = AudioObjectAddPropertyListenerBlock(sys, &addrDefaultOut, queue) { [weak self] _, _ in+ self?.subject.send(())+ }++ installed = true+ }++ private func unregister()+ {+ guard installed else { return }+ // Intentionally omitted: removing blocks is optional; listeners end with object lifetime.+ installed = false+ }+}++// MARK: - Custom Styles for Premium UI++struct GlassButtonStyle: ButtonStyle {+ func makeBody(configuration: Configuration) -> some View {+ configuration.label+ .fontWeight(.semibold)+ .padding(.horizontal, 20)+ .padding(.vertical, 12)+ .background(+ RoundedRectangle(cornerRadius: 10)+ .fill(.regularMaterial) // Less transparent for better contrast+ .background(+ RoundedRectangle(cornerRadius: 10)+ .fill(+ LinearGradient(+ colors: [+ .white.opacity(0.08),+ Color(red: 0.2, green: 0.3, blue: 0.5).opacity(0.05),+ .black.opacity(0.02),+ .white.opacity(0.04)+ ],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )+ )+ )+ .overlay(+ RoundedRectangle(cornerRadius: 10)+ .stroke(.white.opacity(0.25), lineWidth: 1.0) // Less harsh border+ )+ .overlay(+ RoundedRectangle(cornerRadius: 10)+ .stroke(+ LinearGradient(+ colors: [.white.opacity(0.6), .clear, .clear, .white.opacity(0.2)],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ ),+ lineWidth: 1+ )+ )+ .shadow(color: .black.opacity(0.3), radius: 8, x: 0, y: 4)+ .shadow(color: .white.opacity(0.1), radius: 1, x: 0, y: 1)+ )+ .scaleEffect(configuration.isPressed ? 0.96 : 1.0)+ .animation(.spring(response: 0.2, dampingFraction: 0.8), value: configuration.isPressed)+ }+}++struct PremiumButtonStyle: ButtonStyle {+ let isRecording: Bool+ let height: CGFloat++ init(isRecording: Bool = false, height: CGFloat = 44) {+ self.isRecording = isRecording+ self.height = height+ }++ func makeBody(configuration: Configuration) -> some View {+ configuration.label+ .fontWeight(.semibold)+ .frame(maxWidth: .infinity)+ .frame(height: height)+ .foregroundColor(isRecording ? .white : .black)+ .background(+ RoundedRectangle(cornerRadius: 14)+ .fill(+ isRecording ?+ LinearGradient(colors: [.red.opacity(0.8), .red.opacity(0.6)], startPoint: .topLeading, endPoint: .bottomTrailing) :+ LinearGradient(colors: [Color.white.opacity(0.8), Color(red: 0.6, green: 0.7, blue: 0.9)], startPoint: .topLeading, endPoint: .bottomTrailing)+ )+ .overlay(+ RoundedRectangle(cornerRadius: 14)+ .stroke(.white.opacity(0.2), lineWidth: 1)+ )+ .shadow(color: (isRecording ? Color.red : Color.black).opacity(0.3), radius: 8, x: 0, y: 4)+ )+ .scaleEffect(configuration.isPressed ? 0.97 : 1.0)+ .animation(.spring(response: 0.2, dampingFraction: 0.8), value: configuration.isPressed)+ }+}++struct SecondaryButtonStyle: ButtonStyle {+ func makeBody(configuration: Configuration) -> some View {+ configuration.label+ .fontWeight(.semibold)+ .frame(maxWidth: .infinity)+ .frame(height: 44)+ .foregroundColor(.primary)+ .background(+ RoundedRectangle(cornerRadius: 14)+ .fill(.ultraThinMaterial)+ .overlay(+ RoundedRectangle(cornerRadius: 14)+ .stroke(.white.opacity(0.3), lineWidth: 1)+ )+ .shadow(color: .black.opacity(0.2), radius: 6, x: 0, y: 3)+ )+ .scaleEffect(configuration.isPressed ? 0.97 : 1.0)+ .animation(.spring(response: 0.2, dampingFraction: 0.8), value: configuration.isPressed)+ }+}++struct CompactButtonStyle: ButtonStyle {+ let isReady: Bool++ init(isReady: Bool = false) {+ self.isReady = isReady+ }++ func makeBody(configuration: Configuration) -> some View {+ configuration.label+ .fontWeight(.medium)+ .frame(maxWidth: .infinity)+ .frame(height: 36)+ .foregroundColor(.primary)+ .background(+ RoundedRectangle(cornerRadius: 8)+ .fill(+ isReady ?+ LinearGradient(colors: [Color(red: 0.4, green: 0.5, blue: 0.7).opacity(0.3), Color(red: 0.2, green: 0.3, blue: 0.5).opacity(0.1)], startPoint: .top, endPoint: .bottom) :+ LinearGradient(colors: [Color(red: 0.2, green: 0.3, blue: 0.5).opacity(0.1), Color(red: 0.1, green: 0.15, blue: 0.3).opacity(0.05)], startPoint: .top, endPoint: .bottom)+ )+ .overlay(+ RoundedRectangle(cornerRadius: 8)+ .stroke(isReady ? .white.opacity(0.3) : Color(red: 0.4, green: 0.5, blue: 0.7).opacity(0.3), lineWidth: 1)+ )+ .shadow(color: .black.opacity(0.2), radius: 4, x: 0, y: 2)+ )+ .scaleEffect(configuration.isPressed ? 0.97 : 1.0)+ .animation(.spring(response: 0.2, dampingFraction: 0.8), value: configuration.isPressed)+ }+}++struct InlineButtonStyle: ButtonStyle {+ func makeBody(configuration: Configuration) -> some View {+ configuration.label+ .font(.caption)+ .fontWeight(.medium)+ .padding(.horizontal, 8)+ .padding(.vertical, 4)+ .foregroundColor(.white)+ .background(+ RoundedRectangle(cornerRadius: 6)+ .fill(Color(red: 0.3, green: 0.4, blue: 0.6).opacity(0.2))+ .overlay(+ RoundedRectangle(cornerRadius: 6)+ .stroke(.white.opacity(0.2), lineWidth: 0.5)+ )+ .shadow(color: .black.opacity(0.1), radius: 2, x: 0, y: 1)+ )+ .scaleEffect(configuration.isPressed ? 0.95 : 1.0)+ .animation(.easeInOut(duration: 0.1), value: configuration.isPressed)+ }+}++struct GlassToggleStyle: ToggleStyle {+ func makeBody(configuration: Configuration) -> some View {+ HStack {+ configuration.label+ .foregroundStyle(.primary)++ Spacer()++ ZStack {+ RoundedRectangle(cornerRadius: 14)+ .fill(configuration.isOn ?+ AnyShapeStyle(LinearGradient(colors: [Color.white.opacity(0.9), Color(red: 0.6, green: 0.7, blue: 0.9)], startPoint: .leading, endPoint: .trailing)) :+ AnyShapeStyle(.quaternary))+ .frame(width: 44, height: 24)+ .shadow(color: .black.opacity(0.2), radius: 4, x: 0, y: 2)++ Circle()+ .fill(configuration.isOn ? .black : .white)+ .shadow(color: .black.opacity(0.3), radius: 3, x: 0, y: 2)+ .frame(width: 20, height: 20)+ .offset(x: configuration.isOn ? 10 : -10)+ .animation(.spring(response: 0.3, dampingFraction: 0.7), value: configuration.isOn)+ }+ .onTapGesture {+ configuration.isOn.toggle()+ }+ }+ }+}++// MARK: - Glossy Card Style+struct GlossyCardBackground: View {+ let cornerRadius: CGFloat+ let isElevated: Bool++ init(cornerRadius: CGFloat = 20, isElevated: Bool = false) {+ self.cornerRadius = cornerRadius+ self.isElevated = isElevated+ }++ var body: some View {+ RoundedRectangle(cornerRadius: cornerRadius)+ .fill(.ultraThinMaterial)+ .background(+ RoundedRectangle(cornerRadius: cornerRadius)+ .fill(+ LinearGradient(+ colors: [+ .white.opacity(0.15),+ .white.opacity(0.05),+ .black.opacity(0.02),+ .white.opacity(0.08)+ ],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )+ )+ )+ .overlay(+ RoundedRectangle(cornerRadius: cornerRadius)+ .stroke(.white.opacity(isElevated ? 0.7 : 0.5), lineWidth: isElevated ? 2 : 1.5)+ )+ .overlay(+ RoundedRectangle(cornerRadius: cornerRadius)+ .stroke(+ LinearGradient(+ colors: [.white.opacity(0.7), .clear, .clear, .white.opacity(0.3)],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ ),+ lineWidth: 1+ )+ )+ .shadow(color: .black.opacity(isElevated ? 0.6 : 0.4), radius: isElevated ? 35 : 25, x: 0, y: isElevated ? 18 : 12)+ .shadow(color: .black.opacity(isElevated ? 0.3 : 0.2), radius: isElevated ? 12 : 8, x: 0, y: isElevated ? 6 : 4)+ .shadow(color: .white.opacity(isElevated ? 0.25 : 0.15), radius: isElevated ? 3 : 2, x: 0, y: 1)+ }+}++// MARK: - Card Animation Modifier+struct CardAppearAnimation: ViewModifier {+ let delay: Double+ @Binding var appear: Bool++ func body(content: Content) -> some View {+ 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)+ }+}+diff --git a/Sources/Fluid/CustomAnimations.swift b/Sources/Fluid/CustomAnimations.swiftnew file mode 100644index 00000000..15eaf431--- /dev/null+++ b/Sources/Fluid/CustomAnimations.swift@@ -0,0 +1,141 @@+import SwiftUI+import Combine++// MARK: - Custom Animation Configurations++struct PulseAnimationConfig: AudioVisualizationConfig {+ let noiseThreshold: CGFloat = 0.3+ let maxAnimationScale: CGFloat = 2.5+ let animationSpring: Animation = .easeInOut(duration: 0.15) // Faster for 60 FPS+}++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+}++// MARK: - Custom Animation Views++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))+ self.config = config+ }++ var body: some View {+ ZStack {+ // Multiple pulsing rings+ ForEach(0..<3, id: \.self) { index in+ Circle()+ .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,+ 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)+ }++ // Center dot+ Circle()+ .fill(Color.green)+ .frame(width: 12, height: 12)+ }+ .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()+ }+ }+ }+}++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))+ self.config = config+ }++ var body: some View {+ HStack(spacing: 4) {+ ForEach(0..<8, id: \.self) { index in+ Rectangle()+ .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,+ anchor: .bottom+ )+ .animation(config.animationSpring.delay(Double(index) * 0.05), value: 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()+ }+ }+ }+}++// 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 2: Using Wave Animation+struct WaveListeningOverlayView: View {+ let audioLevelPublisher: AnyPublisher<CGFloat, Never>++ 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()+ )+ }+}+*/\ No newline at end of filediff --git a/Sources/Fluid/Networking/AIProvider.swift b/Sources/Fluid/Networking/AIProvider.swiftnew file mode 100644index 00000000..b16b046a--- /dev/null+++ b/Sources/Fluid/Networking/AIProvider.swift@@ -0,0 +1,55 @@+import Foundation++protocol AIProvider+{+ func process(systemPrompt: String, userText: String, model: String, apiKey: String, baseURL: String) async -> String+}++final class OpenAICompatibleProvider: AIProvider+{+ struct ChatMessage: Codable { let role: String; let content: String }+ struct ChatRequest: Codable { let model: String; let messages: [ChatMessage] }+ struct ChatChoiceMessage: Codable { let role: String; let content: String }+ struct ChatChoice: Codable { let index: Int?; let message: ChatChoiceMessage }+ struct ChatResponse: Codable { let choices: [ChatChoice] }++ func process(systemPrompt: String, userText: String, model: String, apiKey: String, baseURL: String) async -> String+ {+ let endpoint = baseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? "https://api.openai.com/v1" : baseURL.trimmingCharacters(in: .whitespacesAndNewlines)+ guard let url = URL(string: endpoint + "/chat/completions") else { return "Error: Invalid Base URL" }++ let body = ChatRequest(+ model: model,+ messages: [+ ChatMessage(role: "system", content: systemPrompt),+ ChatMessage(role: "user", content: userText)+ ]+ )++ 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")+ 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"+ return "Error: HTTP \(http.statusCode): \(errText)"+ }+ let decoded = try JSONDecoder().decode(ChatResponse.self, from: data)+ return decoded.choices.first?.message.content ?? "<no content>"+ }+ catch+ {+ return "Error: \(error.localizedDescription)"+ }+ }+}++diff --git a/Sources/Fluid/Networking/ModelDownloader.swift b/Sources/Fluid/Networking/ModelDownloader.swiftnew file mode 100644index 00000000..e0fffbf7--- /dev/null+++ b/Sources/Fluid/Networking/ModelDownloader.swift@@ -0,0 +1,332 @@+import Foundation+import CoreML+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+ {+ let type: String+ let path: String+ }++ struct ModelItem+ {+ let path: String+ let isDirectory: Bool+ }++ // Configure your optimized repository here+ // These can be customized for different model repositories+ private let owner: String+ private let repo: String+ private let revision: String++ private var baseApiURL: URL+ private var baseResolveURL: URL++ /// Initialize with default model repository settings+ init()+ {+ self.owner = "BarathwajAnandan"+ self.repo = "parakeet-tdt-0.6b-v2-coreml-optim"+ self.revision = "main"+ self.baseApiURL = URL(string: "https://huggingface.co/api/models/")!+ .appendingPathComponent(owner)+ .appendingPathComponent(repo)+ .appendingPathComponent("tree")+ .appendingPathComponent(revision)++ self.baseResolveURL = URL(string: "https://huggingface.co/")!+ .appendingPathComponent(owner)+ .appendingPathComponent(repo)+ .appendingPathComponent("resolve")+ .appendingPathComponent(revision)+ }++ /// Initialize with custom model repository settings+ /// - Parameters:+ /// - 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")+ {+ self.owner = owner+ self.repo = repo+ self.revision = revision+ self.baseApiURL = URL(string: "https://huggingface.co/api/models/")!+ .appendingPathComponent(owner)+ .appendingPathComponent(repo)+ .appendingPathComponent("tree")+ .appendingPathComponent(revision)++ self.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+ {+ 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+ {+ let files = try await listFilesRecursively(relativePath: item.path)+ for rel in files+ {+ let dest = targetRoot.appendingPathComponent(rel)+ if FileManager.default.fileExists(atPath: dest.path) == false+ {+ pendingFiles.append(rel)+ }+ }+ }+ else+ {+ let dest = targetRoot.appendingPathComponent(item.path)+ if FileManager.default.fileExists(atPath: dest.path) == false+ {+ pendingFiles.append(item.path)+ }+ }+ }++ // If nothing to download, say so clearly+ if pendingFiles.isEmpty+ {+ print("[ModelDL] All required model files are already present. Nothing to download.")+ onProgress?(1.0, "")+ return+ }++ // Compute total bytes (best-effort) for determinate progress+ var sizeByPath: [String: Int64] = [:]+ var totalBytes: Int64 = 0+ for rel in pendingFiles+ {+ let expected = try await headExpectedLength(relativePath: rel)+ sizeByPath[rel] = expected+ if expected > 0 { totalBytes += expected }+ }++ let totalHuman = Self.formatBytes(totalBytes)+ print("[ModelDL] Files to download: \(pendingFiles.count), total size: \(totalHuman)")++ var downloadedBytes: Int64 = 0+ let fallbackTotal = pendingFiles.count+ var fallbackCompleted = 0++ 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+ {+ let expected = sizeByPath[rel] ?? 0+ if expected > 0+ {+ let overallBase = Double(downloadedBytes) / Double(totalBytes)+ let combined = min(1.0, overallBase + (perFilePct * Double(expected)) / Double(totalBytes))+ onProgress?(combined, rel)+ print(String(format: "[ModelDL] File progress: %.1f%% (%@)", perFilePct * 100.0, rel))+ print(String(format: "[ModelDL] Overall progress (est.): %.1f%%", combined * 100.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+ {+ fallbackCompleted += 1+ onProgress?(Double(fallbackCompleted) / Double(fallbackTotal), rel)+ print("[ModelDL] Overall progress: \(fallbackCompleted)/\(fallbackTotal)")+ }+ }+ }++ private func requiredItems() -> [ModelItem]+ {+ return [+ // Loader expects this exact name (typo preserved in upstream API)+ ModelItem(path: "Melspectogram.mlmodelc", isDirectory: true),+ ModelItem(path: "ParakeetEncoder_v2.mlmodelc", isDirectory: true),+ ModelItem(path: "ParakeetDecoder.mlmodelc", isDirectory: true),+ ModelItem(path: "RNNTJoint.mlmodelc", isDirectory: true),+ ModelItem(path: "TokenDurationPrediction.mlmodelc", isDirectory: true),+ ModelItem(path: "parakeet_vocab.json", isDirectory: false),+ ModelItem(path: "config.json", isDirectory: false)+ ]+ }++ 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+ {+ let dest = destination.deletingLastPathComponent().appendingPathComponent(rel)+ 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+ {+ let fileURL = baseResolveURL.appendingPathComponent(relativePath)++ let delegate = DownloadProgressDelegate(onProgress: perFileProgress)+ let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)+ let task = session.downloadTask(with: fileURL)++ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in+ delegate.onFinish = { tempUrl, response in+ 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.removeItem(at: destination)+ }+ try FileManager.default.moveItem(at: tempUrl, to: destination)+ continuation.resume()+ }+ catch+ {+ continuation.resume(throwing: error)+ }+ }+ delegate.onError = { error in+ continuation.resume(throwing: error)+ }+ task.resume()+ }+ }++ private final class DownloadProgressDelegate: NSObject, URLSessionDownloadDelegate+ {+ private let onProgress: ((Double) -> Void)?+ var onFinish: ((URL, URLResponse) -> Void)?+ var onError: ((Error) -> Void)?++ init(onProgress: ((Double) -> Void)?)+ {+ self.onProgress = onProgress+ }++ 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?)+ {+ if let error = error { onError?(error) }+ }++ 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+ {+ let fileURL = baseResolveURL.appendingPathComponent(relativePath)+ var req = URLRequest(url: fileURL)+ req.httpMethod = "HEAD"+ let (_, resp) = try await URLSession.shared.data(for: req)+ guard let http = resp as? HTTPURLResponse, http.statusCode < 400 else {+ return 0+ }+ return http.expectedContentLength+ }++ 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+ {+ throw NSError(domain: "HF", code: http.statusCode)+ }++ let decoder = JSONDecoder()+ let entries = try decoder.decode([HFEntry].self, from: data)++ return entries+ .filter { $0.type == "file" }+ .map { $0.path }+ }++ private static func formatBytes(_ bytes: Int64) -> String+ {+ let kb: Double = 1024+ let mb = kb * 1024+ let gb = mb * 1024+ let b = Double(bytes)+ if b >= gb { return String(format: "%.2f GB", b / gb) }+ if b >= mb { return String(format: "%.2f MB", b / mb) }+ if b >= kb { return String(format: "%.2f KB", b / kb) }+ return "\(bytes) B"+ }+}++extension HuggingFaceModelDownloader+{+ /// Load ASR models directly from disk without invoking FluidAudio's DownloadUtils+ func loadLocalAsrModels(from repoDirectory: URL) async throws -> AsrModels+ {+ let config = AsrModels.defaultConfiguration()++ let melUrl = repoDirectory.appendingPathComponent("Melspectogram.mlmodelc")+ let encUrl = repoDirectory.appendingPathComponent("ParakeetEncoder_v2.mlmodelc")+ let decUrl = repoDirectory.appendingPathComponent("ParakeetDecoder.mlmodelc")+ let jointUrl = repoDirectory.appendingPathComponent("RNNTJoint.mlmodelc")+ let tokenUrl = repoDirectory.appendingPathComponent("TokenDurationPrediction.mlmodelc")++ let mel = try MLModel(contentsOf: melUrl, configuration: config)+ let enc = try MLModel(contentsOf: encUrl, configuration: config)+ let dec = try MLModel(contentsOf: decUrl, configuration: config)+ let joint = try MLModel(contentsOf: jointUrl, configuration: config)+ let token = try MLModel(contentsOf: tokenUrl, configuration: config)++ return AsrModels(+ melspectrogram: mel,+ encoder: enc,+ decoder: dec,+ joint: joint,+ tokenDuration: token,+ configuration: config+ )+ }+}++diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swiftnew file mode 100644index 00000000..b0c2a5a4--- /dev/null+++ b/Sources/Fluid/Persistence/SettingsStore.swift@@ -0,0 +1,256 @@+import Foundation+import ServiceManagement+import ApplicationServices+import AppKit++final class SettingsStore+{+ static let shared = SettingsStore()+ private let defaults = UserDefaults.standard++ private init() {}++ // Keys+ private enum Keys+ {+ static let enableAIProcessing = "EnableAIProcessing"+ static let enableDebugLogs = "EnableDebugLogs"+ static let availableAIModels = "AvailableAIModels"+ static let availableModelsByProvider = "AvailableModelsByProvider"+ static let selectedAIModel = "SelectedAIModel"+ static let selectedModelByProvider = "SelectedModelByProvider"+ static let providerAPIKeys = "ProviderAPIKeys"+ static let savedProviders = "SavedProviders"+ static let hotkeyShortcutKey = "HotkeyShortcutKey"+ static let preferredInputDeviceUID = "PreferredInputDeviceUID"+ static let preferredOutputDeviceUID = "PreferredOutputDeviceUID"+ static let visualizerNoiseThreshold = "VisualizerNoiseThreshold"+ static let launchAtStartup = "LaunchAtStartup"+ static let showInDock = "ShowInDock"+ }++ 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] = [])+ {+ self.id = id+ self.name = name+ self.baseURL = baseURL+ self.apiKey = apiKey+ self.models = models+ }+ }++ var enableAIProcessing: Bool+ {+ get { defaults.bool(forKey: Keys.enableAIProcessing) }+ set { defaults.set(newValue, forKey: Keys.enableAIProcessing) }+ }++ var availableModels: [String]+ {+ get { (defaults.array(forKey: Keys.availableAIModels) as? [String]) ?? [] }+ set { defaults.set(newValue, forKey: Keys.availableAIModels) }+ }++ var availableModelsByProvider: [String: [String]]+ {+ get { (defaults.dictionary(forKey: Keys.availableModelsByProvider) as? [String: [String]]) ?? [:] }+ set { defaults.set(newValue, forKey: Keys.availableModelsByProvider) }+ }++ var enableDebugLogs: Bool+ {+ get { defaults.bool(forKey: Keys.enableDebugLogs) }+ set { defaults.set(newValue, forKey: Keys.enableDebugLogs) }+ }++ var selectedModel: String?+ {+ get { defaults.string(forKey: Keys.selectedAIModel) }+ set { defaults.set(newValue, forKey: Keys.selectedAIModel) }+ }++ var selectedModelByProvider: [String: String]+ {+ get { (defaults.dictionary(forKey: Keys.selectedModelByProvider) as? [String: String]) ?? [:] }+ set { defaults.set(newValue, forKey: Keys.selectedModelByProvider) }+ }++ var providerAPIKeys: [String: String]+ {+ get { (defaults.dictionary(forKey: Keys.providerAPIKeys) as? [String: String]) ?? [:] }+ set { defaults.set(newValue, forKey: Keys.providerAPIKeys) }+ }++ var savedProviders: [SavedProvider]+ {+ get+ {+ guard let data = defaults.data(forKey: Keys.savedProviders),+ let decoded = try? JSONDecoder().decode([SavedProvider].self, from: data) else { return [] }+ return decoded+ }+ set+ {+ if let encoded = try? JSONEncoder().encode(newValue)+ {+ defaults.set(encoded, forKey: Keys.savedProviders)+ }+ }+ }++ var hotkeyShortcut: HotkeyShortcut+ {+ get+ {+ if let data = defaults.data(forKey: Keys.hotkeyShortcutKey),+ let shortcut = try? JSONDecoder().decode(HotkeyShortcut.self, from: data)+ {+ return shortcut+ }+ return HotkeyShortcut(keyCode: 61, modifierFlags: [])+ }+ set+ {+ if let data = try? JSONEncoder().encode(newValue)+ {+ defaults.set(data, forKey: Keys.hotkeyShortcutKey)+ }+ }+ }++ 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+ }+ set { defaults.set(newValue, forKey: Keys.visualizerNoiseThreshold) }+ }++ // MARK: - Preferences Settings++ var launchAtStartup: Bool+ {+ get { defaults.bool(forKey: Keys.launchAtStartup) }+ set {+ defaults.set(newValue, forKey: Keys.launchAtStartup)+ // Update launch agent registration+ updateLaunchAtStartup(newValue)+ }+ }++ // MARK: - Initialization Methods++ func initializeAppSettings() {+ #if os(macOS)+ // Apply dock visibility setting on app launch+ let dockVisible = showInDock+ DebugLogger.shared.info("Initializing app with dock visibility: \(dockVisible)", source: "SettingsStore")++ // Set activation policy based on saved preference+ DispatchQueue.main.async {+ NSApp.setActivationPolicy(dockVisible ? .regular : .accessory)+ }+ #endif+ }++ var showInDock: Bool+ {+ get {+ let value = defaults.object(forKey: Keys.showInDock)+ return value as? Bool ?? true // Default to true if not set+ }+ set {+ defaults.set(newValue, forKey: Keys.showInDock)+ // Update dock visibility+ updateDockVisibility(newValue)+ }+ }++++ // MARK: - Private Methods++ private func updateLaunchAtStartup(_ enabled: Bool) {+ #if os(macOS)+ // Note: SMAppService.mainApp requires the app to be signed with Developer ID+ // and have proper entitlements. This may not work in development builds.+ let service = SMAppService.mainApp++ do {+ if enabled {+ try service.register()+ DebugLogger.shared.info("Successfully registered for launch at startup", source: "SettingsStore")+ } else {+ try service.unregister()+ DebugLogger.shared.info("Successfully unregistered from launch at startup", source: "SettingsStore")+ }+ } catch {+ DebugLogger.shared.error("Failed to update launch at startup: \(error)", source: "SettingsStore")+ // In development, this is expected to fail without proper signing/entitlements+ // The setting is still saved and will work when the app is properly signed+ }+ #endif+ }++ private func updateDockVisibility(_ visible: Bool) {+ #if os(macOS)+ // IMPORTANT: This is a simplified implementation for development+ // In production, consider these approaches:+ // 1. Use LSUIElement in Info.plist to control default dock visibility+ // 2. Implement a proper helper app or service for dock management+ // 3. Use NSApplication.shared.setActivationPolicy() for better control++ // For now, we'll try multiple approaches with fallbacks++ 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)++ var psn = ProcessSerialNumber(highLongOfPSN: 0, lowLongOfPSN: UInt32(kCurrentProcess))+ let result = TransformProcessType(&psn, transformState)++ 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")+ }++ // 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")+ }++ // Store the intended state for reference+ UserDefaults.standard.set(visible, forKey: "IntendedDockVisibility")+ DebugLogger.shared.info("✓ Dock visibility preference saved: \(visible)", source: "SettingsStore")+ #endif+ }+}++diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swiftnew file mode 100644index 00000000..fd5fb0e1--- /dev/null+++ b/Sources/Fluid/Services/ASRService.swift@@ -0,0 +1,552 @@+import Foundation+import AVFoundation+import Combine+import Accelerate+import FluidAudio+import CoreAudio+import AppKit++/// A comprehensive speech recognition service that handles real-time audio transcription.+///+/// This service manages the entire ASR (Automatic Speech Recognition) pipeline including:+/// - Audio capture and processing+/// - Model downloading and management+/// - Real-time transcription+/// - Audio level visualization+/// - Text-to-speech integration+///+/// The service is designed to work seamlessly with macOS system APIs and provides+/// robust error handling and performance optimization.+///+/// ## Usage+/// ```swift+/// let asrService = ASRService()+/// asrService.start() // Begin recording+/// // ... speak ...+/// let transcribedText = await asrService.stop() // Stop and get transcription+/// ```+///+/// ## Thread Safety+/// All public methods are marked with @MainActor to ensure thread safety.+/// Audio processing happens on background threads for optimal performance.+///+/// ## Model Management+/// The service automatically downloads and manages ASR models from Hugging Face.+/// Models are cached locally to avoid repeated downloads.+@MainActor+final class ASRService: ObservableObject+{+ @Published var isRunning: Bool = false+ @Published var finalText: String = ""+ @Published var micStatus: AVAuthorizationStatus = .notDetermined+ @Published var isAsrReady: Bool = false+ @Published var isDownloadingModel: Bool = false+ @Published var modelDownloadProgress: Double = 0.0+ @Published var selectedModel: ModelOption = .parakeetTdt06bV2++ enum ModelOption: String, CaseIterable, Identifiable, Hashable+ {+ case parakeetTdt06bV2 = "Parakeet TDT-0.6b v2"+ var id: String { rawValue }+ var displayName: String { rawValue }+ }++ private let engine = AVAudioEngine()+ private var inputFormat: AVAudioFormat?+ private var micPermissionGranted = false++ private var asrManager: AsrManager?++ private var isRecordingWholeSession: Bool = false+ private var recordedPCM: [Float] = []++ 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()+ {+ self.micStatus = AVCaptureDevice.authorizationStatus(for: .audio)+ self.micPermissionGranted = (self.micStatus == .authorized)+ registerDefaultDeviceChangeListener()+ }++ func requestMicAccess()+ {+ AVCaptureDevice.requestAccess(for: .audio)+ { [weak self] granted in+ guard let self = self else { return }+ Task { @MainActor in+ self.micPermissionGranted = granted+ self.micStatus = granted ? .authorized : .denied+ }+ }+ }++ func openSystemSettingsForMic()+ {+ if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone")+ {+ NSWorkspace.shared.open(url)+ }+ }++ /// Starts the speech recognition session.+ ///+ /// This method initiates audio capture and real-time processing. The service will:+ /// - Begin capturing audio from the default input device+ /// - Process audio in real-time for transcription+ /// - Provide audio level feedback for visualization+ ///+ /// ## Requirements+ /// - Microphone permission must be granted+ /// - ASR models must be available (will download if needed)+ /// - No existing recording session should be active+ ///+ /// ## Postconditions+ /// - `isRunning` will be `true`+ /// - Audio processing will begin immediately+ /// - Audio level updates will be published via `audioLevelPublisher`+ ///+ /// ## Errors+ /// If audio session configuration fails, the method will silently fail+ /// and `isRunning` will remain `false`. Check the debug logs for details.+ func start()+ {+ guard micStatus == .authorized else { return }+ guard isRunning == false else { return }++ finalText.removeAll()+ recordedPCM.removeAll()+ isRecordingWholeSession = true++ do+ {+ try configureSession()+ try startEngine()+ setupEngineTap()+ isRunning = true+ }+ 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")+ }+ }++ /// Stops the recording session and returns the transcribed text.+ ///+ /// This method performs the complete transcription process:+ /// 1. Stops audio capture and processing+ /// 2. Ensures ASR models are ready+ /// 3. Transcribes all recorded audio+ /// 4. Returns the final transcribed text+ ///+ /// ## Process+ /// - Stops the audio engine and removes processing tap+ /// - Validates that ASR models are available and ready+ /// - Processes all recorded audio through the ASR pipeline+ /// - Returns the transcribed text for use by the caller+ ///+ /// ## Returns+ /// The transcribed text from the entire recording session, or an empty string if transcription fails.+ ///+ /// ## Note+ /// This method does not update `finalText` property to avoid UI conflicts.+ /// Callers should handle the returned text as needed.+ ///+ /// ## Errors+ /// Returns empty string if:+ /// - No recording was in progress+ /// - ASR models are not available+ /// - Transcription process fails+ /// Check debug logs for detailed error information.+ func stop() async -> String+ {+ guard isRunning else { return "" }+ removeEngineTap()+ engine.stop()+ isRunning = false++ let pcm = recordedPCM+ recordedPCM.removeAll()+ isRecordingWholeSession = false++ do+ {+ try await self.ensureAsrReady()+ guard let manager = self.asrManager else { return "" }+ let result = try await manager.transcribe(pcm, source: AudioSource.microphone)+ // Do not update self.finalText here to avoid instant binding insert in playground+ return result.text+ }+ catch+ {+ DebugLogger.shared.error("ASR transcription failed: \(error)", source: "ASRService")+ return ""+ }+ }++ func stopWithoutTranscription()+ {+ guard isRunning else { return }+ removeEngineTap()+ engine.stop()+ isRunning = false+ recordedPCM.removeAll()+ isRecordingWholeSession = false+ }++ private func configureSession() throws+ {+ if engine.isRunning+ {+ engine.stop()+ }+ engine.reset()+ _ = engine.inputNode+ }++ private func startEngine() throws+ {+ engine.reset()+ var attempts = 0+ while attempts < 3+ {+ do+ {+ try engine.start()+ return+ }+ catch+ {+ attempts += 1+ Thread.sleep(forTimeInterval: 0.1)+ engine.reset()+ }+ }+ throw NSError(domain: "ASRService", code: -1)+ }++ private func removeEngineTap()+ {+ engine.inputNode.removeTap(onBus: 0)+ }++ 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+ self?.processInputBuffer(buffer: buffer)+ }+ }++ private func handleDefaultInputChanged()+ {+ // Restart engine to bind to the new default input and resume level publishing+ if isRunning+ {+ removeEngineTap()+ engine.stop()+ do+ {+ try configureSession()+ try startEngine()+ setupEngineTap()+ }+ catch+ {+ }+ }+ // Nudge visualizer+ DispatchQueue.main.async { self.audioLevelSubject.send(0.0) }+ }++ private var defaultInputListenerInstalled = false+ 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+ self?.handleDefaultInputChanged()+ }+ if status == noErr { defaultInputListenerInstalled = true }+ }++ 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+ {+ recordedPCM.append(contentsOf: mono16k)++ // Publish audio level for visualization+ let audioLevel = self.calculateAudioLevel(mono16k)+ DispatchQueue.main.async { self.audioLevelSubject.send(audioLevel) }+ }+ }++ 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]+ {+ if let format = floatBuffer.format as AVAudioFormat?,+ format.sampleRate == 16000.0,+ format.commonFormat == .pcmFormatFloat32,+ format.channelCount == 1,+ let channelData = floatBuffer.floatChannelData+ {+ let frameCount = Int(floatBuffer.frameLength)+ let ptr = channelData[0]+ return Array(UnsafeBufferPointer(start: ptr, count: frameCount))+ }+ let mono = self.downmixToMono(floatBuffer)+ return self.resampleTo16k(mono, sourceSampleRate: floatBuffer.format.sampleRate)+ }++ 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+ {+ return Array(UnsafeBufferPointer(start: channelData[0], count: frameCount))+ }+ var mono = [Float](repeating: 0, count: frameCount)+ for c in 0..<channels+ {+ let src = channelData[c]+ vDSP_vadd(src, 1, mono, 1, &mono, 1, vDSP_Length(frameCount))+ }+ var div = Float(channels)+ vDSP_vsdiv(mono, 1, &div, &mono, 1, vDSP_Length(frameCount))+ return mono+ }++ 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+ 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+ {+ let srcPos = Double(i) / ratio+ let idx = Int(srcPos)+ let frac = Float(srcPos - Double(idx))+ 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+ {+ output[i] = samples[idx]+ }+ }+ return output+ }++ /// Ensures that ASR models are downloaded and ready for transcription.+ ///+ /// This method handles the complete model lifecycle:+ /// 1. Checks if models are already available and loaded+ /// 2. Downloads models from Hugging Face if needed+ /// 3. Loads models into memory for inference+ /// 4. Initializes the ASR manager with loaded models+ ///+ /// ## Model Management+ /// - Models are downloaded from the configured Hugging Face repository+ /// - Downloads are cached to avoid repeated network requests+ /// - Progress is reported via `isDownloadingModel` and `modelDownloadProgress`+ /// - Models include: melspectrogram, encoder, decoder, joint, and token prediction+ ///+ /// ## Performance+ /// - First run will download ~100-500MB of models+ /// - Subsequent runs use cached models (much faster)+ /// - Model loading happens asynchronously to avoid blocking UI+ ///+ /// ## Errors+ /// Throws if model download or loading fails. Common causes:+ /// - Network connectivity issues+ /// - Insufficient disk space+ /// - Invalid model repository configuration+ ///+ /// ## Note+ /// This method is called automatically when starting transcription.+ /// Manual calls are typically not needed unless you want to preload models.+ func ensureAsrReady() async throws+ {+ if isAsrReady == false+ {+ do+ {+ DebugLogger.shared.debug("Starting ASR initialization...", source: "ASRService")++ // Check model cache directory+ let cacheDir = AsrModels.defaultCacheDirectory()+ DebugLogger.shared.debug("Model cache directory: \(cacheDir.path)", source: "ASRService")+ DebugLogger.shared.debug("Cache directory exists: \(FileManager.default.fileExists(atPath: cacheDir.path))", source: "ASRService")++ let originalStderr = dup(STDERR_FILENO)+ let devNull = open("/dev/null", O_WRONLY)+ dup2(devNull, STDERR_FILENO)+ close(devNull)++ DebugLogger.shared.debug("Ensuring models exist via in-app downloader...", source: "ASRService")+ let downloader = HuggingFaceModelDownloader()+ try await downloader.ensureModelsPresent(at: cacheDir) { progress, item in+ DispatchQueue.main.async {+ self.isDownloadingModel = progress < 1.0+ self.modelDownloadProgress = max(0.0, min(1.0, progress))+ }+ DebugLogger.shared.debug(String(format: "Download progress: %.0f%% (%@)", progress * 100.0, item), source: "ASRService")+ }+ DebugLogger.shared.debug("Models ensured in cache. Now loading from disk (local loader, no network)...", source: "ASRService")+ let models = try await downloader.loadLocalAsrModels(from: cacheDir)+ DebugLogger.shared.debug("Models loaded successfully from cache directory (local)", source: "ASRService")++ if self.asrManager == nil+ {+ DebugLogger.shared.debug("Creating new AsrManager...", source: "ASRService")+ self.asrManager = AsrManager(config: ASRConfig(realtimeMode: false))+ }+ if let manager = self.asrManager+ {+ DebugLogger.shared.debug("Initializing AsrManager with models...", source: "ASRService")+ try await manager.initialize(models: models)+ DebugLogger.shared.debug("AsrManager initialized successfully", source: "ASRService")+ }++ dup2(originalStderr, STDERR_FILENO)+ close(originalStderr)++ DebugLogger.shared.info("ASR initialization completed successfully", source: "ASRService")+ }+ catch+ {+ DebugLogger.shared.error("ASR initialization failed with error: \(error)", source: "ASRService")+ DebugLogger.shared.error("Error details: \(error.localizedDescription)", source: "ASRService")+ throw error+ }+ isAsrReady = true+ }+ else+ {+ DebugLogger.shared.debug("ASR already ready, skipping initialization", source: "ASRService")+ }+ }++ // MARK: - Model lifecycle helpers (parity with original API)+ func predownloadSelectedModel()+ {+ Task+ { [weak self] in+ guard let self = self else { return }+ DebugLogger.shared.debug("Starting model predownload...", source: "ASRService")+ await MainActor.run { self.isDownloadingModel = true }+ do+ {+ try await self.ensureAsrReady()+ DebugLogger.shared.info("Model predownload completed successfully", source: "ASRService")+ }+ catch+ {+ DebugLogger.shared.error("Model predownload failed: \(error)", source: "ASRService")+ DebugLogger.shared.error("Error details: \(error.localizedDescription)", source: "ASRService")+ }+ await MainActor.run { self.isDownloadingModel = false }+ }+ }++ func preloadModelAfterSelection() async+ {+ await MainActor.run { self.isDownloadingModel = true }+ do+ {+ try await self.ensureAsrReady()+ }+ catch+ {+ }+ await MainActor.run { self.isDownloadingModel = false }+ }++ // MARK: - Typing convenience for compatibility+ private let typingService = TypingService() // Reuse instance to avoid conflicts++ func typeTextToActiveField(_ text: String)+ {+ DebugLogger.shared.debug("typeTextToActiveField called with: \"\(text.prefix(50))\(text.count > 50 ? "..." : "")\"", source: "ASRService")+ DebugLogger.shared.debug("About to call typingService.typeTextInstantly", source: "ASRService")+ typingService.typeTextInstantly(text)+ DebugLogger.shared.debug("typingService.typeTextInstantly call completed", source: "ASRService")+ }+}++diff --git a/Sources/Fluid/Services/DebugLogger.swift b/Sources/Fluid/Services/DebugLogger.swiftnew file mode 100644index 00000000..e63f4c37--- /dev/null+++ b/Sources/Fluid/Services/DebugLogger.swift@@ -0,0 +1,97 @@+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)++ struct LogEntry: Identifiable, Equatable {+ let id = UUID()+ let timestamp: Date+ let level: LogLevel+ let message: String+ let source: String++ var formattedTimestamp: String {+ let formatter = DateFormatter()+ formatter.dateFormat = "HH:mm:ss.SSS"+ return formatter.string(from: timestamp)+ }+ }++ 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+ case .warning: return .orange+ case .error: return .red+ case .debug: return .gray+ }+ }+ }++ private init() {}++ func log(_ message: String, level: LogLevel = .info, source: String = "App") {+ queue.async {+ let entry = LogEntry(timestamp: Date(), level: level, message: message, source: source)++ // Check if debug logging is enabled for debug level, but always show errors and warnings+ let shouldLogToConsole = level == .error || level == .warning || SettingsStore.shared.enableDebugLogs++ if shouldLogToConsole {+ // Also print to console for Xcode debugging+ print("[\(entry.formattedTimestamp)] [\(level.rawValue)] [\(source)] \(message)")+ }++ DispatchQueue.main.async {+ self.logs.append(entry)++ // Keep only the last maxLogs entries+ if self.logs.count > self.maxLogs {+ self.logs.removeFirst(self.logs.count - self.maxLogs)+ }+ }+ }+ }++ func clear() {+ DispatchQueue.main.async {+ self.logs.removeAll()+ }+ }++ func exportLogs() -> String {+ return logs.map { entry in+ "[\(entry.formattedTimestamp)] [\(entry.level.rawValue)] [\(entry.source)] \(entry.message)"+ }.joined(separator: "\n")+ }+}++// Convenience functions for easier logging+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 filediff --git a/Sources/Fluid/Services/GlobalHotkeyManager.swift b/Sources/Fluid/Services/GlobalHotkeyManager.swiftnew file mode 100644index 00000000..eb326fa2--- /dev/null+++ b/Sources/Fluid/Services/GlobalHotkeyManager.swift@@ -0,0 +1,294 @@+import Foundation+import AppKit++final class GlobalHotkeyManager: NSObject+{+ private var eventTap: CFMachPort?+ private var runLoopSource: CFRunLoopSource?+ private let asrService: ASRService+ private var shortcut: HotkeyShortcut+ private var stopAndProcessCallback: (() async -> Void)?++ private var isInitialized = false+ private var initializationTask: Task<Void, Never>?+ private var healthCheckTask: Task<Void, Never>?+ private let maxRetryAttempts = 5+ private let retryDelay: TimeInterval = 0.5+ private let healthCheckInterval: TimeInterval = 30.0++ init(asrService: ASRService, shortcut: HotkeyShortcut, stopAndProcessCallback: (() async -> Void)? = nil)+ {+ self.asrService = asrService+ self.shortcut = shortcut+ self.stopAndProcessCallback = stopAndProcessCallback+ 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+ }++ 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 \(retryDelay) seconds...", source: "GlobalHotkeyManager")+ Task {+ try? await Task.sleep(nanoseconds: UInt64(retryDelay * 1_000_000_000))+ await MainActor.run {+ self.setupGlobalHotkeyWithRetry()+ }+ }+ return+ }+ }++ DebugLogger.shared.error("Failed to initialize after \(maxRetryAttempts) attempts", source: "GlobalHotkeyManager")+ }++ @discardableResult+ private func setupGlobalHotkey() -> Bool+ {+ cleanupEventTap()++ if !AXIsProcessTrusted() {+ if UserDefaults.standard.bool(forKey: "enableDebugLogs") {+ print("[GlobalHotkeyManager] Accessibility permissions not granted")+ }+ return false+ }++ let eventMask = (1 << CGEventType.keyDown.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+ guard let refcon = refcon else { return Unmanaged.passUnretained(event) }+ 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")+ }+ return false+ }++ runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0)+ guard let source = runLoopSource else {+ if UserDefaults.standard.bool(forKey: "enableDebugLogs") {+ print("[GlobalHotkeyManager] Failed to create CFRunLoopSource")+ }+ 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")+ }+ cleanupEventTap()+ return false+ }++ if UserDefaults.standard.bool(forKey: "enableDebugLogs") {+ print("[GlobalHotkeyManager] Event tap successfully created and enabled")+ }+ return true+ }++ private 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>?+ {+ let keyCode = UInt16(event.getIntegerValueField(.keyboardEventKeycode))+ let flags = event.flags++ var eventModifiers: NSEvent.ModifierFlags = []+ if flags.contains(.maskCommand) { eventModifiers.insert(.command) }+ if flags.contains(.maskAlternate) { eventModifiers.insert(.option) }+ if flags.contains(.maskControl) { eventModifiers.insert(.control) }+ if flags.contains(.maskShift) { eventModifiers.insert(.shift) }++ if type == .keyDown+ {+ let shortcutModifiers = shortcut.modifierFlags.intersection([.command, .option, .control, .shift])+ if keyCode == shortcut.keyCode && eventModifiers == shortcutModifiers+ {+ DispatchQueue.main.async { [weak self] in+ guard let self = self else { return }+ if self.asrService.isRunning+ {+ if let callback = self.stopAndProcessCallback+ {+ Task { await callback() }+ }+ else+ {+ self.asrService.stopWithoutTranscription()+ }+ }+ else+ {+ self.asrService.start()+ }+ }+ return nil+ }+ }+ else if type == .flagsChanged+ {+ if shortcut.modifierFlags.isEmpty+ {+ let isModifierKeyPressed = flags.contains(.maskCommand) || flags.contains(.maskAlternate) || flags.contains(.maskControl) || flags.contains(.maskShift)+ if keyCode == shortcut.keyCode && isModifierKeyPressed+ {+ DispatchQueue.main.async { [weak self] in+ guard let self = self else { return }+ if self.asrService.isRunning+ {+ if let callback = self.stopAndProcessCallback+ {+ Task { await callback() }+ }+ else+ {+ self.asrService.stopWithoutTranscription()+ }+ }+ else+ {+ self.asrService.start()+ }+ }+ return nil+ }+ }+ }++ return Unmanaged.passUnretained(event)+ }++ func updateShortcut(_ newShortcut: HotkeyShortcut)+ {+ shortcut = newShortcut++ if UserDefaults.standard.bool(forKey: "enableDebugLogs") {+ print("[GlobalHotkeyManager] Updating shortcut to: \(newShortcut.displayString)")+ }++ if setupGlobalHotkey() {+ isInitialized = true+ if UserDefaults.standard.bool(forKey: "enableDebugLogs") {+ print("[GlobalHotkeyManager] Shortcut update successful")+ }+ startHealthCheckTimer()+ } else {+ print("[GlobalHotkeyManager] ERROR: Failed to update shortcut")+ }+ }++ func isEventTapEnabled() -> Bool {+ guard let tap = eventTap else { return false }+ return CGEvent.tapIsEnabled(tap: tap)+ }++ func validateEventTapHealth() -> Bool {+ guard isInitialized else { return false }+ return isEventTapEnabled()+ }++ func reinitialize() {+ if UserDefaults.standard.bool(forKey: "enableDebugLogs") {+ print("[GlobalHotkeyManager] Manual reinitialization requested")+ }++ initializationTask?.cancel()+ healthCheckTask?.cancel()+ isInitialized = false+ initializeWithDelay()+ }++ private func startHealthCheckTimer() {+ healthCheckTask?.cancel()+ healthCheckTask = Task {+ while !Task.isCancelled {+ try? await Task.sleep(nanoseconds: UInt64(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() {+ if UserDefaults.standard.bool(forKey: "enableDebugLogs") {+ print("[GlobalHotkeyManager] Health check recovery successful")+ }+ } else {+ print("[GlobalHotkeyManager] Health check recovery failed")+ self.isInitialized = false+ }+ }+ }+ }+ }+ }++ deinit+ {+ initializationTask?.cancel()+ healthCheckTask?.cancel()+ cleanupEventTap()++ if UserDefaults.standard.bool(forKey: "enableDebugLogs") {+ print("[GlobalHotkeyManager] Deinitialized and cleaned up")+ }+ }+}++diff --git a/Sources/Fluid/Services/ListeningOverlayController.swift b/Sources/Fluid/Services/ListeningOverlayController.swiftnew file mode 100644index 00000000..57844bbf--- /dev/null+++ b/Sources/Fluid/Services/ListeningOverlayController.swift@@ -0,0 +1,63 @@+import AppKit++final class ListeningOverlayController+{+ private var panel: NSPanel?+ private var asrService: ASRService++ init(asrService: ASRService)+ {+ self.asrService = asrService+ }++ func show(with view: NSView)+ {+ if panel == nil+ {+ let style: NSWindow.StyleMask = [.borderless, .nonactivatingPanel]+ let p = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 280, height: 80),+ styleMask: style,+ backing: .buffered,+ defer: false)+ p.level = .statusBar+ p.isOpaque = false+ p.hasShadow = true+ p.hidesOnDeactivate = false+ p.ignoresMouseEvents = true+ p.collectionBehavior = [.canJoinAllSpaces, .transient, .fullScreenAuxiliary]+ p.backgroundColor = .clear+ p.titleVisibility = .hidden+ p.titlebarAppearsTransparent = true+ panel = p+ }+ panel?.contentView = view+ positionCenteredLower()+ panel?.orderFrontRegardless()+ }++ func hide()+ {+ panel?.orderOut(nil)+ }++ private func activeScreen() -> NSScreen?+ {+ if let key = NSApp.keyWindow?.screen { return key }+ if let mouse = NSScreen.screens.first(where: { NSMouseInRect(NSEvent.mouseLocation, $0.frame, false) }) { return mouse }+ return NSScreen.main+ }++ private func positionCenteredLower()+ {+ guard let screen = activeScreen(), let panel else { return }+ let visible = screen.visibleFrame+ panel.layoutIfNeeded()+ let size = panel.frame.size+ let centerX = visible.midX - size.width / 2+ let bottomPadding: CGFloat = 140+ let yPosition = visible.minY + bottomPadding+ panel.setFrameOrigin(NSPoint(x: centerX.rounded(), y: yPosition.rounded()))+ }+}++diff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swiftnew file mode 100644index 00000000..2f764824--- /dev/null+++ b/Sources/Fluid/Services/MenuBarManager.swift@@ -0,0 +1,230 @@+import AppKit+import Combine++@MainActor+final class MenuBarManager: ObservableObject {+ private var statusItem: NSStatusItem?+ private var menu: NSMenu?++ // References to app state+ private weak var asrService: ASRService?+ private var cancellables = Set<AnyCancellable>()++ @Published var isRecording: Bool = false+ @Published var aiProcessingEnabled: Bool = false++ init() {+ setupMenuBar()+ // Initialize from persisted setting+ aiProcessingEnabled = SettingsStore.shared.enableAIProcessing+ // Reflect changes to menu when toggled from elsewhere (e.g., General tab)+ $aiProcessingEnabled+ .receive(on: DispatchQueue.main)+ .sink { [weak self] _ in+ self?.updateMenu()+ }+ .store(in: &cancellables)+ }++ deinit {+ statusItem = nil+ }++ func configure(asrService: ASRService) {+ self.asrService = asrService++ // Subscribe to recording state changes+ asrService.$isRunning+ .receive(on: DispatchQueue.main)+ .sink { [weak self] isRunning in+ self?.isRecording = isRunning+ self?.updateMenuBarIcon()+ self?.updateMenu()+ }+ .store(in: &cancellables)++ // Subscribe to AI processing state+ aiProcessingEnabled = SettingsStore.shared.enableAIProcessing+ }++ private func setupMenuBar() {+ // Create status item+ statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)++ guard let statusItem = statusItem else { return }++ // 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 updateMenu() {+ guard let menu = menu else { return }++ menu.removeAllItems()++ // Status indicator+ let statusTitle = isRecording ? "Recording..." : "Ready to Record"+ let statusItem = NSMenuItem(title: statusTitle, action: nil, keyEquivalent: "")+ statusItem.isEnabled = false+ menu.addItem(statusItem)++ menu.addItem(.separator())++ // Start/Stop Recording+ let recordingAction = isRecording ? "Stop Recording" : "Start Recording"+ let recordingItem = NSMenuItem(title: recordingAction, action: #selector(toggleRecording), keyEquivalent: "")+ recordingItem.target = self++ // Show hotkey if available+ let hotkeyShortcut = SettingsStore.shared.hotkeyShortcut+ recordingItem.keyEquivalent = "" // We'll show it in the title instead+ if !hotkeyShortcut.displayString.isEmpty {+ recordingItem.title = "\(recordingAction) (\(hotkeyShortcut.displayString))"+ }++ menu.addItem(recordingItem)++ // AI Processing Toggle+ let aiTitle = aiProcessingEnabled ? "Disable AI Processing" : "Enable AI Processing"+ let aiItem = NSMenuItem(title: aiTitle, action: #selector(toggleAIProcessing), keyEquivalent: "")+ aiItem.target = self+ menu.addItem(aiItem)++ menu.addItem(.separator())++ // Open Main Window+ let openItem = NSMenuItem(title: "Open Fluid", action: #selector(openMainWindow), keyEquivalent: "")+ openItem.target = self+ menu.addItem(openItem)++ menu.addItem(.separator())++ // Quit+ let quitItem = NSMenuItem(title: "Quit Fluid", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")+ quitItem.target = NSApp+ menu.addItem(quitItem)+ }++ @objc private func toggleRecording() {+ guard let asrService = asrService else { return }++ if isRecording {+ Task {+ _ = await asrService.stop()+ }+ } else {+ asrService.start()+ }+ }++ @objc private func toggleAIProcessing() {+ aiProcessingEnabled.toggle()+ // Persist and broadcast change+ SettingsStore.shared.enableAIProcessing = aiProcessingEnabled+ // If a ContentView has bound to MenuBarManager, its onChange sync will mirror this+ updateMenu()+ }++ @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 and restore the main window+ var foundWindow = false+ for window in NSApp.windows {+ if window.title.contains("Fluid") || window.isMainWindow || window.contentView != nil {+ // Handle minimized windows+ if window.isMiniaturized {+ window.deminiaturize(nil)+ }++ // Bring to current space and make key+ window.makeKeyAndOrderFront(nil)+ window.orderFrontRegardless()+ foundWindow = true+ break+ }+ }++ // If no window found, try to activate any available window+ if !foundWindow && !NSApp.windows.isEmpty {+ if let firstWindow = NSApp.windows.first {+ if firstWindow.isMiniaturized {+ firstWindow.deminiaturize(nil)+ }+ firstWindow.makeKeyAndOrderFront(nil)+ firstWindow.orderFrontRegardless()+ foundWindow = true+ }+ }++ // Final attempt: ensure app is active and visible+ if foundWindow {+ NSApp.activate(ignoringOtherApps: true)+ }+ }+}diff --git a/Sources/Fluid/Services/TypingService.swift b/Sources/Fluid/Services/TypingService.swiftnew file mode 100644index 00000000..a67fdd48--- /dev/null+++ b/Sources/Fluid/Services/TypingService.swift@@ -0,0 +1,385 @@+import Foundation+import AppKit++final class TypingService+{+ private var isCurrentlyTyping = false++ func typeTextInstantly(_ text: String)+ {+ print("[TypingService] ENTRY: typeTextInstantly called with text length: \(text.count)")+ print("[TypingService] Text preview: \"\(String(text.prefix(100)))\"")++ guard text.isEmpty == false else {+ print("[TypingService] ERROR: Empty text provided, aborting")+ return+ }++ // Prevent concurrent typing operations+ guard !isCurrentlyTyping else {+ print("[TypingService] WARNING: Skipping text injection - already in progress")+ return+ }++ // Check accessibility permissions first+ guard AXIsProcessTrusted() else {+ print("[TypingService] ERROR: Accessibility permissions required for text injection")+ print("[TypingService] Current accessibility status: \(AXIsProcessTrusted())")+ return+ }++ print("[TypingService] Accessibility check passed, proceeding with text injection")+ isCurrentlyTyping = true++ DispatchQueue.global(qos: .userInitiated).async+ {+ defer {+ self.isCurrentlyTyping = false+ print("[TypingService] Typing operation completed, isCurrentlyTyping set to false")+ }++ print("[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+ print("[TypingService] Delay completed, calling insertTextInstantly")+ self.insertTextInstantly(text)+ }+ }++ private func insertTextInstantly(_ text: String)+ {+ print("[TypingService] insertTextInstantly called with \(text.count) characters")+ print("[TypingService] Attempting to type text: \"\(text.prefix(50))\(text.count > 50 ? "..." : "")\"")++ // Get frontmost app info+ if let frontApp = NSWorkspace.shared.frontmostApplication {+ print("[TypingService] Target app: \(frontApp.localizedName ?? "Unknown") (\(frontApp.bundleIdentifier ?? "Unknown"))")+ } else {+ print("[TypingService] WARNING: Could not get frontmost application")+ }++ // Check if we have permission to create events+ print("[TypingService] Accessibility trusted: \(AXIsProcessTrusted())")++ // Try direct bulk CGEvent insertion (NO CLIPBOARD)+ print("[TypingService] Trying INSTANT bulk CGEvent insertion (no clipboard)")+ if insertTextBulkInstant(text) {+ print("[TypingService] SUCCESS: Instant bulk CGEvent completed")+ } else {+ print("[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+ print("[TypingService] Typing character \(index+1)/\(text.count): '\(char)'")+ }+ typeCharacter(char)+ usleep(1000) // Small delay between characters (1ms)+ }++ print("[TypingService] Character-by-character typing completed")+ }+ }++ private func insertTextBulkInstant(_ text: String) -> Bool {+ print("[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 {+ print("[TypingService] ERROR: Failed to create bulk CGEvent")+ return false+ }++ // Convert entire text to UTF16+ let utf16Array = Array(text.utf16)+ print("[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)+ print("[TypingService] Posted single CGEvent with entire text - INSTANT!")++ return true+ }++ private func insertTextViaAccessibility(_ text: String) -> Bool {+ print("[TypingService] Starting Accessibility API insertion")++ // Try multiple strategies to find text input element++ // Strategy 1: Get focused element directly+ print("[TypingService] Strategy 1: Getting focused UI element...")+ if let textElement = getFocusedTextElement() {+ print("[TypingService] Found focused text element")+ if tryAllTextInsertionMethods(textElement, text) {+ return true+ }+ }++ // Strategy 2: Traverse frontmost app UI hierarchy to find text elements+ print("[TypingService] Strategy 2: Traversing app UI hierarchy...")+ if let textElement = findTextElementInFrontmostApp() {+ print("[TypingService] Found text element in app hierarchy")+ if tryAllTextInsertionMethods(textElement, text) {+ return true+ }+ }++ // Strategy 3: Find element with keyboard focus+ print("[TypingService] Strategy 3: Looking for keyboard focus...")+ if let textElement = findKeyboardFocusedElement() {+ print("[TypingService] Found keyboard focused element")+ if tryAllTextInsertionMethods(textElement, text) {+ return true+ }+ }++ print("[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)++ if result == .success, let element = focusedElement {+ let axElement = element as! AXUIElement+ if let role = getElementAttribute(axElement, kAXRoleAttribute as CFString) {+ print("[TypingService] Found focused element with role: \(role)")+ return axElement+ }+ } else {+ print("[TypingService] Could not get focused UI element - result: \(result.rawValue)")+ }++ return nil+ }++ private func findTextElementInFrontmostApp() -> AXUIElement? {+ guard let frontmostApp = NSWorkspace.shared.frontmostApplication else {+ print("[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"]+ if textRoles.contains(role) {+ print("[TypingService] Found text element at depth \(depth) with role: \(role)")+ 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) {+ return found+ }+ }+ }++ 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)++ if result == .success, let element = focusedElement {+ let axElement = element as! AXUIElement+ if let role = getElementAttribute(axElement, kAXRoleAttribute as CFString) {+ print("[TypingService] Found app-level focused element with role: \(role)")+ 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) {+ print("[TypingService] Trying insertion on element with role: \(role)")++ if let title = getElementAttribute(element, kAXTitleAttribute as CFString) {+ print("[TypingService] Element title: \(title)")+ }+ }++ // Try multiple approaches for text insertion+ print("[TypingService] Trying approach 1: Direct kAXValueAttribute")+ if setTextViaValue(element, text) {+ return true+ }++ print("[TypingService] Trying approach 2: kAXSelectedTextAttribute (replace selection)")+ if setTextViaSelection(element, text) {+ return true+ }++ print("[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)+ if result == .success, let stringValue = value as? String {+ return stringValue+ }+ return nil+ }+ //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 {+ print("[TypingService] SUCCESS: Set text via kAXValueAttribute")+ return true+ } else {+ print("[TypingService] FAILED: kAXValueAttribute - error: \(result.rawValue)")+ return false+ }+ }++ private func setTextViaSelection(_ element: AXUIElement, _ text: String) -> Bool {+ // First, select all existing text+ let selectAllResult = AXUIElementSetAttributeValue(element, kAXSelectedTextAttribute as CFString, "" as CFString)+ print("[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 {+ print("[TypingService] SUCCESS: Set text via kAXSelectedTextAttribute")+ return true+ } else {+ print("[TypingService] FAILED: kAXSelectedTextAttribute - error: \(result.rawValue)")+ 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)+ print("[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 {+ print("[TypingService] SUCCESS: Inserted text at insertion point")+ return true+ } else {+ print("[TypingService] FAILED: Insertion point method - error: \(result.rawValue)")+ return false+ }+ }++ private func insertTextBulk(_ text: String) -> Bool {+ print("[TypingService] Starting bulk CGEvent insertion")++ // Get the frontmost application's PID for targeted event posting+ guard let frontApp = NSWorkspace.shared.frontmostApplication else {+ print("[TypingService] ERROR: Could not get frontmost application for bulk insertion")+ return false+ }++ let targetPID = frontApp.processIdentifier+ print("[TypingService] Targeting PID \(targetPID) for bulk insertion")++ // Try word-by-word insertion instead of entire text at once (faster than char-by-char but more reliable than bulk)+ let words = text.components(separatedBy: " ")+ print("[TypingService] Splitting text into \(words.count) words for bulk insertion")++ for (index, word) in words.enumerated() {+ let wordToType = word + (index < words.count - 1 ? " " : "") // Add space except for last word++ if !insertWordViaCGEvent(wordToType, targetPID: targetPID) {+ print("[TypingService] Failed to insert word \(index + 1): '\(word)', falling back to character method")+ return false+ }++ if index % 5 == 0 && index > 0 {+ print("[TypingService] Bulk insertion progress: \(index + 1)/\(words.count) words")+ }+ }++ print("[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 {+ print("[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 {+ if UserDefaults.standard.bool(forKey: "enableDebugLogs") {+ print("[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)+ keyUpEvent.post(tap: .cghidEventTap)+ }+}++diff --git a/Sources/Fluid/TalkingAnimations.swift b/Sources/Fluid/TalkingAnimations.swiftnew file mode 100644index 00000000..6d379351--- /dev/null+++ b/Sources/Fluid/TalkingAnimations.swift@@ -0,0 +1,681 @@+//+// TalkingAnimations.swift+// fluid+//+// Created by Assistant+//++import SwiftUI+import Combine+import AppKit+import CoreGraphics++// 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 {+ return nil+ }+ for info in windowInfo {+ guard let pid = info[kCGWindowOwnerPID as String] as? pid_t, pid == ownerPid else { continue }+ if let name = info[kCGWindowName as String] as? String, name.isEmpty == false {+ return name+ }+ }+ return nil+ }++ deinit {+ timer?.invalidate()+ }+}++// 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+ let barWidth: CGFloat = 5+ let minBarHeight: CGFloat = 4+ let maxBarHeight: CGFloat = 32+ 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+ let activeFPS: Double = 60.0 // High FPS during active speech+ let idleFPS: Double = 30.0 // Higher idle FPS+ let silenceFPS: Double = 10.0 // Higher silence FPS+}++// MARK: - Spokenly-Style Audio Visualization View+struct TalkingAudioVisualizationView: View {+ @StateObject private var data: AudioVisualizationData+ @State private var dynamicNoiseThreshold: CGFloat = CGFloat(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))+ }++ var body: some View {+ SpokenlyWaveform(+ config: config,+ audioLevel: data.audioLevel,+ isActive: data.audioLevel > config.noiseThreshold+ )+ .onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in+ // Update threshold when UserDefaults changes+ let newThreshold = CGFloat(SettingsStore.shared.visualizerNoiseThreshold)+ if newThreshold != dynamicNoiseThreshold {+ 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.016, on: .main, in: .common).autoconnect() // 60 FPS base timer++ var body: some View {+ HStack(spacing: config.barSpacing) {+ ForEach(0..<config.barCount, id: \.self) { index in+ SpokenlyBar(+ height: index < barHeights.count ? barHeights[index] : config.minBarHeight,+ opacity: index < barOpacities.count ? barOpacities[index] : 0.4,+ index: index,+ config: config,+ isActive: isActive+ )+ }+ }+ .frame(width: config.containerWidth, height: config.containerHeight)+ .onAppear {+ initializeBars()+ isViewVisible = true+ }+ .onDisappear {+ isViewVisible = false+ }+ .onReceive(animationTimer) { _ in+ if isViewVisible {+ 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++ // Simple frame limiting - much more responsive+ let frameTime = 1.0 / 60.0 // 60 FPS always for real-time feel+ if currentTime - lastUpdateTime < frameTime { return }+ lastUpdateTime = currentTime++ // Safety check+ 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+ for i in 0..<min(config.barCount, barHeights.count) {+ barHeights[i] = config.minBarHeight+ barOpacities[i] = 0.3+ }+ } 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+ let maxParticleSize: CGFloat = 16+ let baseOpacity: Double = 0.2+ let maxOpacity: Double = 0.8+}++struct EnhancedTalkingAudioVisualizationView: View {+ @StateObject private var data: AudioVisualizationData+ @State private var dynamicNoiseThreshold: CGFloat = CGFloat(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))+ }++ var body: some View {+ HStack(spacing: config.particleSpacing) {+ ForEach(0..<config.particleCount, id: \.self) { index in+ PremiumTalkingParticle(+ audioLevel: data.audioLevel,+ config: config,+ index: index+ )+ }+ }+ .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+ }+ }+ }+}++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 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)+ .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)+ ]),+ 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)+ )+ .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()+ }+ }+ .onAppear {+ isParticleVisible = true+ }+ .onDisappear {+ 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+ pulseScale = 1.0+ if animationTrigger % 10 == 0 {+ rotationAngle += 0.2+ }+ } else {+ // Fast, responsive animation+ animationPhase += 0.3 // Much faster phase changes+ rotationAngle += 1.5 // Faster rotation+ pulseScale = 1.0 + (audioLevel * 0.15) // More pronounced pulsing+ }+ }+}++// MARK: - ECG-Style Listening Overlay+struct TalkingListeningOverlayView: View {+ let audioLevelPublisher: AnyPublisher<CGFloat, Never>+ @StateObject private var appTracker = ActiveAppTracker()+ @State private var recordingTime: TimeInterval = 0+ @State private var timer: Timer?++ private var appDisplayName: String {+ if let name = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String, name.isEmpty == false {+ return name+ }+ if let name = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String, name.isEmpty == false {+ return name+ }+ return "Fluid"+ }++ // Optional brand wordmark image from asset catalog+ private var brandWordmarkImage: NSImage? {+ // Try a few common names so you can drop in any of these+ return NSImage(named: "BrandWordmark")+ ?? NSImage(named: "FluidWordmark")+ ?? NSImage(named: "fluid_wordmark")+ }++ var body: some View {+ ZStack {+ // Premium glassmorphism container+ RoundedRectangle(cornerRadius: 16)+ .fill(+ LinearGradient(+ gradient: Gradient(colors: [+ Color.black.opacity(0.7),+ Color.black.opacity(0.9)+ ]),+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )+ )+ .background(+ RoundedRectangle(cornerRadius: 16)+ .fill(+ RadialGradient(+ gradient: Gradient(colors: [+ Color.purple.opacity(0.2),+ Color.black.opacity(0.4)+ ]),+ center: .center,+ startRadius: 0,+ endRadius: 100+ )+ )+ .blur(radius: 25)+ )+ .overlay(+ RoundedRectangle(cornerRadius: 16)+ .stroke(+ LinearGradient(+ gradient: Gradient(colors: [+ Color.white.opacity(0.2),+ Color.cyan.opacity(0.1),+ Color.purple.opacity(0.1),+ Color.clear+ ]),+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ ),+ lineWidth: 1.5+ )+ )+ .overlay(+ // Inner glow+ RoundedRectangle(cornerRadius: 16)+ .stroke(+ Color.white.opacity(0.1),+ lineWidth: 0.5+ )+ .blur(radius: 1)+ .offset(x: -1, y: -1)+ )++ // Timer - absolutely positioned top-left+ Text(formatTime(recordingTime))+ .font(.system(size: 12, weight: .medium, design: .monospaced))+ .foregroundColor(.white.opacity(0.8))+ .padding(.horizontal, 8)+ .padding(.vertical, 4)+ .background(+ RoundedRectangle(cornerRadius: 6)+ .fill(Color.black.opacity(0.5))+ .overlay(+ RoundedRectangle(cornerRadius: 6)+ .stroke(Color.white.opacity(0.1), lineWidth: 0.5)+ )+ )+ .padding(.leading, 12)+ .padding(.top, 8)+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)++ // Centered visualizer - absolutely positioned+ TalkingAudioVisualizationView(audioLevelPublisher: audioLevelPublisher)++ // App name box - absolutely positioned top-right+ HStack {+ Spacer()+ HStack(spacing: 6) {+ Image(systemName: "app.fill")+ .font(.caption2)+ .foregroundColor(.cyan.opacity(0.8))+ VStack(alignment: .leading, spacing: 2) {+ Text(appTracker.activeAppName)+ .font(.caption)+ .fontWeight(.medium)+ .foregroundColor(.white.opacity(0.95))+ .lineLimit(1)+ .truncationMode(.tail)+ if !appTracker.activeWindowTitle.isEmpty {+ Text(appTracker.activeWindowTitle)+ .font(.caption2)+ .foregroundColor(.white.opacity(0.7))+ .lineLimit(1)+ .truncationMode(.tail)+ }+ }+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ .background(+ RoundedRectangle(cornerRadius: 8)+ .fill(+ LinearGradient(+ gradient: Gradient(colors: [+ Color.black.opacity(0.6),+ Color.black.opacity(0.8)+ ]),+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )+ )+ .overlay(+ RoundedRectangle(cornerRadius: 8)+ .stroke(+ LinearGradient(+ gradient: Gradient(colors: [+ Color.cyan.opacity(0.3),+ Color.purple.opacity(0.2),+ Color.clear+ ]),+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ ),+ lineWidth: 1+ )+ )+ )+ .shadow(color: Color.black.opacity(0.4), radius: 3, x: 0, y: 2)+ .padding(.trailing, 12)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing)++ // Brand label - absolutely positioned bottom-right (wordmark if available, else icon + name)+ HStack {+ Spacer()+ HStack(spacing: 4) {+ if let wordmark = brandWordmarkImage {+ Image(nsImage: wordmark)+ .resizable()+ .interpolation(.high)+ .antialiased(true)+ .scaledToFit()+ .frame(height: 35)+ .shadow(color: .black.opacity(0.5), radius: 1, x: 0, y: 1)+ } else {+ if let nsIcon = NSApp.applicationIconImage {+ Image(nsImage: nsIcon)+ .resizable()+ .interpolation(.high)+ .antialiased(true)+ .frame(width: 12, height: 12)+ .cornerRadius(3)+ .shadow(color: .black.opacity(0.5), radius: 1, x: 0, y: 1)+ }+ Text(appDisplayName.uppercased())+ .font(.system(size: 11, weight: .semibold, design: .rounded))+ .kerning(0.6)+ .foregroundColor(.white.opacity(0.5))+ .shadow(color: .black.opacity(0.8), radius: 2, x: 1, y: 1)+ .shadow(color: .black.opacity(0.6), radius: 4, x: 2, y: 2)+ .shadow(color: .black.opacity(0.3), radius: 8, x: 0, y: 0)+ }+ }+ .padding(.horizontal, 8)+ .padding(.vertical, 4)+ .background(+ RoundedRectangle(cornerRadius: 12)+ .fill(+ LinearGradient(+ gradient: Gradient(colors: [+ Color.black.opacity(0.4),+ Color.black.opacity(0.6)+ ]),+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )+ )+ .overlay(+ RoundedRectangle(cornerRadius: 12)+ .stroke(+ Color.white.opacity(0.1),+ lineWidth: 0.5+ )+ )+ )+ .shadow(color: Color.black.opacity(0.3), radius: 2, x: 0, y: 1)+ .padding(.trailing, 12)+ .padding(.bottom, 8)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)+ }+ .frame(width: 280, height: 80)+ .shadow(color: Color.black.opacity(0.6), radius: 25, x: 0, y: 15)+ .shadow(color: Color.cyan.opacity(0.2), radius: 15, x: 0, y: 0)+ .shadow(color: Color.purple.opacity(0.1), radius: 30, x: 0, y: 5)+ .onAppear { startTimerIfNeeded() }+ .onDisappear { stopTimer() }+ .onReceive(audioLevelPublisher) { _ in }+ }++ private func startTimer() {+ recordingTime = 0+ timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in+ recordingTime += 0.1+ }+ if let timer {+ RunLoop.main.add(timer, forMode: .common)+ }+ }++ private func startTimerIfNeeded() {+ if timer == nil {+ startTimer()+ }+ }++ private func stopTimer() {+ timer?.invalidate()+ timer = nil+ recordingTime = 0+ }++ private func formatTime(_ time: TimeInterval) -> String {+ let minutes = Int(time) / 60+ let seconds = Int(time) % 60+ let tenths = Int((time.truncatingRemainder(dividingBy: 1)) * 10)+ return String(format: "%02d:%02d.%d", minutes, seconds, tenths)+ }+}++// 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)+ .frame(width: config.barWidth, height: height)+ .opacity(opacity)+ .shadow(color: Color.black.opacity(0.2), radius: 1, x: 0, y: 1)+ }+}++struct EnhancedTalkingListeningOverlayView: View {+ let audioLevelPublisher: AnyPublisher<CGFloat, Never>++ var body: some View {+ ZStack {+ EnhancedTalkingAudioVisualizationView(audioLevelPublisher: audioLevelPublisher)+ }+ .frame(width: 100, height: 32)+ .background(+ RoundedRectangle(cornerRadius: 16)+ .fill(Color.black.opacity(0.08))+ .blur(radius: 6)+ )+ }+}\ No newline at end of filediff --git a/Sources/Fluid/UI/FluidIcon.swift b/Sources/Fluid/UI/FluidIcon.swiftnew file mode 100644index 00000000..95b6a7c5--- /dev/null+++ b/Sources/Fluid/UI/FluidIcon.swift@@ -0,0 +1,246 @@+//+// 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 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++ // 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,+ y: topEdge,+ width: width,+ height: strokeWidth+ )+ path.addRect(topBarRect)++ // Vertical spine - bold, geometric+ let spineRect = CGRect(+ x: leftEdge,+ y: topEdge,+ width: strokeWidth,+ height: height+ )+ path.addRect(spineRect)++ // Middle horizontal bar - 60% width for dynamic proportions+ let middleBarWidth = width * 0.6+ let middleBarRect = CGRect(+ x: leftEdge,+ y: middleY,+ width: middleBarWidth,+ height: strokeWidth+ )+ path.addRect(middleBarRect)+ }++ // Fill the geometric shapes (no stroke, pure geometry)+ context.fill(path, with: .color(color))++ // Optional: Add subtle inner highlight for premium feel+ if 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)))+ }+ }+ .frame(width: size, height: size)+ }+}++// Variants for different use cases+struct FluidIconFilled: View {+ let size: CGFloat+ 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)+ }+ }+}++// Advanced variant with sophisticated negative space+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)++ // 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))+ path.addLine(to: CGPoint(x: leftX + strokeWidth * cutAngle, y: topY))+ 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))+ path.addLine(to: CGPoint(x: leftX + topBarWidth, y: topY))+ 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))+ path.addLine(to: CGPoint(x: leftX + middleBarWidth, y: middleY))+ path.addLine(to: CGPoint(x: leftX + middleBarWidth - strokeWidth * cutAngle, y: middleY + strokeWidth))+ path.addLine(to: CGPoint(x: leftX, y: middleY + strokeWidth))+ path.closeSubpath()+ }++ context.fill(path, with: .color(color))++ // Add premium inner glow effect+ let glowPath = Path { path in+ let inset: CGFloat = 1+ let adjustedRect = workingRect.insetBy(dx: inset, dy: inset)+ 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)))+ }+ .frame(width: size, height: size)+ }+}++// Preview for development+#Preview("Fluid Icon Variants") {+ 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 filediff --git a/Sources/Fluid/UI/GlossyEffects.swift b/Sources/Fluid/UI/GlossyEffects.swiftnew file mode 100644index 00000000..71b7a394--- /dev/null+++ b/Sources/Fluid/UI/GlossyEffects.swift@@ -0,0 +1,185 @@+import SwiftUI+++// MARK: - 3D Hoverable Card Component+struct HoverableGlossyCard<Content: View>: View {+ @State private var isHovered = false+ let content: Content+ let excludeInteractiveElements: Bool++ init(excludeInteractiveElements: Bool = false, @ViewBuilder content: () -> Content) {+ self.content = content()+ self.excludeInteractiveElements = excludeInteractiveElements+ }++ var body: some View {+ content+ .background(+ RoundedRectangle(cornerRadius: 20)+ .fill(.ultraThinMaterial.opacity(0.8))+ .background(+ RoundedRectangle(cornerRadius: 20)+ .fill(+ LinearGradient(+ colors: [+ Color(red: 0.12, green: 0.14, blue: 0.22).opacity(0.4), // Deep tech blue+ Color(red: 0.08, green: 0.10, blue: 0.18).opacity(0.2), // Blue-charcoal+ Color(red: 0.05, green: 0.06, blue: 0.12).opacity(0.1), // Rich blue-black+ Color(red: 0.10, green: 0.12, blue: 0.20).opacity(0.3) // Dark blue accent+ ],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )+ )+ )+ .overlay(+ RoundedRectangle(cornerRadius: 20)+ .stroke(Color.white.opacity(isHovered ? 0.4 : 0.2), lineWidth: isHovered ? 1.5 : 1)+ .blur(radius: 0.5)+ )+ .shadow(color: Color(red: 0.02, green: 0.03, blue: 0.06).opacity(isHovered ? 0.8 : 0.5), radius: isHovered ? 40 : 30, x: 0, y: isHovered ? 20 : 15)+ .shadow(color: Color(red: 0.01, green: 0.02, blue: 0.04).opacity(isHovered ? 0.6 : 0.3), radius: isHovered ? 20 : 12, x: 0, y: isHovered ? 8 : 5)+ .shadow(color: Color(red: 0.06, green: 0.08, blue: 0.15).opacity(isHovered ? 0.3 : 0.1), radius: isHovered ? 8 : 4, x: 0, y: isHovered ? 3 : 2)+ )+ .brightness(isHovered && !excludeInteractiveElements ? 0.02 : 0.0)+ .onHover { hovering in+ isHovered = hovering+ }+ .animation(.easeInOut(duration: 0.15), value: isHovered)+ }+}++// MARK: - Enhanced Button with Hover Effects+struct HoverableButton<Content: View>: View {+ @State private var isHovered = false+ let action: () -> Void+ let isDisabled: Bool+ let content: Content++ init(action: @escaping () -> Void, isDisabled: Bool = false, @ViewBuilder content: () -> Content) {+ self.action = action+ self.isDisabled = isDisabled+ self.content = content()+ }++ var body: some View {+ Button(action: action) {+ content+ .scaleEffect(isHovered && !isDisabled ? 1.05 : 1.0)+ .brightness(isHovered && !isDisabled ? 0.1 : 0.0)+ .shadow(+ color: .white.opacity(isHovered && !isDisabled ? 0.3 : 0.1),+ radius: isHovered && !isDisabled ? 8 : 2+ )+ }+ .disabled(isDisabled)+ .onHover { hovering in+ if !isDisabled {+ isHovered = hovering+ }+ }+ .animation(.spring(response: 0.2, dampingFraction: 0.7), value: isHovered)+ }+}++// MARK: - Enhanced Button Styles with Hover Effects+struct EnhancedGlassButtonStyle: ButtonStyle {+ @State private var isHovered = false++ func makeBody(configuration: Configuration) -> some View {+ configuration.label+ .fontWeight(.semibold)+ .padding(.horizontal, 20)+ .padding(.vertical, 12)+ .background(+ RoundedRectangle(cornerRadius: 10)+ .fill(.ultraThinMaterial.opacity(0.9))+ .background(+ RoundedRectangle(cornerRadius: 10)+ .fill(+ LinearGradient(+ colors: [+ Color(red: 0.15, green: 0.17, blue: 0.28).opacity(isHovered ? 0.5 : 0.3), // Deep tech blue+ Color(red: 0.08, green: 0.10, blue: 0.18).opacity(isHovered ? 0.3 : 0.15), // Blue-charcoal+ Color(red: 0.05, green: 0.06, blue: 0.12).opacity(0.1), // Rich blue-black+ Color(red: 0.12, green: 0.14, blue: 0.24).opacity(isHovered ? 0.4 : 0.2) // Dark blue accent+ ],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ )+ )+ )+ .overlay(+ RoundedRectangle(cornerRadius: 10)+ .stroke(Color.white.opacity(isHovered ? 0.4 : 0.25), lineWidth: isHovered ? 1.5 : 1)+ .blur(radius: 0.3)+ )+ .shadow(color: Color(red: 0.02, green: 0.03, blue: 0.06).opacity(isHovered ? 0.7 : 0.4), radius: isHovered ? 15 : 10, x: 0, y: isHovered ? 8 : 5)+ .shadow(color: Color(red: 0.06, green: 0.08, blue: 0.15).opacity(isHovered ? 0.3 : 0.15), radius: isHovered ? 6 : 3, x: 0, y: isHovered ? 3 : 2)+ )+ .scaleEffect(configuration.isPressed ? 0.96 : (isHovered ? 1.05 : 1.0))+ .brightness(isHovered ? 0.05 : 0.0)+ .onHover { hovering in isHovered = hovering }+ .animation(.spring(response: 0.2, dampingFraction: 0.8), value: configuration.isPressed)+ .animation(.spring(response: 0.2, dampingFraction: 0.7), value: isHovered)+ }+}++// MARK: - Button Hover Extension+extension View {+ func buttonHoverEffect() -> some View {+ self.modifier(ButtonHoverModifier())+ }+}++struct ButtonHoverModifier: ViewModifier {+ @State private var isHovered = false++ func body(content: Content) -> some View {+ content+ .scaleEffect(isHovered ? 1.05 : 1.0)+ .brightness(isHovered ? 0.1 : 0.0)+ .shadow(color: .white.opacity(isHovered ? 0.3 : 0.0), radius: isHovered ? 6 : 0)+ .onHover { hovering in+ isHovered = hovering+ }+ .animation(.spring(response: 0.2, dampingFraction: 0.7), value: isHovered)+ }+}++// Removed CursorFollowingGlow - was causing performance issues+// struct CursorFollowingGlow: View {+// @EnvironmentObject var mouseTracker: MousePositionTracker+// let size: CGFloat+// let intensity: Double+//+// init(size: CGFloat = 300, intensity: Double = 0.2) {+// self.size = size+// self.intensity = intensity+// }+//+// var body: some View {+// GeometryReader { geometry in+// let relativeX = mouseTracker.relativePosition.x+// let relativeY = mouseTracker.relativePosition.y+//+// RadialGradient(+// colors: [+// Color.white.opacity(intensity * 0.6),+// Color.white.opacity(intensity * 0.3),+// Color.white.opacity(intensity * 0.1),+// Color.clear+// ],+// center: UnitPoint(x: relativeX, y: relativeY),+// startRadius: size * 0.1,+// endRadius: size * 0.5+// )+// .blendMode(.overlay)+// .allowsHitTesting(false)+// .animation(.easeInOut(duration: 0.25), value: mouseTracker.mousePosition)+// }+// }+// }+++diff --git a/Sources/Fluid/UI/MenuBarIconGenerator.swift b/Sources/Fluid/UI/MenuBarIconGenerator.swiftnew file mode 100644index 00000000..f7b353ce--- /dev/null+++ b/Sources/Fluid/UI/MenuBarIconGenerator.swift@@ -0,0 +1,59 @@+import AppKit++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 filediff --git a/Sources/Fluid/UI/MouseTracker.swift b/Sources/Fluid/UI/MouseTracker.swiftnew file mode 100644index 00000000..190b1ba5--- /dev/null+++ b/Sources/Fluid/UI/MouseTracker.swift@@ -0,0 +1,70 @@+import SwiftUI+import Combine++@MainActor+class MousePositionTracker: ObservableObject {+ @Published var mousePosition: CGPoint = .zero+ @Published var windowFrame: CGRect = .zero++ private var lastUpdateTime: TimeInterval = 0+ private let updateInterval: TimeInterval = 1.0/30.0 // 30fps++ var relativePosition: CGPoint {+ guard windowFrame.width > 0 && windowFrame.height > 0 else { return .zero }+ return CGPoint(+ x: (mousePosition.x - windowFrame.minX) / windowFrame.width,+ y: (mousePosition.y - windowFrame.minY) / windowFrame.height+ )+ }++ func updateMousePosition(_ position: CGPoint) {+ let now = CACurrentMediaTime()+ guard now - lastUpdateTime >= updateInterval else { return }++ mousePosition = position+ lastUpdateTime = now+ }++ func updateWindowFrame(_ frame: CGRect) {+ windowFrame = frame+ }+}++struct MouseTrackingModifier: ViewModifier {+ let tracker: MousePositionTracker++ func body(content: Content) -> some View {+ content+ .onContinuousHover { phase in+ switch phase {+ case .active(let location):+ // Convert to global coordinates for consistent tracking+ let globalLocation = CGPoint(+ x: location.x + (tracker.windowFrame.minX),+ y: location.y + (tracker.windowFrame.minY)+ )+ 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+ tracker.updateWindowFrame(newFrame)+ }+ }+ )+ }+}++extension View {+ func withMouseTracking(_ tracker: MousePositionTracker) -> some View {+ self.modifier(MouseTrackingModifier(tracker: tracker))+ }+}\ No newline at end of filediff --git a/Sources/Fluid/UI/Visualization/AudioVisualizationShared.swift b/Sources/Fluid/UI/Visualization/AudioVisualizationShared.swiftnew file mode 100644index 00000000..70cf3a4f--- /dev/null+++ b/Sources/Fluid/UI/Visualization/AudioVisualizationShared.swift@@ -0,0 +1,31 @@+import SwiftUI+import Combine++protocol AudioVisualizationConfig+{+ var noiseThreshold: CGFloat { get }+ var maxAnimationScale: CGFloat { get }+ var animationSpring: Animation { get }+}++final class AudioVisualizationData: ObservableObject+{+ @Published var audioLevel: CGFloat = 0.0+ private var cancellable: AnyCancellable?++ init(audioLevelPublisher: AnyPublisher<CGFloat, Never>)+ {+ cancellable = audioLevelPublisher+ .receive(on: RunLoop.main)+ .sink { [weak self] level in+ self?.audioLevel = level+ }+ }++ deinit+ {+ cancellable?.cancel()+ }+}++diff --git a/Sources/Fluid/fluidApp.swift b/Sources/Fluid/fluidApp.swiftnew file mode 100644index 00000000..b47a1eb5--- /dev/null+++ b/Sources/Fluid/fluidApp.swift@@ -0,0 +1,69 @@+//+// fluidApp.swift+// fluid+//+// Created by Barathwaj Anandan on 7/30/25.+//++import SwiftUI+import AppKit+import ApplicationServices++@main+struct fluidApp: App {+ @StateObject private var menuBarManager = MenuBarManager()++ init() {+ // Request accessibility permissions for global hotkey monitoring+ requestAccessibilityPermissions()++ // Initialize app settings (dock visibility, etc.)+ SettingsStore.shared.initializeAppSettings()+ }++ var body: some Scene {+ WindowGroup {+ ContentView()+ .environmentObject(menuBarManager)+ }+ }++ private func requestAccessibilityPermissions() {+ // Never show if already trusted+ guard !AXIsProcessTrusted() else { return }++ // Per-session debounce+ if AXPromptState.hasPromptedThisSession { return }++ // Cooldown: avoid re-prompting too often across launches+ let cooldownKey = "AXLastPromptAt"+ let now = Date().timeIntervalSince1970+ let last = UserDefaults.standard.double(forKey: cooldownKey)+ let oneDay: Double = 24 * 60 * 60+ if last > 0 && (now - last) < oneDay {+ return+ }++ DebugLogger.shared.warning("Accessibility permissions required for global hotkeys.", source: "fluidApp")+ DebugLogger.shared.info("Prompting for Accessibility permission…", source: "fluidApp")++ let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary+ AXIsProcessTrustedWithOptions(options)++ AXPromptState.hasPromptedThisSession = true+ UserDefaults.standard.set(now, forKey: cooldownKey)++ // If still not trusted shortly after, deep-link to the Accessibility pane for convenience+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {+ guard !AXIsProcessTrusted(),+ let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")+ else { return }+ NSWorkspace.shared.open(url)+ }+ }+}++// MARK: - Session Debounce State+private enum AXPromptState {+ static var hasPromptedThisSession: Bool = false+}