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 analytics to measure latency

grohith3272efaa124fdc4
diff --git a/Sources/Fluid/Analytics/AnalyticsDatabase.swift b/Sources/Fluid/Analytics/AnalyticsDatabase.swift
index e9ba54a8..74240368 100644
--- a/Sources/Fluid/Analytics/AnalyticsDatabase.swift
+++ b/Sources/Fluid/Analytics/AnalyticsDatabase.swift
@@ -111,6 +111,72 @@ final class AnalyticsDatabase {
}
}
+ func recordInsertionLatency(
+ path: AnalyticsInsertionPath,
+ outcome: AnalyticsInsertionOutcome,
+ requestMilliseconds: Int,
+ readyMilliseconds: Int?,
+ toggleStopMilliseconds: Int? = nil,
+ at date: Date
+ ) throws {
+ try self.finalizeDays(before: date)
+ let requestMilliseconds = max(0, requestMilliseconds)
+ let readyMilliseconds = readyMilliseconds.map { max(0, $0) }
+ let readyCount = readyMilliseconds == nil ? 0 : 1
+ let readyValue = readyMilliseconds ?? 0
+ let day = self.dayString(date)
+
+ try self.transaction {
+ try self.run(
+ "INSERT INTO daily_insertion_latency (" +
+ "day, delivery_path, outcome, request_count, request_total_ms, request_min_ms, request_max_ms, " +
+ "ready_count, ready_total_ms, ready_min_ms, ready_max_ms" +
+ ") VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?) " +
+ "ON CONFLICT(day, delivery_path, outcome) DO UPDATE SET " +
+ "request_count = request_count + 1, " +
+ "request_total_ms = request_total_ms + excluded.request_total_ms, " +
+ "request_min_ms = MIN(request_min_ms, excluded.request_min_ms), " +
+ "request_max_ms = MAX(request_max_ms, excluded.request_max_ms), " +
+ "ready_count = ready_count + excluded.ready_count, " +
+ "ready_total_ms = ready_total_ms + excluded.ready_total_ms, " +
+ "ready_min_ms = CASE " +
+ "WHEN excluded.ready_count = 0 THEN ready_min_ms " +
+ "WHEN ready_count = 0 THEN excluded.ready_min_ms " +
+ "ELSE MIN(ready_min_ms, excluded.ready_min_ms) END, " +
+ "ready_max_ms = CASE " +
+ "WHEN excluded.ready_count = 0 THEN ready_max_ms " +
+ "WHEN ready_count = 0 THEN excluded.ready_max_ms " +
+ "ELSE MAX(ready_max_ms, excluded.ready_max_ms) END",
+ bindings: [
+ .text(day), .text(path.rawValue), .text(outcome.rawValue),
+ .integer(requestMilliseconds), .integer(requestMilliseconds), .integer(requestMilliseconds),
+ .integer(readyCount), .integer(readyValue), .integer(readyValue), .integer(readyValue),
+ ]
+ )
+
+ if let toggleStopMilliseconds,
+ outcome == .dispatched,
+ path == .clipboard || path == .clipboardFallback
+ {
+ let milliseconds = max(0, toggleStopMilliseconds)
+ try self.run(
+ "INSERT INTO daily_clipboard_toggle_latency " +
+ "(day, delivery_path, sample_count, total_ms, min_ms, max_ms) " +
+ "VALUES (?, ?, 1, ?, ?, ?) " +
+ "ON CONFLICT(day, delivery_path) DO UPDATE SET " +
+ "sample_count = sample_count + 1, " +
+ "total_ms = total_ms + excluded.total_ms, " +
+ "min_ms = MIN(min_ms, excluded.min_ms), " +
+ "max_ms = MAX(max_ms, excluded.max_ms)",
+ bindings: [
+ .text(day), .text(path.rawValue),
+ .integer(milliseconds), .integer(milliseconds), .integer(milliseconds),
+ ]
+ )
+ }
+ }
+ }
+
func recordOnboardingStarted(origin: AnalyticsOnboardingOrigin, at date: Date) throws {
try self.finalizeDays(before: date)
try self.transaction {
@@ -273,8 +339,20 @@ final class AnalyticsDatabase {
"WHERE day < ? ORDER BY day, role, mode, provider, model",
bindings: [.text(today)]
)
+ let insertionRows = try self.query(
+ "SELECT day, delivery_path, outcome, request_count, request_total_ms, request_min_ms, " +
+ "request_max_ms, ready_count, ready_total_ms, ready_min_ms, ready_max_ms " +
+ "FROM daily_insertion_latency WHERE day < ? ORDER BY day, delivery_path, outcome",
+ bindings: [.text(today)]
+ )
+ let clipboardToggleRows = try self.query(
+ "SELECT day, delivery_path, sample_count, total_ms, min_ms, max_ms " +
+ "FROM daily_clipboard_toggle_latency WHERE day < ? ORDER BY day, delivery_path",
+ bindings: [.text(today)]
+ )
- guard !usageRows.isEmpty || !modelRows.isEmpty else { return }
+ guard !usageRows.isEmpty || !modelRows.isEmpty || !insertionRows.isEmpty || !clipboardToggleRows.isEmpty
+ else { return }
try self.transaction {
for row in usageRows where row.count == 5 {
try self.enqueue(.usageDailySummary, at: date, properties: [
@@ -295,8 +373,49 @@ final class AnalyticsDatabase {
"use_count": Int(row[5]) ?? 0,
])
}
+ for row in insertionRows where row.count == 11 {
+ let requestCount = Int(row[3]) ?? 0
+ let requestTotal = Int(row[4]) ?? 0
+ let readyCount = Int(row[7]) ?? 0
+ let readyTotal = Int(row[8]) ?? 0
+ let toggleRow = clipboardToggleRows.first {
+ $0.count == 6 &&
+ row[2] == AnalyticsInsertionOutcome.dispatched.rawValue &&
+ $0[0] == row[0] &&
+ $0[1] == row[1]
+ }
+ var properties: [String: Any] = [
+ "latency_date": row[0],
+ "delivery_path": row[1],
+ "outcome": row[2],
+ "request_count": requestCount,
+ "request_total_ms": requestTotal,
+ "request_average_ms": Self.average(total: requestTotal, count: requestCount),
+ "request_min_ms": Int(row[5]) ?? 0,
+ "request_max_ms": Int(row[6]) ?? 0,
+ "ready_count": readyCount,
+ ]
+ if readyCount > 0 {
+ properties["ready_total_ms"] = readyTotal
+ properties["ready_average_ms"] = Self.average(total: readyTotal, count: readyCount)
+ properties["ready_min_ms"] = Int(row[9]) ?? 0
+ properties["ready_max_ms"] = Int(row[10]) ?? 0
+ }
+ if let toggleRow {
+ let count = Int(toggleRow[2]) ?? 0
+ let total = Int(toggleRow[3]) ?? 0
+ properties["toggle_stop_to_dispatch_count"] = count
+ properties["toggle_stop_to_dispatch_total_ms"] = total
+ properties["toggle_stop_to_dispatch_average_ms"] = Self.average(total: total, count: count)
+ properties["toggle_stop_to_dispatch_min_ms"] = Int(toggleRow[4]) ?? 0
+ properties["toggle_stop_to_dispatch_max_ms"] = Int(toggleRow[5]) ?? 0
+ }
+ try self.enqueue(.insertionLatencyDailySummary, at: date, properties: properties)
+ }
try self.run("DELETE FROM daily_usage WHERE day < ?", bindings: [.text(today)])
try self.run("DELETE FROM daily_model_usage WHERE day < ?", bindings: [.text(today)])
+ try self.run("DELETE FROM daily_insertion_latency WHERE day < ?", bindings: [.text(today)])
+ try self.run("DELETE FROM daily_clipboard_toggle_latency WHERE day < ?", bindings: [.text(today)])
}
}
@@ -364,6 +483,8 @@ final class AnalyticsDatabase {
try self.execute("DELETE FROM outbox")
try self.execute("DELETE FROM daily_usage")
try self.execute("DELETE FROM daily_model_usage")
+ try self.execute("DELETE FROM daily_insertion_latency")
+ try self.execute("DELETE FROM daily_clipboard_toggle_latency")
try self.execute("DELETE FROM event_dedupe")
try self.execute("DELETE FROM onboarding_flows")
try self.execute("DELETE FROM model_download_attempts")
@@ -398,6 +519,29 @@ final class AnalyticsDatabase {
use_count INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY(day, role, mode, provider, model)
);
+ CREATE TABLE IF NOT EXISTS daily_insertion_latency (
+ day TEXT NOT NULL,
+ delivery_path TEXT NOT NULL,
+ outcome TEXT NOT NULL,
+ request_count INTEGER NOT NULL DEFAULT 0,
+ request_total_ms INTEGER NOT NULL DEFAULT 0,
+ request_min_ms INTEGER NOT NULL DEFAULT 0,
+ request_max_ms INTEGER NOT NULL DEFAULT 0,
+ ready_count INTEGER NOT NULL DEFAULT 0,
+ ready_total_ms INTEGER NOT NULL DEFAULT 0,
+ ready_min_ms INTEGER NOT NULL DEFAULT 0,
+ ready_max_ms INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY(day, delivery_path, outcome)
+ );
+ CREATE TABLE IF NOT EXISTS daily_clipboard_toggle_latency (
+ day TEXT NOT NULL,
+ delivery_path TEXT NOT NULL,
+ sample_count INTEGER NOT NULL DEFAULT 0,
+ total_ms INTEGER NOT NULL DEFAULT 0,
+ min_ms INTEGER NOT NULL DEFAULT 0,
+ max_ms INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY(day, delivery_path)
+ );
CREATE TABLE IF NOT EXISTS event_dedupe (
dedupe_key TEXT PRIMARY KEY,
created_at REAL NOT NULL
@@ -526,6 +670,11 @@ final class AnalyticsDatabase {
return String(format: "%04d-%02d-%02d", components.year ?? 0, components.month ?? 0, components.day ?? 0)
}
+ private static func average(total: Int, count: Int) -> Double {
+ guard count > 0 else { return 0 }
+ return (Double(total) / Double(count) * 10).rounded() / 10
+ }
+
private func purgeDeletedPages() throws {
try self.execute("PRAGMA incremental_vacuum")
try self.execute("PRAGMA wal_checkpoint(TRUNCATE)")
diff --git a/Sources/Fluid/Analytics/AnalyticsEvent.swift b/Sources/Fluid/Analytics/AnalyticsEvent.swift
index 3e8e52ee..bbee4ec3 100644
--- a/Sources/Fluid/Analytics/AnalyticsEvent.swift
+++ b/Sources/Fluid/Analytics/AnalyticsEvent.swift
@@ -5,6 +5,7 @@ enum AnalyticsEvent: String {
case activeUser = "active_user"
case usageDailySummary = "usage_daily_summary"
case modelUsageDailySummary = "model_usage_daily_summary"
+ case insertionLatencyDailySummary = "insertion_latency_daily_summary"
case onboardingStarted = "onboarding_started"
case onboardingStepViewed = "onboarding_step_viewed"
case onboardingStepCompleted = "onboarding_step_completed"
@@ -30,6 +31,24 @@ enum AnalyticsModelRole: String {
case aiPostProcessing = "ai_post_processing"
}
+enum AnalyticsInsertionPath: String {
+ case clipboard
+ case direct
+ case clipboardFallback = "clipboard_fallback"
+ case notAttempted = "not_attempted"
+}
+
+enum AnalyticsInsertionOutcome: String {
+ case dispatched
+ case emptyText = "empty_text"
+ case accessibilityNotTrusted = "accessibility_not_trusted"
+ case clipboardSnapshotFailed = "clipboard_snapshot_failed"
+ case clipboardWriteFailed = "clipboard_write_failed"
+ case pasteCommandFailed = "paste_command_failed"
+ case targetUnavailable = "target_unavailable"
+ case targetRestoreFailed = "target_restore_failed"
+}
+
struct AnalyticsModelDescriptor: Equatable {
let provider: String
let model: String
diff --git a/Sources/Fluid/Analytics/AnalyticsService.swift b/Sources/Fluid/Analytics/AnalyticsService.swift
index a4282af7..dfaa28f2 100644
--- a/Sources/Fluid/Analytics/AnalyticsService.swift
+++ b/Sources/Fluid/Analytics/AnalyticsService.swift
@@ -60,6 +60,25 @@ final class AnalyticsService {
}
}
+ func recordInsertionLatency(
+ path: AnalyticsInsertionPath,
+ outcome: AnalyticsInsertionOutcome,
+ requestMilliseconds: Int,
+ readyMilliseconds: Int?,
+ toggleStopMilliseconds: Int?
+ ) {
+ self.submit { core, context in
+ await core.recordInsertionLatency(
+ path: path,
+ outcome: outcome,
+ requestMilliseconds: requestMilliseconds,
+ readyMilliseconds: readyMilliseconds,
+ toggleStopMilliseconds: toggleStopMilliseconds,
+ context: context
+ )
+ }
+ }
+
func recordOnboardingStarted(origin: AnalyticsOnboardingOrigin) {
self.submit { core, context in
await core.recordOnboardingStarted(origin: origin, context: context)
@@ -251,6 +270,26 @@ private actor AnalyticsCore {
}
}
+ func recordInsertionLatency(
+ path: AnalyticsInsertionPath,
+ outcome: AnalyticsInsertionOutcome,
+ requestMilliseconds: Int,
+ readyMilliseconds: Int?,
+ toggleStopMilliseconds: Int?,
+ context: AnalyticsContext
+ ) async {
+ await self.write(context: context) { database, date in
+ try database.recordInsertionLatency(
+ path: path,
+ outcome: outcome,
+ requestMilliseconds: requestMilliseconds,
+ readyMilliseconds: readyMilliseconds,
+ toggleStopMilliseconds: toggleStopMilliseconds,
+ at: date
+ )
+ }
+ }
+
func recordOnboardingStarted(origin: AnalyticsOnboardingOrigin, context: AnalyticsContext) async {
await self.write(context: context) { database, date in
try database.recordOnboardingStarted(origin: origin, at: date)
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 853dfefe..b9c88319 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -1635,6 +1635,7 @@ struct ContentView: View {
_ outputPlan: DictationLiteralOutputPlan,
targetPID: pid_t?,
textReadyAt: TimeInterval,
+ toggleStopRequestedAt: TimeInterval?,
preserveTranscriptOnClipboard: Bool
) async -> TypingService.DeliveryOutcome {
let sendsExistingDraft = outputPlan.plainText.isEmpty
@@ -1642,6 +1643,7 @@ struct ContentView: View {
outputPlan,
preferredTargetPID: targetPID,
textReadyAt: textReadyAt,
+ toggleStopRequestedAt: toggleStopRequestedAt,
postInsertionKey: self.settings.spokenSendKey,
requiredFocusTarget: self.recordingFocusTarget,
preserveTranscriptOnClipboard: preserveTranscriptOnClipboard
@@ -2090,7 +2092,10 @@ struct ContentView: View {
// MARK: - Stop and Process Transcription
- private func stopAndProcessTranscription(route: DictationOutputRoute = .normal) async {
+ private func stopAndProcessTranscription(
+ route: DictationOutputRoute = .normal,
+ toggleStopRequestedAt: TimeInterval? = nil
+ ) async {
DebugLogger.shared.debug("stopAndProcessTranscription called", source: "ContentView")
DebugLogger.shared.info("Output route selected: \(route.rawValue)", source: "ContentView")
self.appBench("stop_path_enter route=\(route.rawValue)")
@@ -2464,6 +2469,7 @@ struct ContentView: View {
finalOutputPlan,
targetPID: typingTarget.pid,
textReadyAt: finalTextReadyAt,
+ toggleStopRequestedAt: toggleStopRequestedAt,
preserveTranscriptOnClipboard: shouldCopyToClipboard
)
didTypeExternally = deliveryOutcome.didInsert
@@ -2478,6 +2484,7 @@ struct ContentView: View {
finalOutputPlan,
preferredTargetPID: typingTarget.pid,
textReadyAt: finalTextReadyAt,
+ toggleStopRequestedAt: toggleStopRequestedAt,
tracksDictionaryCorrections: true,
preserveTranscriptOnClipboard: shouldCopyToClipboard
)
@@ -3583,10 +3590,13 @@ struct ContentView: View {
)
self.beginDictationRecording(for: .primary, mode: .dictate)
},
- stopAndProcessCallback: {
+ stopAndProcessCallback: { toggleStopRequestedAt in
let route = self.currentDictationOutputRouteForHotkeyStop()
DebugLogger.shared.info("Hotkey stop callback using route: \(route.rawValue)", source: "ContentView")
- await self.stopAndProcessTranscription(route: route)
+ await self.stopAndProcessTranscription(
+ route: route,
+ toggleStopRequestedAt: toggleStopRequestedAt
+ )
},
promptModeCallback: {
DebugLogger.shared.info("Prompt mode triggered", source: "ContentView")
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 1c85d964..c61d8b53 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -4866,6 +4866,7 @@ final class ASRService: ObservableObject {
_ plan: DictationLiteralOutputPlan,
preferredTargetPID: pid_t?,
textReadyAt: TimeInterval? = nil,
+ toggleStopRequestedAt: TimeInterval? = nil,
tracksDictionaryCorrections: Bool = false,
preserveTranscriptOnClipboard: Bool = false
) async -> TextDeliveryResult {
@@ -4881,6 +4882,7 @@ final class ASRService: ObservableObject {
plan,
preferredTargetPID: preferredTargetPID,
textReadyAt: textReadyAt,
+ toggleStopRequestedAt: toggleStopRequestedAt,
tracksDictionaryCorrections: tracksDictionaryCorrections,
preserveTranscriptOnClipboard: preserveTranscriptOnClipboard
)
@@ -4900,6 +4902,7 @@ final class ASRService: ObservableObject {
_ plan: DictationLiteralOutputPlan,
preferredTargetPID: pid_t?,
textReadyAt: TimeInterval? = nil,
+ toggleStopRequestedAt: TimeInterval? = nil,
tracksDictionaryCorrections: Bool = false,
postInsertionKey: SettingsStore.SpokenSendKey? = nil,
requiredFocusTarget: TypingService.CapturedFocusTarget? = nil,
@@ -4918,6 +4921,7 @@ final class ASRService: ObservableObject {
plan,
preferredTargetPID: preferredTargetPID,
textReadyAt: textReadyAt,
+ toggleStopRequestedAt: toggleStopRequestedAt,
tracksDictionaryCorrections: tracksDictionaryCorrections,
postInsertionKey: postInsertionKey,
requiredFocusTarget: requiredFocusTarget,
diff --git a/Sources/Fluid/Services/GlobalHotkeyManager.swift b/Sources/Fluid/Services/GlobalHotkeyManager.swift
index a857f385..aa036c2c 100644
--- a/Sources/Fluid/Services/GlobalHotkeyManager.swift
+++ b/Sources/Fluid/Services/GlobalHotkeyManager.swift
@@ -242,7 +242,7 @@ final class GlobalHotkeyManager: NSObject {
private var rewriteModeShortcutEnabled: Bool
private var startRecordingCallback: (() async -> Void)?
private var dictationModeCallback: (() async -> Void)?
- private var stopAndProcessCallback: (() async -> Void)?
+ private var stopAndProcessCallback: ((TimeInterval?) async -> Void)?
private var promptModeCallback: (() async -> Void)?
private var promptSelectionCallback: ((SettingsStore.DictationPromptSelection) async -> Void)?
private var commandModeCallback: (() async -> Void)?
@@ -470,7 +470,7 @@ final class GlobalHotkeyManager: NSObject {
rewriteModeShortcutEnabled: Bool,
startRecordingCallback: (() async -> Void)? = nil,
dictationModeCallback: (() async -> Void)? = nil,
- stopAndProcessCallback: (() async -> Void)? = nil,
+ stopAndProcessCallback: ((TimeInterval?) async -> Void)? = nil,
promptModeCallback: (() async -> Void)? = nil,
promptSelectionCallback: ((SettingsStore.DictationPromptSelection) async -> Void)? = nil,
commandModeCallback: (() async -> Void)? = nil,
@@ -519,7 +519,7 @@ final class GlobalHotkeyManager: NSObject {
}
}
- func setStopAndProcessCallback(_ callback: @escaping () async -> Void) {
+ func setStopAndProcessCallback(_ callback: @escaping (TimeInterval?) async -> Void) {
self.stopAndProcessCallback = callback
}
@@ -761,7 +761,7 @@ final class GlobalHotkeyManager: NSObject {
source: "GlobalHotkeyManager"
)
if isSameMode {
- self.stopRecordingIfNeeded()
+ self.stopRecordingAfterToggle()
} else {
self.triggerDictationMode()
}
@@ -874,7 +874,7 @@ final class GlobalHotkeyManager: NSObject {
if self.asrService.isRunningOrStarting {
if self.isPromptModeRecordingProvider?() ?? false {
DebugLogger.shared.info("Prompt shortcut pressed in Prompt mode - stopping", source: "GlobalHotkeyManager")
- self.stopRecordingIfNeeded()
+ self.stopRecordingAfterToggle()
} else {
DebugLogger.shared.info("Prompt shortcut pressed while recording - switching mode", source: "GlobalHotkeyManager")
self.triggerPromptSelection(assignment.selection)
@@ -930,7 +930,7 @@ final class GlobalHotkeyManager: NSObject {
if self.asrService.isRunningOrStarting {
if self.isCommandRecordingProvider?() ?? false {
DebugLogger.shared.info("Command mode shortcut pressed in Command mode - stopping", source: "GlobalHotkeyManager")
- self.stopRecordingIfNeeded()
+ self.stopRecordingAfterToggle()
} else {
DebugLogger.shared.info("Command mode shortcut pressed while recording - switching mode", source: "GlobalHotkeyManager")
self.triggerCommandMode()
@@ -981,7 +981,7 @@ final class GlobalHotkeyManager: NSObject {
if self.asrService.isRunningOrStarting {
if self.isRewriteRecordingProvider?() ?? false {
DebugLogger.shared.info("Rewrite mode shortcut pressed in Edit mode - stopping", source: "GlobalHotkeyManager")
- self.stopRecordingIfNeeded()
+ self.stopRecordingAfterToggle()
} else {
DebugLogger.shared.info("Rewrite mode shortcut pressed while recording - switching mode", source: "GlobalHotkeyManager")
self.triggerRewriteMode()
@@ -1121,7 +1121,7 @@ final class GlobalHotkeyManager: NSObject {
if self.asrService.isRunningOrStarting {
if self.isCommandRecordingProvider?() ?? false {
DebugLogger.shared.info("Command mode modifier released (toggle, same mode) - stopping", source: "GlobalHotkeyManager")
- self.stopRecordingIfNeeded()
+ self.stopRecordingAfterToggle()
} else {
DebugLogger.shared.info("Command mode modifier released (toggle, switch mode) - switching", source: "GlobalHotkeyManager")
self.triggerCommandMode()
@@ -1153,7 +1153,7 @@ final class GlobalHotkeyManager: NSObject {
if self.asrService.isRunningOrStarting {
if self.isRewriteRecordingProvider?() ?? false {
DebugLogger.shared.info("Rewrite mode modifier released (toggle, same mode) - stopping", source: "GlobalHotkeyManager")
- self.stopRecordingIfNeeded()
+ self.stopRecordingAfterToggle()
} else {
DebugLogger.shared.info("Rewrite mode modifier released (toggle, switch mode) - switching", source: "GlobalHotkeyManager")
self.triggerRewriteMode()
@@ -1349,7 +1349,7 @@ final class GlobalHotkeyManager: NSObject {
source: "GlobalHotkeyManager"
)
if isSameMode {
- self.stopRecordingIfNeeded()
+ self.stopRecordingAfterToggle()
} else {
self.triggerDictationMode()
}
@@ -1588,7 +1588,7 @@ final class GlobalHotkeyManager: NSObject {
if self.asrService.isRunningOrStarting {
if self.isPromptModeRecordingProvider?() ?? false {
DebugLogger.shared.info("Prompt mode shortcut pressed in Prompt mode - stopping", source: "GlobalHotkeyManager")
- self.stopRecordingIfNeeded()
+ self.stopRecordingAfterToggle()
} else {
DebugLogger.shared.info("Prompt mode shortcut pressed while recording - switching mode", source: "GlobalHotkeyManager")
self.triggerPromptMode()
@@ -1635,7 +1635,7 @@ final class GlobalHotkeyManager: NSObject {
if self.asrService.isRunningOrStarting {
if self.isPromptModeRecordingProvider?() ?? false {
DebugLogger.shared.info("Prompt mode modifier released (toggle, same mode) - stopping", source: "GlobalHotkeyManager")
- self.stopRecordingIfNeeded()
+ self.stopRecordingAfterToggle()
} else {
DebugLogger.shared.info("Prompt mode modifier released (toggle, switch mode) - switching", source: "GlobalHotkeyManager")
self.triggerPromptMode()
@@ -1669,7 +1669,7 @@ final class GlobalHotkeyManager: NSObject {
if self.asrService.isRunningOrStarting {
if self.isPromptModeRecordingProvider?() ?? false {
DebugLogger.shared.info("Prompt shortcut modifier released (toggle, same mode) - stopping", source: "GlobalHotkeyManager")
- self.stopRecordingIfNeeded()
+ self.stopRecordingAfterToggle()
} else {
DebugLogger.shared.info("Prompt shortcut modifier released (toggle, switch mode) - switching", source: "GlobalHotkeyManager")
self.triggerPromptSelection(assignment.selection)
@@ -1909,6 +1909,7 @@ final class GlobalHotkeyManager: NSObject {
}
private func toggleRecording() {
+ let toggleStopRequestedAt = ProcessInfo.processInfo.systemUptime
Task { @MainActor [weak self] in
guard let self = self else { return }
@@ -1916,7 +1917,7 @@ final class GlobalHotkeyManager: NSObject {
guard self.canTriggerRecordingAction("toggle") else { return }
if self.asrService.isRunningOrStarting {
- await self.stopRecordingInternal()
+ await self.stopRecordingInternal(toggleStopRequestedAt: toggleStopRequestedAt)
} else {
// Use callback if available, otherwise fallback to direct start
if let callback = self.startRecordingCallback {
@@ -1946,7 +1947,11 @@ final class GlobalHotkeyManager: NSObject {
}
}
- private func stopRecordingIfNeeded() {
+ private func stopRecordingAfterToggle() {
+ self.stopRecordingIfNeeded(toggleStopRequestedAt: ProcessInfo.processInfo.systemUptime)
+ }
+
+ private func stopRecordingIfNeeded(toggleStopRequestedAt: TimeInterval? = nil) {
Task { @MainActor [weak self] in
guard let self = self else { return }
@@ -1963,12 +1968,12 @@ final class GlobalHotkeyManager: NSObject {
return
}
- await self.stopRecordingInternal()
+ await self.stopRecordingInternal(toggleStopRequestedAt: toggleStopRequestedAt)
}
}
@MainActor
- private func stopRecordingInternal() async {
+ private func stopRecordingInternal(toggleStopRequestedAt: TimeInterval? = nil) async {
if self.asrService.isStarting, self.asrService.isRunning == false {
DebugLogger.shared.debug("Cancelling pending audio capture start", source: "GlobalHotkeyManager")
await self.asrService.cancelPendingAudioCaptureStart(reason: "hotkey_released")
@@ -1987,7 +1992,7 @@ final class GlobalHotkeyManager: NSObject {
defer { isProcessingStop = false }
if let callback = stopAndProcessCallback {
- await callback()
+ await callback(toggleStopRequestedAt)
} else {
await self.asrService.stopWithoutTranscription()
}
diff --git a/Sources/Fluid/Services/PasteDeliveryCoordinator.swift b/Sources/Fluid/Services/PasteDeliveryCoordinator.swift
index 7880106d..6974955d 100644
--- a/Sources/Fluid/Services/PasteDeliveryCoordinator.swift
+++ b/Sources/Fluid/Services/PasteDeliveryCoordinator.swift
@@ -569,7 +569,8 @@ final class PasteDeliveryCoordinator {
func deliver(
_ text: String,
- preserveTranscriptOnClipboard: Bool
+ preserveTranscriptOnClipboard: Bool,
+ onCommandPosted: ((TimeInterval) -> Void)? = nil
) async -> TextDeliveryResult {
await self.acquireDeliverySlot()
defer { self.releaseDeliverySlot() }
@@ -603,6 +604,8 @@ final class PasteDeliveryCoordinator {
self.log("delivery_failed generation=\(generation) reason=paste_command_failed")
return .recoverableFailure(.pasteCommandFailed)
}
+ let commandPostedAt = ProcessInfo.processInfo.systemUptime
+ onCommandPosted?(commandPostedAt)
self.log(
"command_posted generation=\(generation) totalMs=\(Self.elapsedMs(since: startedAt))"
diff --git a/Sources/Fluid/Services/TypingService.swift b/Sources/Fluid/Services/TypingService.swift
index 01262a22..e0383b5a 100644
--- a/Sources/Fluid/Services/TypingService.swift
+++ b/Sources/Fluid/Services/TypingService.swift
@@ -415,12 +415,14 @@ final class TypingService {
_ text: String,
preferredTargetPID: pid_t?,
textReadyAt: TimeInterval?,
+ toggleStopRequestedAt: TimeInterval? = nil,
preserveTranscriptOnClipboard: Bool = false
) async -> TextDeliveryResult {
await self.typeOutputPlanInstantly(
.plain(text),
preferredTargetPID: preferredTargetPID,
textReadyAt: textReadyAt,
+ toggleStopRequestedAt: toggleStopRequestedAt,
preserveTranscriptOnClipboard: preserveTranscriptOnClipboard
)
}
@@ -430,6 +432,7 @@ final class TypingService {
_ plan: DictationLiteralOutputPlan,
preferredTargetPID: pid_t?,
textReadyAt: TimeInterval?,
+ toggleStopRequestedAt: TimeInterval? = nil,
tracksDictionaryCorrections: Bool = false,
preserveTranscriptOnClipboard: Bool = false
) async -> TextDeliveryResult {
@@ -446,7 +449,15 @@ final class TypingService {
guard !text.isEmpty else {
self.bench("request_return reason=empty_text")
self.log("[TypingService] ERROR: Empty text provided, aborting")
- return .recoverableFailure(.emptyText)
+ let result = TextDeliveryResult.recoverableFailure(.emptyText)
+ self.recordInsertionLatency(
+ path: .notAttempted,
+ result: result,
+ requestedAt: requestedAt,
+ textReadyAt: textReadyAt,
+ toggleStopRequestedAt: toggleStopRequestedAt
+ )
+ return result
}
// Check accessibility permissions first
@@ -454,34 +465,57 @@ final class TypingService {
self.bench("request_return reason=accessibility_not_trusted")
self.log("[TypingService] ERROR: Accessibility permissions required for text injection")
self.log("[TypingService] Current accessibility status: \(AXIsProcessTrusted())")
- return .recoverableFailure(.accessibilityNotTrusted)
+ let result = TextDeliveryResult.recoverableFailure(.accessibilityNotTrusted)
+ self.recordInsertionLatency(
+ path: .notAttempted,
+ result: result,
+ requestedAt: requestedAt,
+ textReadyAt: textReadyAt,
+ toggleStopRequestedAt: toggleStopRequestedAt
+ )
+ return result
}
let usesClipboard = mode == .reliablePaste ||
self.ghosttyTargetPID(preferredTargetPID: preferredTargetPID) != nil
let result: TextDeliveryResult
+ let deliveryPath: AnalyticsInsertionPath
+ var dispatchedAt: TimeInterval?
if usesClipboard {
+ deliveryPath = .clipboard
result = await PasteDeliveryCoordinator.shared.deliver(
text,
- preserveTranscriptOnClipboard: preserveTranscriptOnClipboard
+ preserveTranscriptOnClipboard: preserveTranscriptOnClipboard,
+ onCommandPosted: { dispatchedAt = $0 }
)
} else if await self.insertTextDirectlyOffMain(text, preferredTargetPID: preferredTargetPID) {
+ deliveryPath = .direct
if preserveTranscriptOnClipboard {
_ = ClipboardService.copyToClipboard(text)
}
result = .commandPosted
} else {
+ deliveryPath = .clipboardFallback
self.log("[TypingService] Direct insertion failed; using non-blocking clipboard fallback")
result = await PasteDeliveryCoordinator.shared.deliver(
text,
- preserveTranscriptOnClipboard: preserveTranscriptOnClipboard
+ preserveTranscriptOnClipboard: preserveTranscriptOnClipboard,
+ onCommandPosted: { dispatchedAt = $0 }
)
}
- let completedAt = ProcessInfo.processInfo.systemUptime
+ let completedAt = dispatchedAt ?? ProcessInfo.processInfo.systemUptime
self.bench(
"complete result=\(String(describing: result)) totalMs=\(Self.elapsedMs(from: requestedAt, to: completedAt)) textReadyToCompleteMs=\(textReadyAt.map { String(Self.elapsedMs(from: $0, to: completedAt)) } ?? "nil")"
)
+ self.recordInsertionLatency(
+ path: deliveryPath,
+ result: result,
+ requestedAt: requestedAt,
+ textReadyAt: textReadyAt,
+ toggleStopRequestedAt: toggleStopRequestedAt,
+ completedAt: completedAt
+ )
if result.wasDispatched, tracksDictionaryCorrections {
AutomaticDictionaryCorrectionTracker.shared.beginObservingInsertion(
text,
@@ -495,6 +529,7 @@ final class TypingService {
_ plan: DictationLiteralOutputPlan,
preferredTargetPID: pid_t?,
textReadyAt: TimeInterval?,
+ toggleStopRequestedAt: TimeInterval? = nil,
tracksDictionaryCorrections: Bool = false,
postInsertionKey: SettingsStore.SpokenSendKey? = nil,
requiredFocusTarget: CapturedFocusTarget? = nil,
@@ -528,6 +563,7 @@ final class TypingService {
plan,
preferredTargetPID: preferredTargetPID,
textReadyAt: textReadyAt,
+ toggleStopRequestedAt: toggleStopRequestedAt,
tracksDictionaryCorrections: tracksDictionaryCorrections,
preserveTranscriptOnClipboard: preserveTranscriptOnClipboard
)
@@ -574,6 +610,47 @@ final class TypingService {
DebugLogger.shared.benchmark("TYPING_BENCH", message: message, source: "TypingBenchmark")
}
+ private func recordInsertionLatency(
+ path: AnalyticsInsertionPath,
+ result: TextDeliveryResult,
+ requestedAt: TimeInterval,
+ textReadyAt: TimeInterval?,
+ toggleStopRequestedAt: TimeInterval?,
+ completedAt: TimeInterval = ProcessInfo.processInfo.systemUptime
+ ) {
+ let outcome = Self.analyticsOutcome(for: result)
+ let isClipboardDispatch = outcome == .dispatched &&
+ (path == .clipboard || path == .clipboardFallback)
+ AnalyticsService.shared.recordInsertionLatency(
+ path: path,
+ outcome: outcome,
+ requestMilliseconds: max(0, Self.elapsedMs(from: requestedAt, to: completedAt)),
+ readyMilliseconds: textReadyAt.map {
+ max(0, Self.elapsedMs(from: $0, to: completedAt))
+ },
+ toggleStopMilliseconds: isClipboardDispatch ? toggleStopRequestedAt.map {
+ max(0, Self.elapsedMs(from: $0, to: completedAt))
+ } : nil
+ )
+ }
+
+ private static func analyticsOutcome(for result: TextDeliveryResult) -> AnalyticsInsertionOutcome {
+ switch result {
+ case .commandPosted:
+ .dispatched
+ case let .recoverableFailure(failure):
+ switch failure {
+ case .emptyText: .emptyText
+ case .accessibilityNotTrusted: .accessibilityNotTrusted
+ case .clipboardSnapshotFailed: .clipboardSnapshotFailed
+ case .clipboardWriteFailed: .clipboardWriteFailed
+ case .pasteCommandFailed: .pasteCommandFailed
+ case .targetUnavailable: .targetUnavailable
+ case .targetRestoreFailed: .targetRestoreFailed
+ }
+ }
+ }
+
private static func elapsedMs(since start: TimeInterval) -> Int {
Int(((ProcessInfo.processInfo.systemUptime - start) * 1000).rounded())
}
diff --git a/Sources/Fluid/UI/AnalyticsPrivacyView.swift b/Sources/Fluid/UI/AnalyticsPrivacyView.swift
index 08dad9dc..6414983c 100644
--- a/Sources/Fluid/UI/AnalyticsPrivacyView.swift
+++ b/Sources/Fluid/UI/AnalyticsPrivacyView.swift
@@ -36,16 +36,17 @@ struct AnalyticsPrivacyView: View {
self.bullet("Onboarding steps viewed and completed, including skips.")
self.bullet("Transcription and AI provider/model identifiers, counted as daily totals.")
self.bullet("Model download source, outcome, and download duration.")
+ self.bullet("Daily aggregated insertion timing statistics—including toggle-stop-to-paste-dispatch—split by delivery path and outcome.")
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.bullet("Hardware identifiers, CPU/chip details, performance timings, or individual transcription events.")
+ self.bullet("Hardware identifiers, CPU/chip details, target-app identity, or individual insertion timings/events.")
self.sectionTitle("How it’s used")
- self.bullet("To understand feature adoption, onboarding completion, model usage, active installations, and retention without requiring accounts.")
+ self.bullet("To understand feature adoption, insertion performance, onboarding completion, model usage, active installations, and retention without requiring accounts.")
self.sectionTitle("Control")
self.bullet("You can disable analytics anytime in Settings → Share Anonymous Analytics.")
diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swift
index 80e0d233..45535153 100644
--- a/Sources/Fluid/UI/SettingsView.swift
+++ b/Sources/Fluid/UI/SettingsView.swift
@@ -943,7 +943,7 @@ struct SettingsView: View {
self.optionToggleRow(
title: "Share Anonymous Analytics",
- description: "Send lean, anonymous daily usage, onboarding, retention, and model metrics. Never includes transcription text or prompts.",
+ description: "Send lean, anonymous daily usage, insertion performance, onboarding, retention, and model metrics. Never includes transcription text or prompts.",
isOn: self.analyticsToggleBinding
)
diff --git a/Tests/FluidDictationIntegrationTests/AnalyticsDatabaseTests.swift b/Tests/FluidDictationIntegrationTests/AnalyticsDatabaseTests.swift
index 2ad73ef3..fd04fbf2 100644
--- a/Tests/FluidDictationIntegrationTests/AnalyticsDatabaseTests.swift
+++ b/Tests/FluidDictationIntegrationTests/AnalyticsDatabaseTests.swift
@@ -40,6 +40,235 @@ final class AnalyticsDatabaseTests: XCTestCase {
XCTAssertEqual(model.properties["use_count"] as? Int, 2)
}
+ func testInsertionLatencyIsAggregatedUntilTheDayIsFinalized() throws {
+ let database = try self.makeDatabase()
+ let firstDay = Date(timeIntervalSince1970: 1_735_689_600) // 2025-01-01 UTC
+ let secondDay = firstDay.addingTimeInterval(24 * 60 * 60)
+
+ try database.recordInsertionLatency(
+ path: .direct,
+ outcome: .dispatched,
+ requestMilliseconds: 10,
+ readyMilliseconds: 40,
+ at: firstDay
+ )
+ try database.recordInsertionLatency(
+ path: .direct,
+ outcome: .dispatched,
+ requestMilliseconds: 20,
+ readyMilliseconds: nil,
+ at: firstDay.addingTimeInterval(60)
+ )
+ try database.recordInsertionLatency(
+ path: .direct,
+ outcome: .dispatched,
+ requestMilliseconds: 35,
+ readyMilliseconds: 70,
+ at: firstDay.addingTimeInterval(120)
+ )
+
+ XCTAssertTrue(try self.events(in: database).isEmpty)
+
+ try database.finalizeDays(before: secondDay)
+ let summary = try XCTUnwrap(
+ try self.events(in: database).first {
+ $0.name == AnalyticsEvent.insertionLatencyDailySummary.rawValue
+ }
+ )
+ XCTAssertEqual(summary.properties["latency_date"] as? String, "2025-01-01")
+ XCTAssertEqual(summary.properties["delivery_path"] as? String, "direct")
+ XCTAssertEqual(summary.properties["outcome"] as? String, "dispatched")
+ XCTAssertEqual(summary.properties["request_count"] as? Int, 3)
+ XCTAssertEqual(summary.properties["request_total_ms"] as? Int, 65)
+ XCTAssertEqual(summary.properties["request_average_ms"] as? Double, 21.7)
+ XCTAssertEqual(summary.properties["request_min_ms"] as? Int, 10)
+ XCTAssertEqual(summary.properties["request_max_ms"] as? Int, 35)
+ XCTAssertEqual(summary.properties["ready_count"] as? Int, 2)
+ XCTAssertEqual(summary.properties["ready_total_ms"] as? Int, 110)
+ XCTAssertEqual(summary.properties["ready_average_ms"] as? Double, 55)
+ XCTAssertEqual(summary.properties["ready_min_ms"] as? Int, 40)
+ XCTAssertEqual(summary.properties["ready_max_ms"] as? Int, 70)
+
+ try database.finalizeDays(before: secondDay.addingTimeInterval(60))
+ let summaries = try self.events(in: database).filter {
+ $0.name == AnalyticsEvent.insertionLatencyDailySummary.rawValue
+ }
+ XCTAssertEqual(summaries.count, 1)
+ }
+
+ func testInsertionLatencySeparatesPathsAndOutcomes() throws {
+ let database = try self.makeDatabase()
+ let firstDay = Date(timeIntervalSince1970: 1_735_689_600)
+ let secondDay = firstDay.addingTimeInterval(24 * 60 * 60)
+
+ try database.recordInsertionLatency(
+ path: .clipboard,
+ outcome: .dispatched,
+ requestMilliseconds: 5,
+ readyMilliseconds: nil,
+ at: firstDay
+ )
+ try database.recordInsertionLatency(
+ path: .clipboardFallback,
+ outcome: .pasteCommandFailed,
+ requestMilliseconds: 12,
+ readyMilliseconds: nil,
+ at: firstDay
+ )
+ try database.recordInsertionLatency(
+ path: .notAttempted,
+ outcome: .accessibilityNotTrusted,
+ requestMilliseconds: -4,
+ readyMilliseconds: nil,
+ at: firstDay
+ )
+ try database.finalizeDays(before: secondDay)
+
+ let summaries = try self.events(in: database).filter {
+ $0.name == AnalyticsEvent.insertionLatencyDailySummary.rawValue
+ }
+ XCTAssertEqual(summaries.count, 3)
+ XCTAssertTrue(summaries.contains {
+ $0.properties["delivery_path"] as? String == "clipboard" &&
+ $0.properties["outcome"] as? String == "dispatched"
+ })
+ XCTAssertTrue(summaries.contains {
+ $0.properties["delivery_path"] as? String == "clipboard_fallback" &&
+ $0.properties["outcome"] as? String == "paste_command_failed"
+ })
+ let rejected = try XCTUnwrap(summaries.first {
+ $0.properties["delivery_path"] as? String == "not_attempted"
+ })
+ XCTAssertEqual(rejected.properties["request_min_ms"] as? Int, 0)
+ XCTAssertEqual(rejected.properties["ready_count"] as? Int, 0)
+ XCTAssertNil(rejected.properties["ready_total_ms"])
+ XCTAssertNil(rejected.properties["ready_average_ms"])
+ XCTAssertNil(rejected.properties["ready_min_ms"])
+ XCTAssertNil(rejected.properties["ready_max_ms"])
+ }
+
+ func testClipboardToggleLatencyAggregatesOnlySuccessfulClipboardDispatches() throws {
+ let database = try self.makeDatabase()
+ let firstDay = Date(timeIntervalSince1970: 1_735_689_600)
+ let secondDay = firstDay.addingTimeInterval(24 * 60 * 60)
+
+ try database.recordInsertionLatency(
+ path: .clipboard,
+ outcome: .dispatched,
+ requestMilliseconds: 4,
+ readyMilliseconds: 12,
+ toggleStopMilliseconds: 100,
+ at: firstDay
+ )
+ try database.recordInsertionLatency(
+ path: .clipboard,
+ outcome: .dispatched,
+ requestMilliseconds: 5,
+ readyMilliseconds: 15,
+ toggleStopMilliseconds: 250,
+ at: firstDay
+ )
+ try database.recordInsertionLatency(
+ path: .clipboardFallback,
+ outcome: .dispatched,
+ requestMilliseconds: 7,
+ readyMilliseconds: 18,
+ toggleStopMilliseconds: 400,
+ at: firstDay
+ )
+ try database.recordInsertionLatency(
+ path: .direct,
+ outcome: .dispatched,
+ requestMilliseconds: 3,
+ readyMilliseconds: 10,
+ toggleStopMilliseconds: 500,
+ at: firstDay
+ )
+ try database.recordInsertionLatency(
+ path: .clipboard,
+ outcome: .pasteCommandFailed,
+ requestMilliseconds: 6,
+ readyMilliseconds: 20,
+ toggleStopMilliseconds: 600,
+ at: firstDay
+ )
+
+ XCTAssertTrue(try self.events(in: database).isEmpty)
+ try database.finalizeDays(before: secondDay)
+
+ let summaries = try self.events(in: database).filter {
+ $0.name == AnalyticsEvent.insertionLatencyDailySummary.rawValue &&
+ $0.properties["outcome"] as? String == "dispatched" &&
+ $0.properties["toggle_stop_to_dispatch_count"] != nil
+ }
+ XCTAssertEqual(summaries.count, 2)
+ let clipboard = try XCTUnwrap(summaries.first {
+ $0.properties["delivery_path"] as? String == "clipboard"
+ })
+ XCTAssertEqual(clipboard.properties["outcome"] as? String, "dispatched")
+ XCTAssertEqual(clipboard.properties["toggle_stop_to_dispatch_count"] as? Int, 2)
+ XCTAssertEqual(clipboard.properties["toggle_stop_to_dispatch_total_ms"] as? Int, 350)
+ XCTAssertEqual(clipboard.properties["toggle_stop_to_dispatch_average_ms"] as? Double, 175)
+ XCTAssertEqual(clipboard.properties["toggle_stop_to_dispatch_min_ms"] as? Int, 100)
+ XCTAssertEqual(clipboard.properties["toggle_stop_to_dispatch_max_ms"] as? Int, 250)
+
+ let fallback = try XCTUnwrap(summaries.first {
+ $0.properties["delivery_path"] as? String == "clipboard_fallback"
+ })
+ XCTAssertEqual(fallback.properties["toggle_stop_to_dispatch_count"] as? Int, 1)
+ XCTAssertEqual(fallback.properties["toggle_stop_to_dispatch_average_ms"] as? Double, 400)
+
+ let failedClipboard = try XCTUnwrap(try self.events(in: database).first {
+ $0.name == AnalyticsEvent.insertionLatencyDailySummary.rawValue &&
+ $0.properties["delivery_path"] as? String == "clipboard" &&
+ $0.properties["outcome"] as? String == "paste_command_failed"
+ })
+ XCTAssertNil(failedClipboard.properties["toggle_stop_to_dispatch_count"])
+ }
+
+ func testInsertionLatencySurvivesReopeningAndIsPurgedOnOptOut() throws {
+ let databaseURL = self.temporaryDirectory.appendingPathComponent("analytics.sqlite3")
+ let firstDay = Date(timeIntervalSince1970: 1_735_689_600)
+ let secondDay = firstDay.addingTimeInterval(24 * 60 * 60)
+
+ do {
+ let database = try self.makeDatabase(url: databaseURL)
+ try database.recordInsertionLatency(
+ path: .clipboard,
+ outcome: .dispatched,
+ requestMilliseconds: 8,
+ readyMilliseconds: 18,
+ toggleStopMilliseconds: 28,
+ at: firstDay
+ )
+ }
+
+ do {
+ let reopened = try self.makeDatabase(url: databaseURL)
+ try reopened.finalizeDays(before: secondDay)
+ let summaries = try self.events(in: reopened).filter {
+ $0.name == AnalyticsEvent.insertionLatencyDailySummary.rawValue
+ }
+ XCTAssertEqual(summaries.count, 1)
+ XCTAssertEqual(summaries.first?.properties["toggle_stop_to_dispatch_count"] as? Int, 1)
+ XCTAssertEqual(summaries.first?.properties["toggle_stop_to_dispatch_average_ms"] as? Double, 28)
+ }
+
+ let reopened = try self.makeDatabase(url: databaseURL)
+ try reopened.recordInsertionLatency(
+ path: .clipboard,
+ outcome: .dispatched,
+ requestMilliseconds: 4,
+ readyMilliseconds: nil,
+ toggleStopMilliseconds: 12,
+ at: secondDay
+ )
+ try reopened.purgeAll()
+ XCTAssertTrue(try self.events(in: reopened).isEmpty)
+ try reopened.finalizeDays(before: secondDay.addingTimeInterval(24 * 60 * 60))
+ XCTAssertTrue(try self.events(in: reopened).isEmpty)
+ }
+
func testAcknowledgementPurgesOutboxAndTruncatesWAL() throws {
let databaseURL = self.temporaryDirectory.appendingPathComponent("analytics.sqlite3")
let database = try self.makeDatabase(url: databaseURL)