Skip to content

Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more

Add anonymized product analytics (#67)

Rohith Gandhi Gfb432ca98b1f
diff --git a/Info.plist b/Info.plist
index d1968425..77fe9499 100644
--- a/Info.plist
+++ b/Info.plist
@@ -24,6 +24,10 @@
<true/>
<key>NSAppleEventsUsageDescription</key>
<string>FluidVoice needs permission to control system events for managing launch at startup settings.</string>
+ <key>POSTHOG_API_KEY</key>
+ <string>phc_coNu37345O2bgaAeQMD3tezkg1rDCbDS9Y3pOVvp2VM</string>
+ <key>POSTHOG_HOST</key>
+ <string>https://eu.i.posthog.com</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>FluidVoice uses on-device speech recognition to transcribe your voice commands and text quickly and privately.</string>
</dict>
diff --git a/Package.resolved b/Package.resolved
index c724edff..7eaec392 100644
--- a/Package.resolved
+++ b/Package.resolved
@@ -45,6 +45,15 @@
"version" : "1.4.1"
}
},
+ {
+ "identity" : "posthog-ios",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/PostHog/posthog-ios.git",
+ "state" : {
+ "revision" : "cfbae6be113616156e6840dbfb61d59593ea1db5",
+ "version" : "3.36.2"
+ }
+ },
{
"identity" : "promisekit",
"kind" : "remoteSourceControl",
diff --git a/Package.swift b/Package.swift
index 747cceea..df766faf 100644
--- a/Package.swift
+++ b/Package.swift
@@ -14,6 +14,7 @@ let package = Package(
.package(url: "https://github.com/mxcl/PromiseKit", from: "6.0.0"),
.package(url: "https://github.com/MrKai77/DynamicNotchKit", from: "1.0.0"),
.package(url: "https://github.com/exPHAT/SwiftWhisper.git", branch: "master"),
+ .package(url: "https://github.com/PostHog/posthog-ios.git", from: "3.0.0"),
],
targets: [
.executableTarget(
@@ -24,6 +25,7 @@ let package = Package(
"PromiseKit",
"DynamicNotchKit",
"SwiftWhisper",
+ .product(name: "PostHog", package: "posthog-ios"),
]
),
]
diff --git a/Sources/Fluid/Analytics/AnalyticsBuckets.swift b/Sources/Fluid/Analytics/AnalyticsBuckets.swift
new file mode 100644
index 00000000..87ee62d5
--- /dev/null
+++ b/Sources/Fluid/Analytics/AnalyticsBuckets.swift
@@ -0,0 +1,45 @@
+import Foundation
+
+enum AnalyticsBuckets {
+ static func wordCount(in text: String) -> Int {
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return 0 }
+ return trimmed
+ .split(whereSeparator: { $0.isWhitespace || $0.isNewline })
+ .count
+ }
+
+ static func bucketWords(_ count: Int) -> String {
+ switch count {
+ case ...0: return "0"
+ case 1...5: return "1-5"
+ case 6...20: return "6-20"
+ case 21...50: return "21-50"
+ case 51...100: return "51-100"
+ case 101...300: return "101-300"
+ default: return "301+"
+ }
+ }
+
+ static func bucketSeconds(_ seconds: Double) -> String {
+ switch seconds {
+ case ..<0.5: return "<0.5s"
+ case 0.5..<2: return "0.5-2s"
+ case 2..<5: return "2-5s"
+ case 5..<15: return "5-15s"
+ case 15..<60: return "15-60s"
+ default: return "60s+"
+ }
+ }
+
+ static func bucketMs(_ ms: Double) -> String {
+ switch ms {
+ case ..<100: return "<100ms"
+ case 100..<300: return "100-300ms"
+ case 300..<1000: return "300ms-1s"
+ case 1000..<3000: return "1-3s"
+ case 3000..<10_000: return "3-10s"
+ default: return "10s+"
+ }
+ }
+}
diff --git a/Sources/Fluid/Analytics/AnalyticsConfig.swift b/Sources/Fluid/Analytics/AnalyticsConfig.swift
new file mode 100644
index 00000000..c4327673
--- /dev/null
+++ b/Sources/Fluid/Analytics/AnalyticsConfig.swift
@@ -0,0 +1,18 @@
+import Foundation
+
+struct AnalyticsConfig {
+ let postHogApiKey: String
+ let postHogHost: String
+
+ /// Default EU ingestion host.
+ static let defaultEUHost = "https://eu.i.posthog.com"
+
+ static func fromBundle() -> AnalyticsConfig {
+ let info = Bundle.main.infoDictionary ?? [:]
+ let key = (info["POSTHOG_API_KEY"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ let host = (info["POSTHOG_HOST"] as? String ?? AnalyticsConfig.defaultEUHost).trimmingCharacters(in: .whitespacesAndNewlines)
+ return AnalyticsConfig(postHogApiKey: key, postHogHost: host.isEmpty ? AnalyticsConfig.defaultEUHost : host)
+ }
+
+ var isConfigured: Bool { !self.postHogApiKey.isEmpty }
+}
diff --git a/Sources/Fluid/Analytics/AnalyticsEvent.swift b/Sources/Fluid/Analytics/AnalyticsEvent.swift
new file mode 100644
index 00000000..81b3a22f
--- /dev/null
+++ b/Sources/Fluid/Analytics/AnalyticsEvent.swift
@@ -0,0 +1,49 @@
+import Foundation
+
+/// Typed analytics events to avoid typos and enforce a low-cardinality schema.
+enum AnalyticsEvent: String {
+ // App lifecycle
+ case appFirstOpen = "app_first_open"
+ case appOpen = "app_open"
+
+ // Consent
+ case analyticsConsentChanged = "analytics_consent_changed"
+
+ // Dictation
+ case transcriptionCompleted = "transcription_completed"
+ case outputDelivered = "output_delivered"
+
+ // Command mode
+ case commandModeRunCompleted = "command_mode_run_completed"
+
+ // Write/Rewrite
+ case rewriteRunCompleted = "rewrite_run_completed"
+
+ // Meeting transcription
+ case meetingTranscriptionCompleted = "meeting_transcription_completed"
+
+ // Errors
+ case errorOccurred = "error_occurred"
+}
+
+enum AnalyticsMode: String {
+ case dictation
+ case command
+ case rewrite
+ case meeting
+}
+
+enum AnalyticsOutputMethod: String {
+ case typed
+ case clipboard
+ case historyOnly = "history_only"
+}
+
+enum AnalyticsErrorDomain: String {
+ case asr
+ case llm
+ case typing
+ case hotkey
+ case update
+ case other
+}
diff --git a/Sources/Fluid/Analytics/AnalyticsIdentityStore.swift b/Sources/Fluid/Analytics/AnalyticsIdentityStore.swift
new file mode 100644
index 00000000..95994b40
--- /dev/null
+++ b/Sources/Fluid/Analytics/AnalyticsIdentityStore.swift
@@ -0,0 +1,40 @@
+import Foundation
+
+/// Stores anonymous analytics identifiers. This is intentionally NOT tied to any user identity.
+final class AnalyticsIdentityStore {
+ static let shared = AnalyticsIdentityStore()
+
+ private let defaults = UserDefaults.standard
+
+ private enum Keys {
+ static let anonymousInstallID = "AnalyticsAnonymousInstallID"
+ static let firstOpenAt = "AnalyticsFirstOpenAt"
+ }
+
+ private init() {}
+
+ var anonymousInstallID: String {
+ if let existing = defaults.string(forKey: Keys.anonymousInstallID), existing.isEmpty == false {
+ return existing
+ }
+ let newID = UUID().uuidString
+ self.defaults.set(newID, forKey: Keys.anonymousInstallID)
+ return newID
+ }
+
+ /// Returns true if this is the first time we've ever recorded an app open on this install.
+ @discardableResult
+ func ensureFirstOpenRecorded() -> Bool {
+ if self.defaults.object(forKey: Keys.firstOpenAt) == nil {
+ self.defaults.set(Date().timeIntervalSince1970, forKey: Keys.firstOpenAt)
+ return true
+ }
+ return false
+ }
+
+ var firstOpenAt: Date? {
+ let ts = self.defaults.double(forKey: Keys.firstOpenAt)
+ if ts <= 0 { return nil }
+ return Date(timeIntervalSince1970: ts)
+ }
+}
diff --git a/Sources/Fluid/Analytics/AnalyticsService.swift b/Sources/Fluid/Analytics/AnalyticsService.swift
new file mode 100644
index 00000000..40ea39b2
--- /dev/null
+++ b/Sources/Fluid/Analytics/AnalyticsService.swift
@@ -0,0 +1,238 @@
+import Foundation
+
+/// Lightweight analytics pipeline:
+/// - bounded in-memory queue (drops oldest)
+/// - periodic background flush
+/// - fire-and-forget publishing (does not await responses)
+final class AnalyticsService {
+ static let shared = AnalyticsService()
+
+ private let core = AnalyticsCore()
+
+ private init() {}
+
+ /// Call once at startup. Cheap and does not start networking unless configured + enabled.
+ func bootstrap() {
+ let enabled = SettingsStore.shared.shareAnonymousAnalytics
+ let config = AnalyticsConfig.fromBundle()
+ Task.detached(priority: .background) { [core] in
+ await core.bootstrap(enabled: enabled, config: config)
+ }
+ }
+
+ func setEnabled(_ enabled: Bool) {
+ let config = AnalyticsConfig.fromBundle()
+ Task.detached(priority: .background) { [core] in
+ await core.setEnabled(enabled, config: config)
+ }
+ }
+
+ func capture(_ event: AnalyticsEvent, properties: [String: Any] = [:]) {
+ // Capture should be as close to O(1) as possible on the caller thread.
+ // We compute common properties quickly (no heavy work, no content).
+ let common = AnalyticsService.commonProperties()
+ let merged = common.merging(properties) { _, new in new }
+
+ let enabled = SettingsStore.shared.shareAnonymousAnalytics
+ let config = AnalyticsConfig.fromBundle()
+ let distinctID = AnalyticsIdentityStore.shared.anonymousInstallID
+
+ Task.detached(priority: .background) { [core] in
+ await core.capture(
+ eventName: event.rawValue,
+ distinctID: distinctID,
+ enabled: enabled,
+ config: config,
+ properties: merged
+ )
+ }
+ }
+
+ // MARK: - Common props (low-cardinality only)
+
+ private static func commonProperties() -> [String: Any] {
+ let info = Bundle.main.infoDictionary
+ let version = info?["CFBundleShortVersionString"] as? String ?? "unknown"
+ let build = info?["CFBundleVersion"] as? String ?? "unknown"
+
+ let os = ProcessInfo.processInfo.operatingSystemVersion
+ let osVersion = "\(os.majorVersion).\(os.minorVersion).\(os.patchVersion)"
+
+ #if arch(arm64)
+ let arch = "arm64"
+ #else
+ let arch = "x86_64"
+ #endif
+
+ #if DEBUG
+ let environment = "debug"
+ #else
+ let environment = "release"
+ #endif
+
+ let settings = SettingsStore.shared
+
+ return [
+ "app_version": version,
+ "app_build": build,
+ "os_version": osVersion,
+ "arch": arch,
+ "environment": environment,
+
+ // Low-cardinality settings snapshot
+ "ai_processing_enabled": settings.enableAIProcessing,
+ "streaming_preview_enabled": settings.enableStreamingPreview,
+ "press_and_hold_mode": settings.pressAndHoldMode,
+ "copy_to_clipboard_enabled": settings.copyTranscriptionToClipboard,
+ ]
+ }
+}
+
+// MARK: - Core (actor)
+
+private actor AnalyticsCore {
+ private var enabled: Bool = true
+ private var config: AnalyticsConfig = .fromBundle()
+
+ // Bounded queue to protect memory.
+ private var queue: [[String: Any]] = []
+ private let maxQueuedEvents: Int = 200
+
+ // Flush tuning.
+ private let flushAt: Int = 20
+ private let flushIntervalSeconds: UInt64 = 30
+
+ private var flushTask: Task<Void, Never>?
+ private var isFlushing: Bool = false
+
+ func bootstrap(enabled: Bool, config: AnalyticsConfig) async {
+ self.enabled = enabled
+ self.config = config
+
+ // Record first open timestamp (used for retention-style calculations).
+ _ = AnalyticsIdentityStore.shared.ensureFirstOpenRecorded()
+
+ self.startFlushLoopIfNeeded()
+ }
+
+ func setEnabled(_ enabled: Bool, config: AnalyticsConfig) async {
+ self.enabled = enabled
+ self.config = config
+
+ if !enabled {
+ // Drop any pending events to honor opt-out immediately.
+ self.queue.removeAll(keepingCapacity: true)
+ }
+
+ self.startFlushLoopIfNeeded()
+ }
+
+ func capture(
+ eventName: String,
+ distinctID: String,
+ enabled: Bool,
+ config: AnalyticsConfig,
+ properties: [String: Any]
+ ) async {
+ // Use latest values passed by caller to avoid cross-actor UserDefaults reads.
+ self.enabled = enabled
+ self.config = config
+
+ guard self.enabled, self.config.isConfigured else { return }
+
+ var event: [String: Any] = [:]
+ event["event"] = eventName
+ event["timestamp"] = ISO8601DateFormatter().string(from: Date())
+
+ // PostHog expects distinct_id inside properties.
+ var props = properties
+ props["distinct_id"] = distinctID
+ props["$lib"] = "FluidVoice"
+ props["$lib_version"] = "1"
+ event["properties"] = props
+
+ self.enqueue(event)
+
+ if self.queue.count >= self.flushAt {
+ await self.flushIfNeeded()
+ }
+ }
+
+ private func enqueue(_ event: [String: Any]) {
+ self.queue.append(event)
+ if self.queue.count > self.maxQueuedEvents {
+ // Drop oldest.
+ self.queue.removeFirst(self.queue.count - self.maxQueuedEvents)
+ }
+ }
+
+ private func startFlushLoopIfNeeded() {
+ // Only run a background flush loop when enabled and configured.
+ guard self.enabled, self.config.isConfigured else {
+ self.flushTask?.cancel()
+ self.flushTask = nil
+ return
+ }
+
+ guard self.flushTask == nil else { return }
+
+ self.flushTask = Task.detached(priority: .background) { [weak self] in
+ guard let self else { return }
+ while !Task.isCancelled {
+ try? await Task.sleep(nanoseconds: self.flushIntervalSeconds * 1_000_000_000)
+ await self.flushIfNeeded()
+ }
+ }
+ }
+
+ private func flushIfNeeded() async {
+ guard self.enabled, self.config.isConfigured else { return }
+ guard !self.queue.isEmpty else { return }
+ guard !self.isFlushing else { return }
+
+ self.isFlushing = true
+ defer { self.isFlushing = false }
+
+ // Drain up to max batch size.
+ let batchCount = min(self.queue.count, self.maxQueuedEvents)
+ let batch = Array(self.queue.prefix(batchCount))
+ self.queue.removeFirst(batchCount)
+
+ await self.sendBatch(batch)
+ }
+
+ private func sendBatch(_ batch: [[String: Any]]) async {
+ // Fire-and-forget network request; do not await response.
+ let host = self.config.postHogHost
+ let apiKey = self.config.postHogApiKey
+
+ guard let url = URL(string: host)?.appendingPathComponent("batch") else { return }
+
+ var payload: [String: Any] = [
+ "api_key": apiKey,
+ "batch": batch,
+ ]
+
+ // Ensure payload is JSON serializable.
+ guard JSONSerialization.isValidJSONObject(payload) else { return }
+
+ let data: Data
+ do {
+ data = try JSONSerialization.data(withJSONObject: payload, options: [])
+ } catch {
+ return
+ }
+
+ var request = URLRequest(url: url)
+ request.httpMethod = "POST"
+ request.httpBody = data
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ request.timeoutInterval = 8
+
+ // Detached task ensures we never block the actor while URLSession does its work.
+ Task.detached(priority: .background) {
+ let session = URLSession.shared
+ _ = try? await session.data(for: request)
+ }
+ }
+}
diff --git a/Sources/Fluid/AppDelegate.swift b/Sources/Fluid/AppDelegate.swift
index 4e389b6e..4eeced8c 100644
--- a/Sources/Fluid/AppDelegate.swift
+++ b/Sources/Fluid/AppDelegate.swift
@@ -25,6 +25,17 @@ class AppDelegate: NSObject, NSApplicationDelegate {
// Initialize app settings (dock visibility, etc.)
SettingsStore.shared.initializeAppSettings()
+ AnalyticsService.shared.bootstrap()
+
+ let isFirstOpen = AnalyticsIdentityStore.shared.ensureFirstOpenRecorded()
+ if isFirstOpen {
+ AnalyticsService.shared.capture(.appFirstOpen)
+ }
+ AnalyticsService.shared.capture(
+ .appOpen,
+ properties: ["accessibility_trusted": AXIsProcessTrusted()]
+ )
+
// Check for updates automatically if enabled (initial check on launch)
self.checkForUpdatesAutomatically()
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 3116dd61..6bb02e99 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -1389,6 +1389,14 @@ struct ContentView: View {
if wasRewriteMode {
DebugLogger.shared.info("Processing rewrite with instruction: \(transcribedText)", source: "ContentView")
await self.processRewriteWithVoiceInstruction(transcribedText)
+ AnalyticsService.shared.capture(
+ .transcriptionCompleted,
+ properties: [
+ "mode": AnalyticsMode.rewrite.rawValue,
+ "words_bucket": AnalyticsBuckets.bucketWords(AnalyticsBuckets.wordCount(in: transcribedText)),
+ "ai_used": true,
+ ]
+ )
return
}
@@ -1396,6 +1404,14 @@ struct ContentView: View {
if wasCommandMode {
DebugLogger.shared.info("Processing command: \(transcribedText)", source: "ContentView")
await self.processCommandWithVoice(transcribedText)
+ AnalyticsService.shared.capture(
+ .transcriptionCompleted,
+ properties: [
+ "mode": AnalyticsMode.command.rawValue,
+ "words_bucket": AnalyticsBuckets.bucketWords(AnalyticsBuckets.wordCount(in: transcribedText)),
+ "ai_used": true,
+ ]
+ )
return
}
@@ -1433,6 +1449,16 @@ struct ContentView: View {
DebugLogger.shared.info("Transcription finalized (chars: \(finalText.count))", source: "ContentView")
+ AnalyticsService.shared.capture(
+ .transcriptionCompleted,
+ properties: [
+ "mode": AnalyticsMode.dictation.rawValue,
+ "words_bucket": AnalyticsBuckets.bucketWords(AnalyticsBuckets.wordCount(in: finalText)),
+ "ai_used": shouldUseAI,
+ "ai_changed_text": transcribedText != finalText,
+ ]
+ )
+
// Save to transcription history (transcription mode only, if enabled)
if SettingsStore.shared.saveTranscriptionHistory {
let appInfo = self.recordingAppInfo ?? self.getCurrentAppInfo()
@@ -1447,8 +1473,16 @@ struct ContentView: View {
// Copy to clipboard if enabled (happens before typing as a backup)
if SettingsStore.shared.copyTranscriptionToClipboard {
ClipboardService.copyToClipboard(finalText)
+ AnalyticsService.shared.capture(
+ .outputDelivered,
+ properties: [
+ "mode": AnalyticsMode.dictation.rawValue,
+ "method": AnalyticsOutputMethod.clipboard.rawValue,
+ ]
+ )
}
+ var didTypeExternally = false
await MainActor.run {
let frontmostApp = NSWorkspace.shared.frontmostApplication
let frontmostName = frontmostApp?.localizedName ?? "Unknown"
@@ -1462,8 +1496,29 @@ struct ContentView: View {
if shouldTypeExternally {
self.asr.typeTextToActiveField(finalText)
+ didTypeExternally = true
}
}
+
+ if didTypeExternally {
+ AnalyticsService.shared.capture(
+ .outputDelivered,
+ properties: [
+ "mode": AnalyticsMode.dictation.rawValue,
+ "method": AnalyticsOutputMethod.typed.rawValue,
+ ]
+ )
+ } else if SettingsStore.shared.copyTranscriptionToClipboard == false,
+ SettingsStore.shared.saveTranscriptionHistory
+ {
+ AnalyticsService.shared.capture(
+ .outputDelivered,
+ properties: [
+ "mode": AnalyticsMode.dictation.rawValue,
+ "method": AnalyticsOutputMethod.historyOnly.rawValue,
+ ]
+ )
+ }
}
// MARK: - Rewrite Mode Voice Processing
@@ -1490,15 +1545,36 @@ struct ContentView: View {
// Copy to clipboard as backup
if SettingsStore.shared.copyTranscriptionToClipboard {
ClipboardService.copyToClipboard(self.rewriteModeService.rewrittenText)
+ AnalyticsService.shared.capture(
+ .outputDelivered,
+ properties: [
+ "mode": AnalyticsMode.rewrite.rawValue,
+ "method": AnalyticsOutputMethod.clipboard.rawValue,
+ ]
+ )
}
// Type the rewritten text
self.asr.typeTextToActiveField(self.rewriteModeService.rewrittenText)
+ AnalyticsService.shared.capture(
+ .outputDelivered,
+ properties: [
+ "mode": AnalyticsMode.rewrite.rawValue,
+ "method": AnalyticsOutputMethod.typed.rawValue,
+ ]
+ )
// Clear the rewrite service state for next use
self.rewriteModeService.clearState()
} else {
DebugLogger.shared.error("Rewrite failed - no result", source: "ContentView")
+ AnalyticsService.shared.capture(
+ .errorOccurred,
+ properties: [
+ "domain": AnalyticsErrorDomain.llm.rawValue,
+ "category": "rewrite_no_result",
+ ]
+ )
}
}
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index 25cb08d4..a2186bfd 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -26,6 +26,7 @@ final class SettingsStore: ObservableObject {
static let providerAPIKeys = "ProviderAPIKeys"
static let providerAPIKeyIdentifiers = "ProviderAPIKeyIdentifiers"
static let savedProviders = "SavedProviders"
+ static let shareAnonymousAnalytics = "ShareAnonymousAnalytics"
static let hotkeyShortcutKey = "HotkeyShortcutKey"
static let preferredInputDeviceUID = "PreferredInputDeviceUID"
static let preferredOutputDeviceUID = "PreferredOutputDeviceUID"
@@ -148,6 +149,20 @@ final class SettingsStore: ObservableObject {
}
}
+ /// Anonymous analytics toggle (default: ON). Uses default-true semantics so existing installs
+ /// upgrading to a version that includes analytics do not silently default to OFF.
+ var shareAnonymousAnalytics: Bool {
+ get {
+ let value = self.defaults.object(forKey: Keys.shareAnonymousAnalytics)
+ if value == nil { return true }
+ return self.defaults.bool(forKey: Keys.shareAnonymousAnalytics)
+ }
+ set {
+ objectWillChange.send()
+ self.defaults.set(newValue, forKey: Keys.shareAnonymousAnalytics)
+ }
+ }
+
var availableModels: [String] {
get { (self.defaults.array(forKey: Keys.availableAIModels) as? [String]) ?? [] }
set {
diff --git a/Sources/Fluid/Services/CommandModeService.swift b/Sources/Fluid/Services/CommandModeService.swift
index 8dbf73f6..6746bc46 100644
--- a/Sources/Fluid/Services/CommandModeService.swift
+++ b/Sources/Fluid/Services/CommandModeService.swift
@@ -15,6 +15,7 @@ final class CommandModeService: ObservableObject {
private let chatStore = ChatHistoryStore.shared
private var currentTurnCount = 0
private let maxTurns = 20
+ private var didRequireConfirmationThisRun: Bool = false
// Flag to enable notch output display
var enableNotchOutput: Bool = true
@@ -300,6 +301,7 @@ final class CommandModeService: ObservableObject {
self.isProcessing = true
self.currentTurnCount = 0
+ self.didRequireConfirmationThisRun = false
self.conversationHistory.append(Message(role: .user, content: text))
// Auto-save after adding user message
@@ -326,6 +328,7 @@ final class CommandModeService: ObservableObject {
self.saveCurrentChat()
self.isProcessing = true
+ self.didRequireConfirmationThisRun = false
NotchContentState.shared.setCommandProcessing(true)
await self.processNextTurn()
@@ -368,6 +371,8 @@ final class CommandModeService: ObservableObject {
// Auto-save on completion
self.saveCurrentChat()
+ self.captureCommandRunCompleted(success: false)
+
// Push to notch
if self.enableNotchOutput {
NotchContentState.shared.addCommandMessage(role: .assistant, content: errorMsg)
@@ -416,6 +421,7 @@ final class CommandModeService: ObservableObject {
// Check if we need confirmation for destructive commands
if SettingsStore.shared.commandModeConfirmBeforeExecute, self.isDestructiveCommand(tc.command) {
+ self.didRequireConfirmationThisRun = true
self.pendingCommand = PendingCommand(
id: tc.id,
command: tc.command,
@@ -455,6 +461,8 @@ final class CommandModeService: ObservableObject {
// Auto-save on completion
self.saveCurrentChat()
+ self.captureCommandRunCompleted(success: isFinal)
+
// Push final response to notch and show expanded view
if self.enableNotchOutput {
NotchContentState.shared.updateCommandStreamingText("") // Clear streaming
@@ -477,6 +485,8 @@ final class CommandModeService: ObservableObject {
// Auto-save on error
self.saveCurrentChat()
+ self.captureCommandRunCompleted(success: false)
+
// Push error to notch
if self.enableNotchOutput {
NotchContentState.shared.addCommandMessage(role: .assistant, content: errorMsg)
@@ -486,6 +496,38 @@ final class CommandModeService: ObservableObject {
}
}
+ private func captureCommandRunCompleted(success: Bool) {
+ let toolCalls = self.conversationHistory.compactMap { $0.toolCall }.count
+ let turns = self.currentTurnCount
+
+ let turnsBucket: String
+ switch turns {
+ case ...1: turnsBucket = "1"
+ case 2...3: turnsBucket = "2-3"
+ case 4...7: turnsBucket = "4-7"
+ case 8...20: turnsBucket = "8-20"
+ default: turnsBucket = "20+"
+ }
+
+ let toolCallsBucket: String
+ switch toolCalls {
+ case 0: toolCallsBucket = "0"
+ case 1...2: toolCallsBucket = "1-2"
+ case 3...5: toolCallsBucket = "3-5"
+ default: toolCallsBucket = "6+"
+ }
+
+ AnalyticsService.shared.capture(
+ .commandModeRunCompleted,
+ properties: [
+ "success": success,
+ "turns_bucket": turnsBucket,
+ "tool_calls_bucket": toolCallsBucket,
+ "confirmation_needed": self.didRequireConfirmationThisRun,
+ ]
+ )
+ }
+
/// Show expanded notch output if there's content to display
private func showExpandedNotchIfNeeded() {
guard self.enableNotchOutput else { return }
diff --git a/Sources/Fluid/Services/MeetingTranscriptionService.swift b/Sources/Fluid/Services/MeetingTranscriptionService.swift
index a908a207..b37212fe 100644
--- a/Sources/Fluid/Services/MeetingTranscriptionService.swift
+++ b/Sources/Fluid/Services/MeetingTranscriptionService.swift
@@ -57,6 +57,26 @@ final class MeetingTranscriptionService: ObservableObject {
}
}
+ private func errorCategory(for error: Error) -> String {
+ guard let transcriptionError = error as? TranscriptionError else {
+ return "unknownError"
+ }
+ return self.errorCategory(for: transcriptionError)
+ }
+
+ private func errorCategory(for error: TranscriptionError) -> String {
+ switch error {
+ case .modelLoadFailed:
+ return "modelLoadFailed"
+ case .audioConversionFailed:
+ return "audioConversionFailed"
+ case .transcriptionFailed:
+ return "transcriptionFailed"
+ case .fileNotSupported:
+ return "fileNotSupported"
+ }
+ }
+
/// Initialize the ASR models (reuses models from ASRService - no duplicate download!)
func initializeModels() async throws {
guard !self.asrService.isAsrReady else { return }
@@ -142,6 +162,16 @@ final class MeetingTranscriptionService: ObservableObject {
fileName: fileURL.lastPathComponent
)
+ AnalyticsService.shared.capture(
+ .meetingTranscriptionCompleted,
+ properties: [
+ "success": true,
+ "file_type": fileURL.pathExtension.lowercased(),
+ "audio_duration_bucket": AnalyticsBuckets.bucketSeconds(duration),
+ "processing_time_bucket": AnalyticsBuckets.bucketSeconds(processingTime),
+ ]
+ )
+
self.result = result
return result
#else
@@ -151,10 +181,26 @@ final class MeetingTranscriptionService: ObservableObject {
} catch let error as TranscriptionError {
self.error = error.localizedDescription
+ AnalyticsService.shared.capture(
+ .meetingTranscriptionCompleted,
+ properties: [
+ "success": false,
+ "file_type": fileURL.pathExtension.lowercased(),
+ "category": errorCategory(for: error),
+ ]
+ )
throw error
} catch {
let wrappedError = TranscriptionError.transcriptionFailed(error.localizedDescription)
self.error = wrappedError.localizedDescription
+ AnalyticsService.shared.capture(
+ .meetingTranscriptionCompleted,
+ properties: [
+ "success": false,
+ "file_type": fileURL.pathExtension.lowercased(),
+ "category": self.errorCategory(for: wrappedError),
+ ]
+ )
throw wrappedError
}
}
diff --git a/Sources/Fluid/Services/RewriteModeService.swift b/Sources/Fluid/Services/RewriteModeService.swift
index 5eb0ae12..193334e2 100644
--- a/Sources/Fluid/Services/RewriteModeService.swift
+++ b/Sources/Fluid/Services/RewriteModeService.swift
@@ -53,6 +53,7 @@ final class RewriteModeService: ObservableObject {
}
func processRewriteRequest(_ prompt: String) async {
+ let startTime = Date()
// If no original text, we're in "Write Mode" - generate content based on user's request
if self.originalText.isEmpty {
self.originalText = prompt
@@ -90,9 +91,27 @@ final class RewriteModeService: ObservableObject {
self.conversationHistory.append(Message(role: .assistant, content: response))
self.rewrittenText = response
self.isProcessing = false
+
+ AnalyticsService.shared.capture(
+ .rewriteRunCompleted,
+ properties: [
+ "write_mode": self.isWriteMode,
+ "success": true,
+ "latency_bucket": AnalyticsBuckets.bucketSeconds(Date().timeIntervalSince(startTime)),
+ ]
+ )
} catch {
self.conversationHistory.append(Message(role: .assistant, content: "Error: \(error.localizedDescription)"))
self.isProcessing = false
+
+ AnalyticsService.shared.capture(
+ .rewriteRunCompleted,
+ properties: [
+ "write_mode": self.isWriteMode,
+ "success": false,
+ "latency_bucket": AnalyticsBuckets.bucketSeconds(Date().timeIntervalSince(startTime)),
+ ]
+ )
}
}
@@ -100,6 +119,14 @@ final class RewriteModeService: ObservableObject {
guard !self.rewrittenText.isEmpty else { return }
NSApp.hide(nil) // Restore focus to the previous app
self.typingService.typeTextInstantly(self.rewrittenText)
+
+ AnalyticsService.shared.capture(
+ .outputDelivered,
+ properties: [
+ "mode": AnalyticsMode.rewrite.rawValue,
+ "method": AnalyticsOutputMethod.typed.rawValue,
+ ]
+ )
}
func clearState() {
diff --git a/Sources/Fluid/UI/AnalyticsPrivacyView.swift b/Sources/Fluid/UI/AnalyticsPrivacyView.swift
new file mode 100644
index 00000000..63b2a86d
--- /dev/null
+++ b/Sources/Fluid/UI/AnalyticsPrivacyView.swift
@@ -0,0 +1,109 @@
+import SwiftUI
+
+struct AnalyticsPrivacyView: View {
+ @Environment(\.theme) private var theme
+ @Environment(\.dismiss) private var dismiss
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 14) {
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Anonymous Analytics")
+ .font(.system(size: 18, weight: .semibold))
+ Text("What FluidVoice collects when analytics is enabled")
+ .font(.system(size: 12))
+ .foregroundStyle(.secondary)
+ }
+
+ Spacer()
+
+ Button("Done") { self.dismiss() }
+ .buttonStyle(.bordered)
+ }
+
+ Divider().opacity(0.4)
+
+ self.contactInfoView
+
+ Divider().opacity(0.4)
+
+ ScrollView {
+ VStack(alignment: .leading, spacing: 14) {
+ self.sectionTitle("We collect")
+ self.bullet("Basic app/device info (app version, macOS version, etc.)")
+ self.bullet("Which features were used (for example: dictation, Command Mode etc.)")
+ self.bullet("Approximate ranges only (not exact values), such as duration or word count.")
+ self.bullet("Whether something worked and high-level error info.")
+
+ self.sectionTitle("We do NOT collect")
+ self.bullet("Any transcription text or audio.")
+ self.bullet("Selected text, rewrite prompts, or AI responses.")
+ self.bullet("Terminal commands or outputs from Command Mode.")
+ self.bullet("Window titles, app names, file names/paths, clipboard contents, or anything you type.")
+
+ self.sectionTitle("How it’s used")
+ self.bullet("To understand which features are being used and where reliability/performance can be improved.")
+ self.bullet("To measure product health (e.g., active devices, retention) without requiring accounts.")
+
+ self.sectionTitle("Control")
+ self.bullet("You can disable analytics anytime in Settings → Share Anonymous Analytics.")
+ }
+ .padding(.vertical, 6)
+ }
+ }
+ .padding(16)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ .background(self.theme.palette.cardBackground.opacity(0.2))
+ }
+
+ private var contactInfoView: some View {
+ Text(self.contactInfoText)
+ .font(.system(size: 13))
+ .foregroundStyle(.primary)
+ .padding(12)
+ .background(
+ RoundedRectangle(cornerRadius: 8)
+ .fill(.ultraThinMaterial)
+ )
+ .overlay(
+ RoundedRectangle(cornerRadius: 8)
+ .stroke(self.theme.palette.accent.opacity(0.3), lineWidth: 1)
+ )
+ }
+
+ private var contactInfoText: AttributedString {
+ var text = AttributedString(
+ "If you have any concerns we would love to hear about it, please email [email protected] or file an issue in our GitHub."
+ )
+
+ if let emailRange = text.range(of: "[email protected]") {
+ text[emailRange].link = URL(string: "mailto:[email protected]")
+ text[emailRange].foregroundColor = self.theme.palette.accent
+ }
+
+ if let githubRange = text.range(of: "GitHub") {
+ text[githubRange].link = URL(string: "https://github.com/altic-dev/FluidVoice")
+ text[githubRange].foregroundColor = self.theme.palette.accent
+ }
+
+ return text
+ }
+
+ private func sectionTitle(_ text: String) -> some View {
+ Text(text)
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(self.theme.palette.accent)
+ .padding(.top, 4)
+ }
+
+ private func bullet(_ text: String) -> some View {
+ HStack(alignment: .top, spacing: 8) {
+ Text("•")
+ .foregroundStyle(.secondary)
+ Text(text)
+ .font(.system(size: 13))
+ .foregroundStyle(.primary)
+ Spacer(minLength: 0)
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swift
index 61aedb2e..f82a77f7 100644
--- a/Sources/Fluid/UI/SettingsView.swift
+++ b/Sources/Fluid/UI/SettingsView.swift
@@ -39,6 +39,12 @@ struct SettingsView: View {
@State private var cachedDefaultInputName: String = ""
@State private var cachedDefaultOutputName: String = ""
+ // Analytics consent UI state (default ON; user can opt-out)
+ @State private var shareAnonymousAnalytics: Bool = SettingsStore.shared.shareAnonymousAnalytics
+ @State private var showAnalyticsPrivacy: Bool = false
+ @State private var pendingAnalyticsValue: Bool? = nil
+ @State private var showAreYouSureToStopAnalytics: Bool = false
+
let hotkeyManager: GlobalHotkeyManager?
let menuBarManager: MenuBarManager
let startRecording: () -> Void
@@ -48,6 +54,45 @@ struct SettingsView: View {
let revealAppInFinder: () -> Void
let openApplicationsFolder: () -> Void
+ private var analyticsToggleBinding: Binding<Bool> {
+ Binding(
+ get: {
+ self.pendingAnalyticsValue ?? self.shareAnonymousAnalytics
+ },
+ set: { newValue in
+ // User is trying to turn OFF → ask first
+ if self.shareAnonymousAnalytics == true, newValue == false {
+ self.pendingAnalyticsValue = false
+ self.showAreYouSureToStopAnalytics = true
+
+ return
+ }
+
+ // Normal ON path
+ self.shareAnonymousAnalytics = newValue
+ self.applyAnalyticsConsentChange(newValue)
+ }
+ )
+ }
+
+ private var analyticsConfirmationBinding: Binding<Bool> {
+ Binding(
+ get: { self.showAreYouSureToStopAnalytics },
+ set: { newValue in
+ // Only open modal if we have a pending value
+ if newValue {
+ if self.pendingAnalyticsValue != nil {
+ self.showAreYouSureToStopAnalytics = true
+ }
+ } else {
+ // Closing the modal: reset pending state
+ self.showAreYouSureToStopAnalytics = false
+ self.pendingAnalyticsValue = nil
+ }
+ }
+ )
+ }
+
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 16) {
@@ -378,6 +423,24 @@ struct SettingsView: View {
set: { SettingsStore.shared.saveTranscriptionHistory = $0 }
)
)
+
+ Divider().padding(.vertical, 8)
+
+ self.optionToggleRow(
+ title: "Share Anonymous Analytics",
+ description: "Send anonymous usage and performance metrics to help improve FluidVoice. Never includes transcription text or prompts.",
+ isOn: self.analyticsToggleBinding
+ )
+
+ HStack {
+ Button("What we collect") {
+ self.showAnalyticsPrivacy = true
+ }
+ .buttonStyle(.link)
+
+ Spacer()
+ }
+ .padding(.top, 6)
}
.padding(12)
.background(RoundedRectangle(cornerRadius: 8, style: .continuous)
@@ -702,6 +765,28 @@ struct SettingsView: View {
}
.padding(16)
}
+ .sheet(isPresented: self.$showAnalyticsPrivacy) {
+ AnalyticsPrivacyView()
+ .frame(minWidth: 520, minHeight: 520)
+ .appTheme(self.theme)
+ .preferredColorScheme(.dark)
+ }
+ .sheet(isPresented: self.analyticsConfirmationBinding) {
+ AnalyticsConfirmationView(
+ onConfirm: {
+ if let pending = pendingAnalyticsValue {
+ self.shareAnonymousAnalytics = pending
+ self.applyAnalyticsConsentChange(pending)
+ }
+ self.pendingAnalyticsValue = nil
+ self.showAreYouSureToStopAnalytics = false
+ },
+ onCancel: {
+ self.pendingAnalyticsValue = nil
+ self.showAreYouSureToStopAnalytics = false
+ }
+ )
+ }
.onAppear {
Task { @MainActor in
// Ensure the shared audio startup gate is scheduled. Safe to call repeatedly.
@@ -757,6 +842,12 @@ struct SettingsView: View {
}
}
+ private func applyAnalyticsConsentChange(_ enabled: Bool) {
+ SettingsStore.shared.shareAnonymousAnalytics = enabled
+ AnalyticsService.shared.setEnabled(enabled)
+ AnalyticsService.shared.capture(.analyticsConsentChanged, properties: ["enabled": enabled])
+ }
+
// MARK: - Helper Views
@ViewBuilder
@@ -1044,3 +1135,72 @@ struct FlowLayout: Layout {
return (CGSize(width: maxWidth, height: y + rowHeight), positions)
}
}
+
+// MARK: - Analytics modal confirmation
+
+struct AnalyticsConfirmationView: View {
+ let onConfirm: () -> Void
+ let onCancel: () -> Void
+ @Environment(\.theme) private var theme
+
+ private var contactInfoText: AttributedString {
+ var text = AttributedString(
+ "If you have any concerns we would love to hear about it, please email [email protected] or file an issue in our GitHub."
+ )
+
+ if let emailRange = text.range(of: "[email protected]") {
+ text[emailRange].link = URL(string: "mailto:[email protected]")
+ text[emailRange].foregroundColor = self.theme.palette.accent
+ }
+
+ if let githubRange = text.range(of: "GitHub") {
+ text[githubRange].link = URL(string: "https://github.com/altic-dev/FluidVoice")
+ text[githubRange].foregroundColor = self.theme.palette.accent
+ }
+
+ return text
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 16) {
+ Text("Are you sure you want to stop sharing anonymous analytics?")
+ .font(.headline)
+
+ Text("By sharing anonymous usage data, you help us build the features you care about most. We never collect personal information (Audio, Transcription text etc), ever. Your support simply helps us make FluidVoice better for you.")
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ .padding(12)
+ .background(
+ RoundedRectangle(cornerRadius: 8)
+ .fill(.ultraThinMaterial)
+ )
+ .overlay(
+ RoundedRectangle(cornerRadius: 8)
+ .stroke(self.theme.palette.accent.opacity(0.3), lineWidth: 1)
+ )
+
+ Text(self.contactInfoText)
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ .textSelection(.enabled)
+
+ Divider()
+
+ HStack {
+ Spacer()
+
+ Button("Cancel") {
+ self.onCancel()
+ }
+
+ Button("Yes") {
+ self.onConfirm()
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(.red)
+ }
+ }
+ .padding(20)
+ .frame(width: 420)
+ }
+}
diff --git a/scripts/format-and-lint.sh b/scripts/format-and-lint.sh
new file mode 100755
index 00000000..03e8e8ce
--- /dev/null
+++ b/scripts/format-and-lint.sh
@@ -0,0 +1,176 @@
+#!/bin/bash
+set -euo pipefail
+
+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+cd "$REPO_ROOT"
+
+if [ -t 1 ]; then
+ RED="$(tput setaf 1)"
+ YELLOW="$(tput setaf 3)"
+ GREEN="$(tput setaf 2)"
+ BLUE="$(tput setaf 4)"
+ BOLD="$(tput bold)"
+ RESET="$(tput sgr0)"
+else
+ RED=""; YELLOW=""; GREEN=""; BLUE=""; BOLD=""; RESET=""
+fi
+
+die() {
+ echo "${RED}${BOLD}Error:${RESET} $*" >&2
+ exit 1
+}
+
+ensure_brew() {
+ if ! command -v brew >/dev/null 2>&1; then
+ die "Homebrew is required to auto-install tools. Install from https://brew.sh/ or install the tools manually."
+ fi
+}
+
+ensure_tool() {
+ local tool="$1"
+ local brew_pkg="$2"
+
+ if command -v "$tool" >/dev/null 2>&1; then
+ return 0
+ fi
+
+ if [ "${FLUIDVOICE_NO_TOOL_INSTALL:-0}" = "1" ]; then
+ die "Missing dependency: '$tool' (auto-install disabled via FLUIDVOICE_NO_TOOL_INSTALL=1)."
+ fi
+
+ ensure_brew
+ echo "${BLUE}${BOLD}Installing${RESET} missing dependency: ${BOLD}${tool}${RESET} (brew install ${brew_pkg})"
+ brew install "$brew_pkg"
+
+ command -v "$tool" >/dev/null 2>&1 || die "Failed to install '$tool' (brew package: '$brew_pkg')."
+}
+
+ensure_tool swiftformat swiftformat
+ensure_tool swiftlint swiftlint
+
+echo "${BLUE}${BOLD}Running SwiftFormat...${RESET}"
+swiftformat --config .swiftformat Sources
+
+# If SwiftFormat changed files, print them (but continue on to SwiftLint).
+if command -v git >/dev/null 2>&1 && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
+ if git diff --name-only -- Sources | grep -q .; then
+ echo "${YELLOW}${BOLD}SwiftFormat updated files.${RESET} (Continuing to SwiftLint; remember to stage/commit if needed.)"
+ git diff --name-only -- Sources | sed 's/^/ - /'
+ fi
+fi
+
+echo "${BLUE}${BOLD}Running SwiftLint...${RESET}"
+tmpfile="$(mktemp -t fluidvoice-swiftlint.XXXXXX)"
+
+trap 'rm -f "$tmpfile"' EXIT
+
+set +e
+swiftlint --strict --config .swiftlint.yml >"$tmpfile" 2>&1
+swiftlint_exit=$?
+set -e
+
+if [ "$swiftlint_exit" -ne 0 ]; then
+ echo "${RED}${BOLD}SwiftLint failed.${RESET}"
+ echo
+
+ # Beautify SwiftLint output: group by file, show line + severity + message, include counts.
+ if command -v gawk >/dev/null 2>&1; then
+ AWK_BIN="gawk"
+ AWK_MODE="gawk"
+ elif command -v awk >/dev/null 2>&1; then
+ AWK_BIN="awk"
+ AWK_MODE="posix"
+ else
+ die "Missing dependency: neither 'gawk' nor 'awk' was found. Install GNU awk (recommended): 'brew install gawk'."
+ fi
+
+ if [ "$AWK_MODE" = "gawk" ]; then
+ "$AWK_BIN" -v RED="$RED" -v YELLOW="$YELLOW" -v BOLD="$BOLD" -v RESET="$RESET" '
+ BEGIN { current=""; errors=0; warnings=0; other=0 }
+ function print_header(file) {
+ current=file
+ print BOLD file RESET
+ }
+ {
+ # Typical SwiftLint line:
+ # path/to/File.swift:12:34: error: Message...
+ if (match($0, /^(.*):([0-9]+):([0-9]+): (warning|error): (.*)$/, a)) {
+ file=a[1]; line=a[2]; sev=a[4]; msg=a[5]
+ if (file != current) print_header(file)
+ if (sev == "error") { c=RED; errors++ } else { c=YELLOW; warnings++ }
+ printf(" L%s: %s%s%s: %s\n", line, c, sev, RESET, msg)
+ next
+ }
+
+ # Keep any other lines (tooling errors, config issues, etc.)
+ other++
+ if (current != "__misc__") { print_header("__misc__"); }
+ print " " $0
+ }
+ END {
+ print ""
+ summary = sprintf("Summary: %d error(s), %d warning(s)", errors, warnings)
+ if (other > 0) summary = summary sprintf(", %d other line(s)", other)
+ print BOLD summary RESET > "/dev/stderr"
+ }
+ ' "$tmpfile"
+ else
+ # POSIX/BSD awk compatible parser (macOS default awk doesn't support match(..., array)).
+ "$AWK_BIN" -v RED="$RED" -v YELLOW="$YELLOW" -v BOLD="$BOLD" -v RESET="$RESET" '
+ BEGIN { current=""; errors=0; warnings=0; other=0 }
+ function print_header(file) {
+ current=file
+ print BOLD file RESET
+ }
+ function rindex_char(s, ch, i) {
+ for (i=length(s); i>0; i--) if (substr(s, i, 1) == ch) return i
+ return 0
+ }
+ {
+ # Typical SwiftLint line:
+ # path/to/File.swift:12:34: error: Message...
+ # Extract by locating ": (warning|error): ", then splitting "file:line:col" from the end.
+ if (match($0, /: (warning|error): /)) {
+ marker = substr($0, RSTART, RLENGTH) # ": warning: " or ": error: "
+ sev = substr(marker, 3, RLENGTH-4) # strip leading/trailing ": "
+ msg = substr($0, RSTART + RLENGTH) # rest of line after the marker
+ prefix = substr($0, 1, RSTART-1) # "file:line:col"
+
+ last = rindex_char(prefix, ":")
+ if (last > 0) {
+ col = substr(prefix, last+1)
+ prefix2 = substr(prefix, 1, last-1)
+ second = rindex_char(prefix2, ":")
+ if (second > 0) {
+ line = substr(prefix2, second+1)
+ file = substr(prefix2, 1, second-1)
+
+ if (line ~ /^[0-9]+$/ && col ~ /^[0-9]+$/ && (sev == "warning" || sev == "error")) {
+ if (file != current) print_header(file)
+ if (sev == "error") { c=RED; errors++ } else { c=YELLOW; warnings++ }
+ printf(" L%s: %s%s%s: %s\n", line, c, sev, RESET, msg)
+ next
+ }
+ }
+ }
+ }
+
+ # Keep any other lines (tooling errors, config issues, etc.)
+ other++
+ if (current != "__misc__") { print_header("__misc__"); }
+ print " " $0
+ }
+ END {
+ print ""
+ summary = sprintf("Summary: %d error(s), %d warning(s)", errors, warnings)
+ if (other > 0) summary = summary sprintf(", %d other line(s)", other)
+ print BOLD summary RESET > "/dev/stderr"
+ }
+ ' "$tmpfile"
+ fi
+
+ exit "$swiftlint_exit"
+fi
+
+echo "${GREEN}${BOLD}OK${RESET} - formatting and linting passed."
+exit 0
\ No newline at end of file