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
Reduce dictation latency and add pipeline evaluation (#950)
ALTIC42e33e68ec47
diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxprojindex bf48a9fb..8bf0e82f 100644--- a/Fluid.xcodeproj/project.pbxproj+++ b/Fluid.xcodeproj/project.pbxproj@@ -33,6 +33,7 @@B51800000000000000000002 /* SpokenSendTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B51800000000000000000001 /* SpokenSendTests.swift */; };B51900000000000000000002 /* PrivateAIProviderPromptFormatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B51900000000000000000001 /* PrivateAIProviderPromptFormatTests.swift */; };C0DE63700000000000000002 /* WhisperLanguageSelectionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE63700000000000000001 /* WhisperLanguageSelectionTests.swift */; };+ CACEC0010000000000000002 /* KeychainServiceCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CACEC0010000000000000001 /* KeychainServiceCacheTests.swift */; };7CDB0A2F2F3C4D5600FB7CAD /* dictation_fixture.wav in Resources */ = {isa = PBXBuildFile; fileRef = 7CDB0A2B2F3C4D5600FB7CAD /* dictation_fixture.wav */; };7CDB0A302F3C4D5600FB7CAD /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7CDB0A2C2F3C4D5600FB7CAD /* XCTest.framework */; };7CE006BD2E80EBE600DDCCD6 /* AppUpdater in Frameworks */ = {isa = PBXBuildFile; productRef = 7CE006BC2E80EBE600DDCCD6 /* AppUpdater */; };@@ -76,6 +77,7 @@B51900000000000000000001 /* PrivateAIProviderPromptFormatTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrivateAIProviderPromptFormatTests.swift; sourceTree = "<group>"; };B52000000000000000000001 /* PrivateAIDictationTokenBudgetTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrivateAIDictationTokenBudgetTests.swift; sourceTree = "<group>"; };C0DE63700000000000000001 /* WhisperLanguageSelectionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WhisperLanguageSelectionTests.swift; sourceTree = "<group>"; };+ CACEC0010000000000000001 /* KeychainServiceCacheTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeychainServiceCacheTests.swift; sourceTree = "<group>"; };7C078D8F2E3B339200FB7CAC /* FluidVoice Debug.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "FluidVoice Debug.app"; sourceTree = BUILT_PRODUCTS_DIR; };7C91B0022F42AA0100C0DEF0 /* HotkeyShortcutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HotkeyShortcutTests.swift; sourceTree = "<group>"; };C0DE89000000000000000001 /* SettingsNavigationStateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsNavigationStateTests.swift; sourceTree = "<group>"; };@@ -172,6 +174,7 @@B51900000000000000000001 /* PrivateAIProviderPromptFormatTests.swift */,B52000000000000000000001 /* PrivateAIDictationTokenBudgetTests.swift */,C0DE63700000000000000001 /* WhisperLanguageSelectionTests.swift */,+ CACEC0010000000000000001 /* KeychainServiceCacheTests.swift */,0B05F11E000000000000A001 /* SupportedFileExtensionsTests.swift */,);path = FluidDictationIntegrationTests;@@ -347,6 +350,7 @@B51800000000000000000002 /* SpokenSendTests.swift in Sources */,B51900000000000000000002 /* PrivateAIProviderPromptFormatTests.swift in Sources */,C0DE63700000000000000002 /* WhisperLanguageSelectionTests.swift in Sources */,+ CACEC0010000000000000002 /* KeychainServiceCacheTests.swift in Sources */,0B05F11E000000000000A002 /* SupportedFileExtensionsTests.swift in Sources */,);runOnlyForDeploymentPostprocessing = 0;diff --git a/Sources/Fluid/Analytics/AnalyticsDatabase.swift b/Sources/Fluid/Analytics/AnalyticsDatabase.swiftindex 77b38404..fe17f133 100644--- a/Sources/Fluid/Analytics/AnalyticsDatabase.swift+++ b/Sources/Fluid/Analytics/AnalyticsDatabase.swift@@ -14,6 +14,11 @@ enum AnalyticsDatabaseError: Error {/// SQLite aggregates and crash-safe upload outbox.final class AnalyticsDatabase {+ private static let performanceBucketUpperBounds = [+ 25, 50, 75, 100, 150, 200, 300, 500, 750, 1000,+ 1500, 2000, 3000, 5000, 7500, 10_000, 20_000, 60_000,+ ]+private let connection: OpaquePointerprivate let distinctID: Stringprivate let appVersion: String@@ -119,6 +124,35 @@ final class AnalyticsDatabase {}}+ func recordDictationPerformance(+ asrMilliseconds: Int?,+ fluidIntelligenceMilliseconds: Int?,+ measuredAppVersion: String,+ at date: Date+ ) throws {+ guard asrMilliseconds != nil || fluidIntelligenceMilliseconds != nil else { return }+ try self.finalizeDays(before: date)+ let day = self.dayString(date)+ try self.transaction {+ if let asrMilliseconds {+ try self.upsertPerformanceMetric(+ day: day,+ measuredAppVersion: measuredAppVersion,+ metric: "asr",+ milliseconds: asrMilliseconds+ )+ }+ if let fluidIntelligenceMilliseconds {+ try self.upsertPerformanceMetric(+ day: day,+ measuredAppVersion: measuredAppVersion,+ metric: "fluid_intelligence",+ milliseconds: fluidIntelligenceMilliseconds+ )+ }+ }+ }+func recordOnboardingStarted(origin: AnalyticsOnboardingOrigin, at date: Date) throws {try self.finalizeDays(before: date)try self.transaction {@@ -370,8 +404,14 @@ final class AnalyticsDatabase {"WHERE day < ? ORDER BY day, role, mode, provider, model",bindings: [.text(today)])+ let performanceRows = try self.query(+ "SELECT day, measured_app_version, measured_os_version, metric, bucket_index, sample_count " ++ "FROM daily_dictation_performance WHERE day < ? " ++ "ORDER BY day, measured_app_version, measured_os_version, metric, bucket_index",+ bindings: [.text(today)]+ )- guard !usageRows.isEmpty || !modelRows.isEmpty else { return }+ guard !usageRows.isEmpty || !modelRows.isEmpty || !performanceRows.isEmpty else { return }try self.transaction {for row in usageRows where row.count == 5 {try self.enqueue(.usageDailySummary, at: date, properties: [@@ -392,8 +432,12 @@ final class AnalyticsDatabase {"use_count": Int(row[5]) ?? 0,])}+ for summary in self.performanceSummaries(from: performanceRows) {+ try self.enqueue(.dictationPerformanceDailySummary, at: date, properties: summary.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_dictation_performance WHERE day < ?", bindings: [.text(today)])}}@@ -473,6 +517,7 @@ 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_dictation_performance")try self.execute("DELETE FROM event_dedupe")try self.execute("DELETE FROM onboarding_flows")try self.execute("DELETE FROM onboarding_tryout_state")@@ -485,8 +530,11 @@ final class AnalyticsDatabase {func purgeDetailedAnalytics() throws {try self.transaction {try self.run(- "DELETE FROM outbox WHERE event_name != ?",- bindings: [.text(AnalyticsEvent.activeUser.rawValue)]+ "DELETE FROM outbox WHERE event_name != ? AND event_name != ?",+ bindings: [+ .text(AnalyticsEvent.activeUser.rawValue),+ .text(AnalyticsEvent.dictationPerformanceDailySummary.rawValue),+ ])try self.execute("DELETE FROM daily_usage")try self.execute("DELETE FROM daily_model_usage")@@ -527,6 +575,15 @@ final class AnalyticsDatabase {use_count INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(day, role, mode, provider, model));+ CREATE TABLE IF NOT EXISTS daily_dictation_performance (+ day TEXT NOT NULL,+ measured_app_version TEXT NOT NULL,+ measured_os_version TEXT NOT NULL,+ metric TEXT NOT NULL,+ bucket_index INTEGER NOT NULL,+ sample_count INTEGER NOT NULL DEFAULT 0,+ PRIMARY KEY(day, measured_app_version, measured_os_version, metric, bucket_index)+ );CREATE TABLE IF NOT EXISTS event_dedupe (dedupe_key TEXT PRIMARY KEY,created_at REAL NOT NULL@@ -627,6 +684,123 @@ final class AnalyticsDatabase {)}+ private func upsertPerformanceMetric(+ day: String,+ measuredAppVersion: String,+ metric: String,+ milliseconds: Int+ ) throws {+ let boundedMilliseconds = min(max(milliseconds, 0), 600_000)+ let bucketIndex = Self.performanceBucketUpperBounds.firstIndex { boundedMilliseconds <= $0 }+ ?? Self.performanceBucketUpperBounds.count+ try self.run(+ "INSERT INTO daily_dictation_performance " ++ "(day, measured_app_version, measured_os_version, metric, bucket_index, sample_count) " ++ "VALUES (?, ?, ?, ?, ?, 1) " ++ "ON CONFLICT(day, measured_app_version, measured_os_version, metric, bucket_index) " ++ "DO UPDATE SET sample_count = sample_count + 1",+ bindings: [+ .text(day), .text(measuredAppVersion), .text(self.systemConfiguration.osVersion),+ .text(metric), .integer(bucketIndex),+ ]+ )+ }++ private struct PerformanceSummaryKey: Hashable {+ let day: String+ let measuredAppVersion: String+ let measuredOSVersion: String+ }++ private struct PerformanceMetricSummary {+ var bucketCounts = Array(repeating: 0, count: performanceBucketUpperBounds.count + 1)+ var sampleCount = 0+ }++ private struct PerformanceSummary {+ let key: PerformanceSummaryKey+ var asr = PerformanceMetricSummary()+ var fluidIntelligence = PerformanceMetricSummary()++ var properties: [String: Any] {+ var properties: [String: Any] = [+ "performance_date": self.key.day,+ "measured_app_version": self.key.measuredAppVersion,+ "measured_os_version": self.key.measuredOSVersion,+ "histogram_schema_version": 1,+ ]+ Self.add(self.asr, prefix: "asr", to: &properties)+ Self.add(self.fluidIntelligence, prefix: "fluid_intelligence", to: &properties)+ return properties+ }++ private static func add(+ _ metric: PerformanceMetricSummary,+ prefix: String,+ to properties: inout [String: Any]+ ) {+ properties["\(prefix)_sample_count"] = metric.sampleCount+ guard metric.sampleCount > 0 else { return }+ properties["\(prefix)_p50_bucket"] = self.quantileBucket(metric.bucketCounts, percentile: 0.50)+ properties["\(prefix)_p95_bucket"] = self.quantileBucket(metric.bucketCounts, percentile: 0.95)+ }++ private static func quantileBucket(_ counts: [Int], percentile: Double) -> String {+ let target = max(1, Int(ceil(Double(counts.reduce(0, +)) * percentile)))+ var cumulative = 0+ for (index, count) in counts.enumerated() {+ cumulative += count+ if cumulative >= target {+ guard index < performanceBucketUpperBounds.count else { return "60000_plus" }+ return String(performanceBucketUpperBounds[index])+ }+ }+ return "unknown"+ }+ }++ private func performanceSummaries(from rows: [[String]]) -> [PerformanceSummary] {+ var summaries: [PerformanceSummaryKey: PerformanceSummary] = [:]+ for row in rows where row.count == 6 {+ let key = PerformanceSummaryKey(+ day: row[0],+ measuredAppVersion: row[1],+ measuredOSVersion: row[2]+ )+ var summary = summaries[key] ?? PerformanceSummary(key: key)+ let bucketIndex = Int(row[4]) ?? -1+ let sampleCount = Int(row[5]) ?? 0+ if row[3] == "asr" {+ Self.mergePerformanceRow(+ into: &summary.asr,+ bucketIndex: bucketIndex,+ sampleCount: sampleCount+ )+ } else if row[3] == "fluid_intelligence" {+ Self.mergePerformanceRow(+ into: &summary.fluidIntelligence,+ bucketIndex: bucketIndex,+ sampleCount: sampleCount+ )+ }+ summaries[key] = summary+ }+ return summaries.values.sorted {+ ($0.key.day, $0.key.measuredAppVersion, $0.key.measuredOSVersion) <+ ($1.key.day, $1.key.measuredAppVersion, $1.key.measuredOSVersion)+ }+ }++ private static func mergePerformanceRow(+ into metric: inout PerformanceMetricSummary,+ bucketIndex: Int,+ sampleCount: Int+ ) {+ guard metric.bucketCounts.indices.contains(bucketIndex) else { return }+ metric.bucketCounts[bucketIndex] += sampleCount+ metric.sampleCount += sampleCount+ }+private func activeOnboardingFlow(origin: AnalyticsOnboardingOrigin, at date: Date) throws -> String {if let existing = try self.string("SELECT flow_id FROM onboarding_flows WHERE completed = 0 AND origin = ? " +diff --git a/Sources/Fluid/Analytics/AnalyticsEvent.swift b/Sources/Fluid/Analytics/AnalyticsEvent.swiftindex a4a8ab37..5ae86995 100644--- a/Sources/Fluid/Analytics/AnalyticsEvent.swift+++ b/Sources/Fluid/Analytics/AnalyticsEvent.swift@@ -12,6 +12,44 @@ enum AnalyticsEvent: String {case onboardingTryoutFinished = "onboarding_tryout_finished"case modelDownloadStarted = "model_download_started"case modelDownloadFinished = "model_download_finished"+ case dictationPerformanceDailySummary = "dictation_performance_daily_summary"+}++enum AnalyticsBuildPolicy {+ // Release artifacts identify the beta cohort in their installed version+ // (e.g. 1.6.10-beta.1). The updater preference only selects future updates;+ // enabling it on a stable installation must not turn on beta telemetry.+ static func automaticallyCollectsDictationPerformance(appVersion: String) -> Bool {+ appVersion+ .lowercased()+ .components(separatedBy: CharacterSet.alphanumerics.inverted)+ .contains("beta")+ }+}++enum DictationPerformanceLogSummary {+ static func line(+ asrMilliseconds: Int?,+ aiMilliseconds: Int?,+ readyMilliseconds: Int,+ outcome: String+ ) -> String {+ let asr = asrMilliseconds ?? -1+ let ai = aiMilliseconds ?? -1+ let measured = max(asr, 0) + max(ai, 0)+ let appOverhead = max(readyMilliseconds - measured, 0)+ let slowest: String+ if ai >= asr, ai >= appOverhead, ai >= 0 {+ slowest = "ai"+ } else if asr >= appOverhead, asr >= 0 {+ slowest = "asr"+ } else {+ slowest = "app_overhead"+ }+ return "DICTATION_SUMMARY asrMs=\(asr) aiMs=\(ai) "+ + "appOverheadMs=\(appOverhead) readyMs=\(readyMilliseconds) "+ + "slowest=\(slowest) outcome=\(outcome)"+ }}enum AnalyticsActivityKind: String {diff --git a/Sources/Fluid/Analytics/AnalyticsService.swift b/Sources/Fluid/Analytics/AnalyticsService.swiftindex bf9ef4c7..1656f3eb 100644--- a/Sources/Fluid/Analytics/AnalyticsService.swift+++ b/Sources/Fluid/Analytics/AnalyticsService.swift@@ -63,6 +63,20 @@ final class AnalyticsService {}}+ /// Beta builds aggregate these timings locally and emit one summary per day.+ func recordBetaDictationPerformance(+ asrMilliseconds: Int?,+ fluidIntelligenceMilliseconds: Int?+ ) {+ self.submit { core, context in+ await core.recordBetaDictationPerformance(+ asrMilliseconds: asrMilliseconds,+ fluidIntelligenceMilliseconds: fluidIntelligenceMilliseconds,+ context: context+ )+ }+ }+func recordOnboardingStarted(origin: AnalyticsOnboardingOrigin) {self.submit { core, context inawait core.recordOnboardingStarted(origin: origin, context: context)@@ -195,7 +209,9 @@ final class AnalyticsService {detailedConsentGeneration: detailedConsentGeneration,config: AnalyticsConfig.fromBundle(),distinctID: AnalyticsIdentityStore.shared.anonymousInstallID,- appVersion: version+ appVersion: version,+ collectsBetaPerformance: AnalyticsBuildPolicy+ .automaticallyCollectsDictationPerformance(appVersion: version))}}@@ -206,6 +222,7 @@ private struct AnalyticsContext {let config: AnalyticsConfiglet distinctID: Stringlet appVersion: String+ let collectsBetaPerformance: Bool}final nonisolated class DetailedAnalyticsConsentGate: @unchecked Sendable {@@ -250,8 +267,8 @@ private actor AnalyticsCore {}guard context.config.isConfigured else { return }let database = try self.database(for: context)+ try database.finalizeDays(before: Date())if context.detailedAnalyticsEnabled {- try database.finalizeDays(before: Date())try database.recoverInterruptedModelDownloads(at: Date())}self.startFlushLoopIfNeeded()@@ -301,6 +318,28 @@ private actor AnalyticsCore {}}+ func recordBetaDictationPerformance(+ asrMilliseconds: Int?,+ fluidIntelligenceMilliseconds: Int?,+ context: AnalyticsContext+ ) async {+ guard context.collectsBetaPerformance,+ context.config.isConfigured+ else { return }+ do {+ let database = try self.database(for: context)+ try database.recordDictationPerformance(+ asrMilliseconds: asrMilliseconds,+ fluidIntelligenceMilliseconds: fluidIntelligenceMilliseconds,+ measuredAppVersion: context.appVersion,+ at: Date()+ )+ self.startFlushLoopIfNeeded()+ } catch {+ return+ }+ }+func recordOnboardingStarted(origin: AnalyticsOnboardingOrigin, context: AnalyticsContext) async {await self.writeDetailed(context: context, fallbackActivity: .app) { database, date intry database.recordOnboardingStarted(origin: origin, at: date)@@ -537,9 +576,7 @@ private actor AnalyticsCore {let items: [AnalyticsOutboxItem]do {- if context.detailedAnalyticsEnabled {- try database.finalizeDays(before: Date())- }+ try database.finalizeDays(before: Date())items = try database.readyOutbox(limit: self.batchSize, at: Date())} catch {returndiff --git a/Sources/Fluid/Analytics/AnalyticsSystemConfiguration.swift b/Sources/Fluid/Analytics/AnalyticsSystemConfiguration.swiftindex f1fe3d7e..a36b758a 100644--- a/Sources/Fluid/Analytics/AnalyticsSystemConfiguration.swift+++ b/Sources/Fluid/Analytics/AnalyticsSystemConfiguration.swift@@ -4,10 +4,12 @@ import Foundationstruct AnalyticsSystemConfiguration: Equatable {let ramGB: Intlet chip: String+ let osVersion: Stringstatic let current = AnalyticsSystemConfiguration(ramGB: Self.installedRAMInGigabytes,- chip: Self.sysctlString("machdep.cpu.brand_string") ?? "unknown"+ chip: Self.sysctlString("machdep.cpu.brand_string") ?? "unknown",+ osVersion: ProcessInfo.processInfo.operatingSystemVersionString)private static var installedRAMInGigabytes: Int {diff --git a/Sources/Fluid/AppDelegate.swift b/Sources/Fluid/AppDelegate.swiftindex 5a8d09cf..e9eefc8c 100644--- a/Sources/Fluid/AppDelegate.swift+++ b/Sources/Fluid/AppDelegate.swift@@ -26,6 +26,8 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelefunc applicationDidFinishLaunching(_ notification: Notification) {// Bring up file logging + crash handlers immediately during launch._ = FileLogger.shared+ TypingService.startKeyboardLayoutTracking()+ _ = TranscriptionHistoryStore.shared// Must be read during the launch callback - the current Apple Event identifies// login-item launches (used to optionally start silently, see issue #369).self.wasLaunchedAsLoginItem = Self.detectLoginItemLaunch()@@ -62,6 +64,23 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele// All gradients and effects are optimized for dark mode}+ func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {+ Task { @MainActor in+ await TranscriptionHistoryStore.shared.finishPendingWrites()+ if let error = TranscriptionHistoryStore.shared.persistenceError {+ let alert = NSAlert()+ alert.messageText = "History could not be saved"+ alert.informativeText = error+ alert.addButton(withTitle: "Keep Open")+ alert.addButton(withTitle: "Quit Anyway")+ sender.reply(toApplicationShouldTerminate: alert.runModal() == .alertSecondButtonReturn)+ return+ }+ sender.reply(toApplicationShouldTerminate: true)+ }+ return .terminateLater+ }+func applicationWillTerminate(_ notification: Notification) {DebugLogger.shared.info("Application will terminate", source: "AppDelegate")self.shutdownPrivateAIRuntimeForTermination()@@ -127,6 +146,9 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele}func applicationDidBecomeActive(_ notification: Notification) {+ DispatchQueue.global(qos: .utility).async {+ try? KeychainService.shared.refreshCachedKeys()+ }if let deadline = self.analyticsActivationSuppressionDeadline, Date() <= deadline {self.analyticsActivationSuppressionDeadline = nil} else {diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swiftindex c79ff30e..79700192 100644--- a/Sources/Fluid/ContentView.swift+++ b/Sources/Fluid/ContentView.swift@@ -15,7 +15,7 @@ import SwiftUI// MARK: - AI Processing Errors-enum AIProcessingError: LocalizedError {+nonisolated enum AIProcessingError: LocalizedError {case noVerifiedProvidercase missingAPIKey(provider: String)case missingModel(provider: String)@@ -48,29 +48,99 @@ enum AIProcessingError: LocalizedError {}}-@MainActor-private final class DictationAIStreamPreviewBuffer {- private var chunks: [String] = []- private var lastUIUpdate = CFAbsoluteTimeGetCurrent()- private let minimumUpdateInterval: CFTimeInterval = 0.033+nonisolated enum DictationAIFailurePresentationPolicy {+ static func shouldPresent(shouldPersistOutputs: Bool, fallbackReason: String?) -> Bool {+ shouldPersistOutputs && fallbackReason != nil+ }++ static func notificationMessage(for error: Error) -> String {+ if let aiError = error as? AIProcessingError, aiError.isConfigurationError {+ return "\(aiError.localizedDescription). Open AI Providers to configure a provider."+ }+ return error.localizedDescription+ }+}++nonisolated enum DictationStreamingFallbackPolicy {+ static func shouldRetryWithoutStreaming(after error: Error) -> Bool {+ if error is CancellationError || error is URLError {+ return false+ }+ guard let llmError = error as? LLMError else { return true }+ switch llmError {+ case .networkError, .timeout, .invalidURL, .encodingError, .invalidRequest:+ return false+ case .invalidResponse, .httpError:+ return true+ }+ }+}++final nonisolated class DictationAIStreamPreviewBuffer: @unchecked Sendable {+ typealias Publisher = @MainActor @Sendable (String) -> Void++ private let lock = NSLock()+ private let minimumUpdateInterval: TimeInterval+ private let publisher: Publisher+ private var bufferedText = ""+ private var lastPublishedText = ""+ private var nextEligibleUIUpdate: TimeInterval+ private var isUIUpdateScheduled = false++ init(+ minimumUpdateInterval: TimeInterval = 0.033,+ initialUpdateDelay: TimeInterval = 0.5,+ publisher: @escaping Publisher = { text in+ NotchOverlayManager.shared.updateTranscriptionText(text)+ }+ ) {+ self.minimumUpdateInterval = minimumUpdateInterval+ self.nextEligibleUIUpdate = ProcessInfo.processInfo.systemUptime + initialUpdateDelay+ self.publisher = publisher+ }func append(_ chunk: String) {guard !chunk.isEmpty else { return }- self.chunks.append(chunk)+ let shouldSchedule = self.lock.withLock {+ self.bufferedText += chunk+ guard !self.isUIUpdateScheduled,+ ProcessInfo.processInfo.systemUptime >= self.nextEligibleUIUpdate+ else {+ return false+ }+ self.isUIUpdateScheduled = true+ return true+ }+ guard shouldSchedule else { return }- let now = CFAbsoluteTimeGetCurrent()- guard now - self.lastUIUpdate >= self.minimumUpdateInterval else { return }- self.lastUIUpdate = now- self.publish()+ Task { @MainActor [weak self] in+ self?.publishScheduledUpdate()+ }}+ @MainActorfunc flush() {- self.publish()+ guard let text = self.takeTextForPublishing(requiresScheduledUpdate: false) else { return }+ self.publisher(text)+ }++ @MainActor+ private func publishScheduledUpdate() {+ guard let text = self.takeTextForPublishing(requiresScheduledUpdate: true) else { return }+ self.publisher(text)}- private func publish() {- let processedText = self.chunks.joined()- NotchOverlayManager.shared.updateTranscriptionText(processedText)+ private func takeTextForPublishing(requiresScheduledUpdate: Bool) -> String? {+ self.lock.withLock {+ if requiresScheduledUpdate, !self.isUIUpdateScheduled {+ return nil+ }+ self.isUIUpdateScheduled = false+ self.nextEligibleUIUpdate = ProcessInfo.processInfo.systemUptime + self.minimumUpdateInterval+ guard self.bufferedText != self.lastPublishedText else { return nil }+ self.lastPublishedText = self.bufferedText+ return self.bufferedText+ }}}@@ -161,6 +231,8 @@ enum ShortcutRecordingTarget: Hashable {// swiftlint:disable type_body_length file_lengthstruct ContentView: View {+ private static let aiProcessingStatusDelayNanoseconds: UInt64 = 500_000_000+private enum ActiveRecordingMode: String {case nonecase dictate@@ -906,6 +978,26 @@ struct ContentView: View {)}+ private func recordDictationUsage(+ shouldUseAI: Bool,+ dictationSlot: SettingsStore.DictationShortcutSlot?,+ appBundleID: String+ ) -> (provider: String?, model: String?) {+ let postProcessing = self.currentDictationAIModelInfo(+ dictationSlot: dictationSlot,+ appBundleID: appBundleID+ )+ AnalyticsService.shared.recordUsage(+ mode: .dictation,+ transcriptionModel: self.settings.selectedSpeechModel.analyticsDescriptor,+ aiModel: shouldUseAI ? AnalyticsModelDescriptor(+ provider: postProcessing.provider ?? "unknown",+ model: postProcessing.model ?? "unknown"+ ) : nil+ )+ return postProcessing+ }+// MARK: - Mode Transition Handler/// Centralized handler for sidebar mode transitions to ensure proper cleanup and state management@@ -2155,6 +2247,7 @@ struct ContentView: View {private struct AITextProcessingResult {let text: Stringlet tokensPerSecond: Double?+ let fluidIntelligenceLatencyMilliseconds: Int?}private func processTextWithAI(@@ -2163,7 +2256,8 @@ struct ContentView: View {overrideProviderID: String? = nil,overrideModel: String? = nil,dictationSlot: SettingsStore.DictationShortcutSlot? = nil,- streamHandler: PrivateAIStreamHandler? = nil+ streamHandler: PrivateAIStreamHandler? = nil,+ benchmarkID: String? = nil) async throws -> String {try await self.processTextWithAIMetrics(inputText,@@ -2171,7 +2265,8 @@ struct ContentView: View {overrideProviderID: overrideProviderID,overrideModel: overrideModel,dictationSlot: dictationSlot,- streamHandler: streamHandler+ streamHandler: streamHandler,+ benchmarkID: benchmarkID).text}@@ -2181,8 +2276,10 @@ struct ContentView: View {overrideProviderID: String? = nil,overrideModel: String? = nil,dictationSlot: SettingsStore.DictationShortcutSlot? = nil,- streamHandler: PrivateAIStreamHandler? = nil+ streamHandler: PrivateAIStreamHandler? = nil,+ benchmarkID: String? = nil) async throws -> AITextProcessingResult {+ let routeStartedAt = ProcessInfo.processInfo.systemUptimelet appInfo = self.recordingAppInfo ?? self.getCurrentAppInfo()let route: DictationProviderRouteif let overrideProviderID, let overrideModel {@@ -2198,6 +2295,9 @@ struct ContentView: View {appBundleID: appInfo.bundleId)}+ self.appBench(+ "ai_route_resolved elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - routeStartedAt) * 1000).rounded()))"+ )let currentSelectedProviderID = route.providerIDlet derivedCurrentProvider = route.providerKeylet derivedBaseURL = route.baseURL@@ -2225,6 +2325,8 @@ struct ContentView: View {self.logDictationPromptTrace("Selected context text", value: "<none (dictation mode)>")}+ self.appBench("ai_private_call")+ let fluidIntelligenceStartedAt = ProcessInfo.processInfo.systemUptimelet response = try await PrivateAIIntegrationService.shared.enhanceDictation(inputText,runtime: PrivateAIIntegrationService.RuntimeConfiguration(@@ -2246,6 +2348,7 @@ struct ContentView: View {),streamHandler: streamHandler)+ self.appBench("ai_private_return")if self.shouldTracePromptProcessing {self.logDictationPromptTrace("Model answer (A)", value: response.outputText)@@ -2253,9 +2356,13 @@ struct ContentView: View {let tokensPerSecond = response.tokensPerSecond.flatMap { value invalue.isFinite && value > 0 ? value : nil}+ let fluidIntelligenceLatencyMilliseconds = Int(+ ((ProcessInfo.processInfo.systemUptime - fluidIntelligenceStartedAt) * 1000).rounded()+ )return AITextProcessingResult(text: response.outputText,- tokensPerSecond: tokensPerSecond+ tokensPerSecond: tokensPerSecond,+ fluidIntelligenceLatencyMilliseconds: fluidIntelligenceLatencyMilliseconds)}@@ -2374,7 +2481,8 @@ struct ContentView: View {streaming: enableStreaming,tools: [],temperature: isTemperatureUnsupported ? nil : 0.2,- extraParameters: extraParams+ extraParameters: extraParams,+ benchmarkID: benchmarkID)if enableStreaming {config.onContentChunk = { chunk in@@ -2389,6 +2497,11 @@ struct ContentView: View {do {response = try await LLMClient.shared.call(config)} catch {+ guard DictationStreamingFallbackPolicy.shouldRetryWithoutStreaming(after: error) else {+ self.appBench("ai_streaming_fallback_skipped reason=transport_or_cancel")+ throw error+ }+ self.appBench("ai_streaming_fallback_start")DebugLogger.shared.warning("Streaming dictation post-processing failed; retrying without streaming: \(error.localizedDescription)",source: "ContentView"@@ -2401,7 +2514,8 @@ struct ContentView: View {streaming: false,tools: [],temperature: isTemperatureUnsupported ? nil : 0.2,- extraParameters: extraParams+ extraParameters: extraParams,+ benchmarkID: benchmarkID)response = try await LLMClient.shared.call(fallbackConfig)}@@ -2424,7 +2538,11 @@ struct ContentView: View {guard !response.content.isEmpty else {throw AIProcessingError.emptyResponse}- return AITextProcessingResult(text: response.content, tokensPerSecond: nil)+ return AITextProcessingResult(+ text: response.content,+ tokensPerSecond: nil,+ fluidIntelligenceLatencyMilliseconds: nil+ )}// MARK: - Streaming Response Handler (DEPRECATED - Now handled by LLMClient)@@ -2434,7 +2552,19 @@ struct ContentView: View {// MARK: - Stop and Process Transcriptionprivate func stopAndProcessTranscription(route: DictationOutputRoute = .normal) async {- DebugLogger.shared.debug("stopAndProcessTranscription called", source: "ContentView")+ let pipelineID = UUID().uuidString+ await DebugLogger.$pipelineID.withValue(pipelineID) {+ await self.processStoppedTranscription(route: route, pipelineID: pipelineID)+ }+ }++ private func processStoppedTranscription(route: DictationOutputRoute, pipelineID: String) async {+ let pipelineStartedAt = ProcessInfo.processInfo.systemUptime+ let expectedOverlayLifecycleID = self.overlayLifecycleID+ self.appBench("pipeline_begin id=\(pipelineID) route=\(route.rawValue)")+ defer {+ self.appBench("pipeline_handler_return id=\(pipelineID) elapsedMs=\((ProcessInfo.processInfo.systemUptime - pipelineStartedAt) * 1000) deliveryMayBePending=true")+ }DebugLogger.shared.info("Output route selected: \(route.rawValue)", source: "ContentView")self.appBench("stop_path_enter route=\(route.rawValue)")let isOnboardingTryout = route == .onboardingSandbox && self.isOnboardingVoicePlaygroundStepActive@@ -2455,30 +2585,15 @@ struct ContentView: View {!promptTest.isActive &&!shouldUseAIOnStop &&!self.settings.spokenSendEnabled- var didRequestOverlayHideOnStop = falseDebugLogger.shared.info("Routing decision snapshot | activeMode=\(modeAtStop.rawValue) | rewrite=\(wasRewriteMode) | command=\(wasCommandMode) | overlay=\(NotchContentState.shared.mode.rawValue)",source: "ContentView")self.clearActiveRecordingMode()-- if shouldHideOverlayOnStop {- didRequestOverlayHideOnStop = true- DebugLogger.shared.debug("Hiding dictation overlay at stop path", source: "ContentView")- self.hideOverlayAsync(reason: "stop_path")- } else {- // Show "Transcribing" state before calling stop() when the overlay needs- // to remain available for prompt, command, rewrite, or AI feedback.- DebugLogger.shared.debug("Showing transcription processing state", source: "ContentView")- self.appBench("processing_ui_request status=Transcribing")- self.menuBarManager.setProcessing(true)- NotchOverlayManager.shared.updateTranscriptionText("Transcribing")- self.appBench("processing_ui_requested status=Transcribing")-- // Give SwiftUI a chance to render the processing state before heavier work.- await Task.yield()- }+ let stopOverlay = self.prepareOverlayForASRStop(shouldHideOverlayOnStop: shouldHideOverlayOnStop)+ let stopUIInvalidationHold = self.holdStopUIInvalidation(whileProcessing: !stopOverlay.didRequestHide)+ defer { self.releaseStopUIInvalidation(stopUIInvalidationHold) }// Stop the ASR service and wait for transcription to complete// The processing indicator will stay visible during this phase@@ -2487,9 +2602,12 @@ struct ContentView: View {// Play the stop cue as soon as the audio engine has stopped, before the// (potentially slow) final transcription pass. Scoped to dictation only —// Command/Edit modes call asr.stop() without this callback.- let transcribedText = await asr.stop(onCaptureStopped: {- TranscriptionSoundPlayer.shared.playStopSound()- })+ let transcribedText = await asr.stop(+ onCaptureStopped: {+ TranscriptionSoundPlayer.shared.playStopSound()+ },+ onFinalTranscriptionStarted: stopOverlay.onFinalTranscriptionStarted+ )self.appBench("asr_stop_return elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - asrStopStartedAt) * 1000).rounded()))")let audioSnapshot = self.asr.consumeLastCompletedAudioSnapshot()let transcriptionDurationMilliseconds = self.asr.consumeLastFinalTranscriptionDurationMs()@@ -2498,10 +2616,10 @@ struct ContentView: View {source: "ContentView")- // Reset the transcription text display after transcription completes- NotchOverlayManager.shared.updateTranscriptionText("")-guard transcribedText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false else {+ // Empty results have no delivery callback, so clear their stale+ // preview before the existing empty-result dismissal path runs.+ NotchOverlayManager.shared.updateTranscriptionText("")DebugLogger.shared.debug("Transcription returned empty text", source: "ContentView")if isOnboardingTryout {if self.asr.lastStopOutcome == .failed {@@ -2513,8 +2631,11 @@ struct ContentView: View {AnalyticsService.shared.recordOnboardingTryoutAttemptResult(outcome: .empty)}}+ if route == .normal, !wasRewriteMode, !wasCommandMode, !promptTest.isActive {+ self.recordEmptyDictationPerformance(startedAt: pipelineStartedAt, asrMs: transcriptionDurationMilliseconds)+ }// Finish the same short exit transition even when no text is emitted.- if !didRequestOverlayHideOnStop {+ if !stopOverlay.didRequestHide {await self.menuBarManager.finishProcessingAndHideOverlay()}return@@ -2522,45 +2643,7 @@ struct ContentView: View {// Prompt Test Mode: reroute dictation hotkey output into the prompt editor (no typing/clipboard/history).if promptTest.isActive {- promptTest.lastTranscriptionText = transcribedText- promptTest.lastOutputText = ""- promptTest.lastError = ""-- guard DictationAIPostProcessingGate.isProviderConfigured(- providerID: promptTest.draftProviderID,- model: promptTest.draftModel- ) else {- promptTest.lastError = "AI post-processing is not configured. Configure a provider/model (and API key for non-local endpoints) to test prompts."- self.menuBarManager.setProcessing(false)- return- }-- promptTest.isProcessing = true- // Processing already true from above- defer {- self.menuBarManager.setProcessing(false)- promptTest.isProcessing = false- }-- do {- let result = try await self.processTextWithAI(- transcribedText,- overrideSystemPrompt: promptTest.draftPromptText,- overrideProviderID: promptTest.draftProviderID,- overrideModel: promptTest.draftModel- )- let appInfo = self.recordingAppInfo ?? self.getCurrentAppInfo()- let literalFormattedResult = ASRService.applyDictationLiteralFormatting(- result,- appName: appInfo.name,- bundleID: appInfo.bundleId,- windowTitle: appInfo.windowTitle- )- promptTest.lastOutputText = ASRService.applyGAAVFormatting(literalFormattedResult)- } catch {- DebugLogger.shared.error("Prompt test AI call failed: \(error.localizedDescription)", source: "ContentView")- promptTest.lastError = error.localizedDescription- }+ await self.processDictationPromptTest(transcribedText)return}@@ -2597,7 +2680,9 @@ struct ContentView: View {var aiFallbackReason: String?var postProcessingModel: String?var aiProcessingDurationMilliseconds: Int?+ var fluidIntelligenceDurationMilliseconds: Int?var aiTokensPerSecond: Double?+ var aiFallbackNotificationError: String?let appInfo = self.recordingAppInfo ?? self.getCurrentAppInfo()let punctuationFormattedText = ASRService.applySpokenPunctuationFormatting(transcribedText,@@ -2619,51 +2704,45 @@ struct ContentView: View {DictationAIPostProcessingGate.isConfigured(for: $0, appBundleID: appInfo.bundleId)} ?? DictationAIPostProcessingGate.isConfigured(for: .primary, appBundleID: appInfo.bundleId))let transcriptionModelInfo = self.currentTranscriptionModelInfo()- let postProcessingModelInfo = self.currentDictationAIModelInfo(+ let postProcessingModelInfo = self.recordDictationUsage(+ shouldUseAI: shouldUseAI,dictationSlot: activeDictationSlot,appBundleID: appInfo.bundleId)- AnalyticsService.shared.recordUsage(- mode: .dictation,- transcriptionModel: self.settings.selectedSpeechModel.analyticsDescriptor,- aiModel: shouldUseAI ? AnalyticsModelDescriptor(- provider: postProcessingModelInfo.provider ?? "unknown",- model: postProcessingModelInfo.model ?? "unknown"- ) : nil- )if shouldUseAI {DebugLogger.shared.debug("Routing transcription through AI post-processing", source: "ContentView")postProcessingModel = postProcessingModelInfo.modellet postProcessingInputChars = normalizedTranscribedText.countlet postProcessingStart = ProcessInfo.processInfo.systemUptime+ let processingFeedback = self.makeAIProcessingFeedback(lifecycleID: expectedOverlayLifecycleID)+ let refiningStatusTask = processingFeedback.statusTask+ defer { refiningStatusTask.cancel() }- // Update overlay text to show we're now refining (processing already true)- self.appBench("processing_ui_request status=Refining")- NotchOverlayManager.shared.updateTranscriptionText("Refining")- self.appBench("processing_ui_requested status=Refining")-- // Ensure the status label becomes visible immediately.- await Task.yield()-- let streamPreview = DictationAIStreamPreviewBuffer()+ let streamPreview = processingFeedback.streamPreviewlet streamHandler: PrivateAIStreamHandler = { chunk in- Task { @MainActor in- streamPreview.append(chunk)- }+ streamPreview.append(chunk)}do {+ self.logAIProcessCall(pipelineID, postProcessingModelInfo, postProcessingInputChars)let result = try await self.processTextWithAIMetrics(normalizedTranscribedText,overrideSystemPrompt: promptOverride,dictationSlot: activeDictationSlot,- streamHandler: streamHandler+ streamHandler: streamHandler,+ benchmarkID: pipelineID)+ refiningStatusTask.cancel()finalText = result.text+ self.appBench("ai_process_return id=\(pipelineID)")aiTokensPerSecond = result.tokensPerSecond- await streamPreview.flush()+ fluidIntelligenceDurationMilliseconds = result.fluidIntelligenceLatencyMilliseconds+ streamPreview.flush()+ self.appBench("ai_preview_flushed id=\(pipelineID)")} catch {+ refiningStatusTask.cancel()+ self.appBench("ai_process_fail id=\(pipelineID)")// Fall back to the raw transcription so the user still gets// their words typed instead of an error string.DebugLogger.shared.error(@@ -2671,17 +2750,7 @@ struct ContentView: View {source: "ContentView")aiFallbackReason = error.localizedDescription- // Configuration errors are actionable — point the user at settings- // rather than just echoing the technical error string.- if let aiError = error as? AIProcessingError,- aiError.isConfigurationError- {- NotificationService.showAIProcessingFallback(- error: "\(aiError.localizedDescription). Open AI Providers to configure a provider."- )- } else {- NotificationService.showAIProcessingFallback(error: error.localizedDescription)- }+ aiFallbackNotificationError = DictationAIFailurePresentationPolicy.notificationMessage(for: error)finalText = normalizedTranscribedText}let postProcessingLatencyMs = Int(@@ -2696,10 +2765,6 @@ struct ContentView: View {+ "inputChars=\(postProcessingInputChars) fallback=\(aiFallbackReason != nil)",source: "ContentView")- // Clear transient status text before leaving processing state to avoid- // a brief non-shimmer "Refining..." preview flash.- NotchOverlayManager.shared.updateTranscriptionText("")-} else {finalText = normalizedTranscribedText}@@ -2740,6 +2805,15 @@ struct ContentView: View {DebugLogger.shared.info("Transcription finalized (chars: \(finalText.count))", source: "ContentView")let finalTextReadyAt = ProcessInfo.processInfo.systemUptime+ self.recordCompletedDictationPerformance(+ route: route,+ pipelineStartedAt: pipelineStartedAt,+ readyAt: finalTextReadyAt,+ transcriptionDurationMilliseconds: transcriptionDurationMilliseconds,+ aiProcessingDurationMilliseconds: aiProcessingDurationMilliseconds,+ fluidIntelligenceDurationMilliseconds: fluidIntelligenceDurationMilliseconds,+ outcome: aiFallbackReason == nil ? "success" : "ai_fallback"+ )let finalOutputPlan = ASRService.makeDictationLiteralOutputPlan(for: finalText,appName: appInfo.name,@@ -2748,6 +2822,7 @@ struct ContentView: View {)self.appBench("transcription_finalized chars=\(finalText.count)")self.appBench("text_ready chars=\(finalText.count)")+ self.appBench("pipeline_text_ready id=\(pipelineID) stopToReadyMs=\((finalTextReadyAt - pipelineStartedAt) * 1000)")let shouldPersistOutputs = route == .normalif !shouldPersistOutputs {@@ -2757,12 +2832,11 @@ struct ContentView: View {)}- let shouldShowAIProcessingFailure = shouldPersistOutputs && aiFallbackReason != nil- if shouldShowAIProcessingFailure {- self.pendingAIReprocessText = spokenSendParse.shouldSend ? normalizedTranscribedText : transcribedText- NotchContentState.shared.showAIProcessingFailure()- self.menuBarManager.finishProcessingKeepingOverlayVisible()- } else {+ let shouldShowAIProcessingFailure = DictationAIFailurePresentationPolicy.shouldPresent(+ shouldPersistOutputs: shouldPersistOutputs,+ fallbackReason: aiFallbackReason+ )+ if !shouldShowAIProcessingFailure {self.pendingAIReprocessText = nil}@@ -2807,6 +2881,7 @@ struct ContentView: View {}var didTypeExternally = false+ var didScheduleOverlayHideAfterDelivery = falselet shouldTypeExternally = shouldPersistOutputs && !isFluidFrontmostDebugLogger.shared.debug(@@ -2824,8 +2899,9 @@ struct ContentView: View {&& (sendsExistingDraft || !finalText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)&& targetMatchesRecordingFocus&& !self.isSpokenSendBlockedApp(appInfo)- // Dispatch insertion as soon as the destination app is ready; the- // overlay hides asynchronously after output so it cannot delay paste.+ // Submit insertion first, then retire the overlay in this same main+ // turn. The worker can paste concurrently; dismissal must not queue+ // behind history notifications or a subsequent SwiftUI render.if typingTarget.shouldRestoreOriginalFocus {await self.restoreFocusToRecordingTarget()}@@ -2842,14 +2918,34 @@ struct ContentView: View {targetPID: typingTarget.pid,textReadyAt: finalTextReadyAt)+ self.logPipelineCompletion(+ outcome: String(describing: deliveryOutcome),+ pipelineID: pipelineID,+ pipelineStartedAt: pipelineStartedAt,+ textReadyAt: finalTextReadyAt+ )didTypeExternally = deliveryOutcome.didInsert} else {+ let shouldHideOverlayAfterDelivery = !shouldShowAIProcessingFailure+ && !stopOverlay.didRequestHideself.asr.typeOutputPlanToActiveField(finalOutputPlan,preferredTargetPID: typingTarget.pid,textReadyAt: finalTextReadyAt,- tracksDictionaryCorrections: true+ tracksDictionaryCorrections: true,+ completion: { outcome in+ self.handleTypingDelivery(+ outcome,+ pipelineID: pipelineID,+ pipelineStartedAt: pipelineStartedAt,+ textReadyAt: finalTextReadyAt,+ shouldHideOverlay: shouldHideOverlayAfterDelivery && spokenSendRequested,+ expectedOverlayLifecycleID: expectedOverlayLifecycleID+ )+ })+ self.hideOverlayForDispatchedPaste(shouldHide: shouldHideOverlayAfterDelivery && !spokenSendRequested, lifecycleID: expectedOverlayLifecycleID)+ didScheduleOverlayHideAfterDelivery = shouldHideOverlayAfterDeliverydidTypeExternally = true}if spokenSendRequested, !spokenSendAllowed {@@ -2863,16 +2959,228 @@ struct ContentView: View {try? await Task.sleep(nanoseconds: 650_000_000)}}- NotchOverlayManager.shared.updateTranscriptionText("")NotchContentState.shared.setSpokenSendIndicatorState(.hidden)- if !shouldShowAIProcessingFailure, !didRequestOverlayHideOnStop {+ if !shouldShowAIProcessingFailure,+ !stopOverlay.didRequestHide,+ !didScheduleOverlayHideAfterDelivery+ {+ NotchOverlayManager.shared.updateTranscriptionText("")self.hideOverlayAfterOutput()}}- if !didTypeExternally, !shouldShowAIProcessingFailure, !didRequestOverlayHideOnStop {+ // Submit raw fallback delivery before failure UI or notification work can+ // compete with it on the main actor. Sandbox runs never present either.+ if shouldShowAIProcessingFailure {+ self.pendingAIReprocessText = spokenSendParse.shouldSend ? normalizedTranscribedText : transcribedText+ NotchContentState.shared.showAIProcessingFailure()+ self.menuBarManager.finishProcessingKeepingOverlayVisible()+ if let aiFallbackNotificationError {+ NotificationService.showAIProcessingFallback(error: aiFallbackNotificationError)+ }+ }++ if !didTypeExternally, !shouldShowAIProcessingFailure, !stopOverlay.didRequestHide {self.hideOverlayAfterOutput()}+ if !shouldTypeExternally {+ self.logPipelineCompletion(+ outcome: shouldPersistOutputs ? "internal_editor" : "sandbox",+ pipelineID: pipelineID,+ pipelineStartedAt: pipelineStartedAt,+ textReadyAt: finalTextReadyAt+ )+ }+ }++ private func processDictationPromptTest(_ transcribedText: String) async {+ let promptTest = DictationPromptTestCoordinator.shared+ promptTest.lastTranscriptionText = transcribedText+ promptTest.lastOutputText = ""+ promptTest.lastError = ""+ guard DictationAIPostProcessingGate.isProviderConfigured(+ providerID: promptTest.draftProviderID,+ model: promptTest.draftModel+ ) else {+ promptTest.lastError = "AI post-processing is not configured. Configure a provider/model (and API key for non-local endpoints) to test prompts."+ self.menuBarManager.setProcessing(false)+ return+ }+ promptTest.isProcessing = true+ defer {+ self.menuBarManager.setProcessing(false)+ promptTest.isProcessing = false+ }+ do {+ let result = try await self.processTextWithAI(+ transcribedText,+ overrideSystemPrompt: promptTest.draftPromptText,+ overrideProviderID: promptTest.draftProviderID,+ overrideModel: promptTest.draftModel+ )+ let appInfo = self.recordingAppInfo ?? self.getCurrentAppInfo()+ let literalFormattedResult = ASRService.applyDictationLiteralFormatting(+ result,+ appName: appInfo.name,+ bundleID: appInfo.bundleId,+ windowTitle: appInfo.windowTitle+ )+ promptTest.lastOutputText = ASRService.applyGAAVFormatting(literalFormattedResult)+ } catch {+ DebugLogger.shared.error("Prompt test AI call failed: \(error.localizedDescription)", source: "ContentView")+ promptTest.lastError = error.localizedDescription+ }+ }++ private func makeAIProcessingFeedback(+ lifecycleID: UInt64+ ) -> (statusTask: Task<Void, Never>, streamPreview: DictationAIStreamPreviewBuffer) {+ // Fast local cleanup should finish before transient SwiftUI work can queue+ // ahead of its result. Slow providers still receive visible status feedback.+ let statusTask = scheduleDeferredMainActorOperation(+ afterNanoseconds: Self.aiProcessingStatusDelayNanoseconds+ ) {+ guard self.overlayLifecycleID == lifecycleID else {+ self.appBench("processing_ui_skipped status=Refining reason=stale_lifecycle")+ return+ }+ self.menuBarManager.flushDeferredStoppedRecordingState()+ self.menuBarManager.setProcessing(true)+ self.appBench("processing_ui_request status=Refining trigger=delayed_status")+ NotchOverlayManager.shared.updateTranscriptionText("Refining")+ self.appBench("processing_ui_requested status=Refining trigger=delayed_status")+ }+ let streamPreview = DictationAIStreamPreviewBuffer { text in+ guard self.overlayLifecycleID == lifecycleID else { return }+ NotchOverlayManager.shared.updateTranscriptionText(text)+ }+ return (statusTask, streamPreview)+ }++ private func prepareOverlayForASRStop(+ shouldHideOverlayOnStop: Bool+ ) -> (didRequestHide: Bool, onFinalTranscriptionStarted: (@MainActor () -> Void)?) {+ if shouldHideOverlayOnStop {+ DebugLogger.shared.debug("Hiding dictation overlay at stop path", source: "ContentView")+ self.hideOverlayAsync(reason: "stop_path")+ return (true, nil)+ }++ guard self.asr.isFinalTranscriptionReady else {+ DebugLogger.shared.debug("Showing transcription processing state", source: "ContentView")+ self.appBench("processing_ui_request status=Transcribing")+ self.menuBarManager.setProcessing(true)+ NotchOverlayManager.shared.updateTranscriptionText("Transcribing")+ self.appBench("processing_ui_requested status=Transcribing")+ return (false, nil)+ }++ // Own the overlay before isRunning changes, but publish processing UI+ // only after final ASR has entered its executor.+ self.menuBarManager.reserveProcessingOverlay()+ self.appBench("processing_ui_reserved trigger=warm_final_asr")+ let onFinalTranscriptionStarted: @MainActor () -> Void = {+ self.menuBarManager.flushDeferredStoppedRecordingState()+ self.appBench("processing_ui_request status=Transcribing trigger=final_executor")+ self.menuBarManager.setProcessing(true)+ NotchOverlayManager.shared.updateTranscriptionText("Transcribing")+ self.appBench("processing_ui_requested status=Transcribing trigger=final_executor")+ }+ return (false, onFinalTranscriptionStarted)+ }++ private func holdStopUIInvalidation(whileProcessing: Bool) -> UInt64? {+ whileProcessing ? self.asr.holdStopUIInvalidationForOutputPipeline() : nil+ }++ private func releaseStopUIInvalidation(_ generation: UInt64?) {+ guard let generation else { return }+ self.asr.releaseStopUIInvalidationForOutputPipeline(generation)+ }++ private func hideOverlayForDispatchedPaste(shouldHide: Bool, lifecycleID: UInt64) {+ guard shouldHide, self.overlayLifecycleID == lifecycleID else { return }+ self.appBench("overlay_hide_request reason=paste_dispatched")+ self.menuBarManager.beginProcessingCompletionAndHideOverlay()+ }++ private func handleTypingDelivery(+ _ outcome: TypingService.DeliveryOutcome,+ pipelineID: String,+ pipelineStartedAt: TimeInterval,+ textReadyAt: TimeInterval,+ shouldHideOverlay: Bool,+ expectedOverlayLifecycleID: UInt64+ ) {+ self.logPipelineCompletion(+ outcome: String(describing: outcome),+ pipelineID: pipelineID,+ pipelineStartedAt: pipelineStartedAt,+ textReadyAt: textReadyAt+ )+ guard shouldHideOverlay else { return }+ guard self.overlayLifecycleID == expectedOverlayLifecycleID else {+ self.appBench(+ "overlay_hide_skipped reason=delivery_complete staleLifecycle=\(expectedOverlayLifecycleID) currentLifecycle=\(self.overlayLifecycleID)"+ )+ return+ }+ // Preserve delivery-timed dismissal for the send-suppressed status path.+ // Ordinary dictation already hid in the dispatch turn and returns above.+ self.appBench("overlay_hide_request reason=delivery_complete outcome=\(outcome)")+ self.menuBarManager.beginProcessingCompletionAndHideOverlay()+ }++ private func logPipelineCompletion(+ outcome: String,+ pipelineID: String,+ pipelineStartedAt: TimeInterval,+ textReadyAt: TimeInterval+ ) {+ let finishedAt = ProcessInfo.processInfo.systemUptime+ DebugLogger.shared.info(+ "PIPELINE_SUMMARY id=\(pipelineID) t=\(finishedAt) " ++ "stopToReadyMs=\((textReadyAt - pipelineStartedAt) * 1000) readyToDeliveryMs=\((finishedAt - textReadyAt) * 1000) " ++ "totalMs=\((finishedAt - pipelineStartedAt) * 1000) outcome=\(outcome)",+ source: "AppBenchmark"+ )+ }++ private func recordCompletedDictationPerformance(+ route: DictationOutputRoute,+ pipelineStartedAt: TimeInterval,+ readyAt: TimeInterval = ProcessInfo.processInfo.systemUptime,+ transcriptionDurationMilliseconds: Int?,+ aiProcessingDurationMilliseconds: Int?,+ fluidIntelligenceDurationMilliseconds: Int?,+ outcome: String+ ) {+ guard route == .normal else { return }+ let readyMilliseconds = Int(((readyAt - pipelineStartedAt) * 1000).rounded())+ DebugLogger.shared.info(+ DictationPerformanceLogSummary.line(+ asrMilliseconds: transcriptionDurationMilliseconds,+ aiMilliseconds: aiProcessingDurationMilliseconds,+ readyMilliseconds: readyMilliseconds,+ outcome: outcome+ ),+ source: "AppBenchmark"+ )+ AnalyticsService.shared.recordBetaDictationPerformance(+ asrMilliseconds: transcriptionDurationMilliseconds,+ fluidIntelligenceMilliseconds: fluidIntelligenceDurationMilliseconds+ )+ }++ private func recordEmptyDictationPerformance(startedAt: TimeInterval, asrMs: Int?) {+ self.recordCompletedDictationPerformance(+ route: .normal,+ pipelineStartedAt: startedAt,+ transcriptionDurationMilliseconds: asrMs,+ aiProcessingDurationMilliseconds: nil,+ fluidIntelligenceDurationMilliseconds: nil,+ outcome: self.asr.lastStopOutcome == .failed ? "asr_failed" : "empty"+ )}private func hideOverlayAfterOutput() {@@ -3045,6 +3353,7 @@ struct ContentView: View {else {return}+ let saveGeneration = TranscriptionHistoryStore.shared.audioSaveGenerationTask.detached(priority: .utility) {let result: (metadata: DictationAudioMetadata?, error: String?) = {@@ -3063,11 +3372,18 @@ struct ContentView: View {await MainActor.run {if let metadata = result.metadata {- TranscriptionHistoryStore.shared.attachAudio(metadata, to: entryID)+ TranscriptionHistoryStore.shared.attachAudio(+ metadata,+ to: entryID,+ expectedSaveGeneration: saveGeneration+ )} else if let error = result.error {DebugLogger.shared.error("Failed to save dictation audio: \(error)", source: "ContentView")}}+ if let metadata = result.metadata {+ DictationAudioHistoryStore.shared.completePendingSave(fileName: metadata.fileName)+ }}}@@ -3325,12 +3641,12 @@ struct ContentView: View {self.setActiveRecordingMode(.dictate)self.menuBarManager.setProcessing(true)NotchOverlayManager.shared.updateTranscriptionText("Reprocessing...")- await Task.yield()var aiFallbackReason: String?var postProcessingModel: String?var aiProcessingDurationMilliseconds: Int?var aiTokensPerSecond: Double?+ var aiFallbackNotificationError: String?let appInfo = self.getCurrentAppInfo()let normalizedTranscribedText = ASRService.applySpokenPunctuationFormatting(transcribedText,@@ -3359,7 +3675,7 @@ struct ContentView: View {source: "ContentView")aiFallbackReason = error.localizedDescription- NotificationService.showAIProcessingFallback(error: error.localizedDescription)+ aiFallbackNotificationError = DictationAIFailurePresentationPolicy.notificationMessage(for: error)finalText = normalizedTranscribedText}aiProcessingDurationMilliseconds = Int(@@ -3367,8 +3683,6 @@ struct ContentView: View {)}- NotchOverlayManager.shared.updateTranscriptionText("")-finalText = ASRService.applyDictationLiteralFormatting(finalText,appName: appInfo.name,@@ -3407,11 +3721,11 @@ struct ContentView: View {aiProcessingError: aiFallbackReason)}- if aiFallbackReason != nil {- self.pendingAIReprocessText = transcribedText- NotchContentState.shared.showAIProcessingFailure()- self.menuBarManager.finishProcessingKeepingOverlayVisible()- } else {+ let shouldShowAIProcessingFailure = DictationAIFailurePresentationPolicy.shouldPresent(+ shouldPersistOutputs: true,+ fallbackReason: aiFallbackReason+ )+ if !shouldShowAIProcessingFailure {self.pendingAIReprocessText = nil}@@ -3437,7 +3751,15 @@ struct ContentView: View {)}- if aiFallbackReason == nil {+ NotchOverlayManager.shared.updateTranscriptionText("")+ if shouldShowAIProcessingFailure {+ self.pendingAIReprocessText = transcribedText+ NotchContentState.shared.showAIProcessingFailure()+ self.menuBarManager.finishProcessingKeepingOverlayVisible()+ if let aiFallbackNotificationError {+ NotificationService.showAIProcessingFallback(error: aiFallbackNotificationError)+ }+ } else {self.hideOverlayAfterOutput()}@@ -4325,6 +4647,18 @@ extension ContentView {DebugLogger.shared.benchmark("APP_BENCH", message: message, source: "AppBenchmark")}+ private func logAIProcessCall(+ _ pipelineID: String,+ _ modelInfo: (provider: String?, model: String?),+ _ inputChars: Int+ ) {+ let provider = (modelInfo.provider ?? "unknown").replacingOccurrences(of: " ", with: "_")+ let model = (modelInfo.model ?? "unknown").replacingOccurrences(of: " ", with: "_")+ self.appBench(+ "ai_process_call id=\(pipelineID) provider=\(provider) model=\(model) inputChars=\(inputChars)"+ )+ }+private func callOpenAIChat() async {guard !self.isCallingAI else { return }await MainActor.run { self.isCallingAI = true }diff --git a/Sources/Fluid/Persistence/BackupService.swift b/Sources/Fluid/Persistence/BackupService.swiftindex 7610f20c..0dfdd165 100644--- a/Sources/Fluid/Persistence/BackupService.swift+++ b/Sources/Fluid/Persistence/BackupService.swift@@ -159,7 +159,8 @@ final class BackupService {private init() {}- func makeBackupDocument() async -> AppBackupDocument {+ func makeBackupDocument() async throws -> AppBackupDocument {+ try await TranscriptionHistoryStore.shared.waitUntilLoaded()let pronunciationProfiles = await PronunciationDictionaryStore.shared.allProfiles()return AppBackupDocument(schemaVersion: .current,diff --git a/Sources/Fluid/Persistence/DictationAudioHistoryStore.swift b/Sources/Fluid/Persistence/DictationAudioHistoryStore.swiftindex c3457842..f2fc4b62 100644--- a/Sources/Fluid/Persistence/DictationAudioHistoryStore.swift+++ b/Sources/Fluid/Persistence/DictationAudioHistoryStore.swift@@ -47,6 +47,8 @@ final nonisolated class DictationAudioHistoryStore: @unchecked Sendable {private let appSupportFolder = "FluidVoice"private let audioFolder = "DictationAudioHistory"private let fileManager = FileManager.default+ private let pendingSaveLock = NSLock()+ private var pendingSaveFileNames: Set<String> = []private init() {}@@ -57,10 +59,20 @@ final nonisolated class DictationAudioHistoryStore: @unchecked Sendable {model: String?) throws -> DictationAudioMetadata {let directory = try self.audioDirectory()- let fileName = self.audioFileName(entryID: entryID, timestamp: timestamp)+ let fileName = self.pendingSaveLock.withLock { () -> String in+ let fileName = self.audioFileName(entryID: entryID, timestamp: timestamp)+ self.pendingSaveFileNames.insert(fileName)+ return fileName+ }let url = directory.appendingPathComponent(fileName, isDirectory: false)- let data = Self.wavData(from: snapshot)- try data.write(to: url, options: .atomic)+ let data: Data+ do {+ data = Self.wavData(from: snapshot)+ try data.write(to: url, options: .atomic)+ } catch {+ self.completePendingSave(fileName: fileName)+ throw error+ }return DictationAudioMetadata(fileName: fileName,@@ -72,6 +84,14 @@ final nonisolated class DictationAudioHistoryStore: @unchecked Sendable {)}+ /// Keeps a completed WAV protected from orphan cleanup until its history+ /// metadata has attached on the main actor.+ func completePendingSave(fileName: String) {+ self.pendingSaveLock.withLock {+ self.pendingSaveFileNames.remove(fileName)+ }+ }+func audioFileURL(for entry: TranscriptionHistoryEntry) -> URL? {guard let audio = entry.audio else { return nil }return self.audioFileURL(fileName: audio.fileName, createIfNeeded: false)@@ -104,9 +124,14 @@ final nonisolated class DictationAudioHistoryStore: @unchecked Sendable {options: [.skipsHiddenFiles])) ?? []+ let pendingFileNames = self.pendingSaveLock.withLock { self.pendingSaveFileNames }var fileCount = 0var byteCount: Int64 = 0- for file in files where file.pathExtension.lowercased() == "wav" && !referencedFileNames.contains(file.lastPathComponent) {+ for file in files where Self.shouldDeleteUnreferencedAudioFile(+ fileName: file.lastPathComponent,+ referencedFileNames: referencedFileNames,+ pendingFileNames: pendingFileNames+ ) {guard let removedBytes = self.deleteAudioFile(at: file) else { continue }fileCount += 1byteCount += removedBytes@@ -115,6 +140,16 @@ final nonisolated class DictationAudioHistoryStore: @unchecked Sendable {return (fileCount, byteCount)}+ static func shouldDeleteUnreferencedAudioFile(+ fileName: String,+ referencedFileNames: Set<String>,+ pendingFileNames: Set<String>+ ) -> Bool {+ URL(fileURLWithPath: fileName).pathExtension.lowercased() == "wav"+ && !referencedFileNames.contains(fileName)+ && !pendingFileNames.contains(fileName)+ }+private func deleteAudioFile(at url: URL) -> Int64? {guard self.fileManager.fileExists(atPath: url.path) else {return nildiff --git a/Sources/Fluid/Persistence/KeychainService.swift b/Sources/Fluid/Persistence/KeychainService.swiftindex 58547d1c..8f4256f1 100644--- a/Sources/Fluid/Persistence/KeychainService.swift+++ b/Sources/Fluid/Persistence/KeychainService.swift@@ -23,16 +23,43 @@ enum KeychainServiceError: Error, LocalizedError {final class KeychainService {static let shared = KeychainService()+ private struct TestingBackend {+ let load: () throws -> [String: String]+ let save: ([String: String]) throws -> Void+ }++ private enum KeyCache {+ case unloaded+ case loaded([String: String])+ }+private let service = "com.fluidvoice.provider-api-keys"private let account = "fluidApiKeys"+ private let cacheLock = NSLock()+ private let ioLock = NSRecursiveLock()+ private var keyCache = KeyCache.unloaded+ private let testingBackend: TestingBackend?++ private init() {+ self.testingBackend = nil+ }- private init() {}+ init(+ testingLoad: @escaping () throws -> [String: String],+ testingSave: @escaping ([String: String]) throws -> Void+ ) {+ self.testingBackend = TestingBackend(load: testingLoad, save: testingSave)+ }// MARK: - Public APIfunc storeKey(_ key: String, for providerID: String) throws {+ self.ioLock.lock()+ defer { self.ioLock.unlock() }let trimmed = key.trimmingCharacters(in: .whitespacesAndNewlines)- var keys = try loadStoredKeys()+ // Mutations are rare and must merge against the latest aggregate in+ // case another app instance or Keychain Access changed it.+ var keys = try self.loadStoredKeys(forceRefresh: true)keys[providerID] = trimmedtry self.saveStoredKeys(keys)}@@ -43,7 +70,9 @@ final class KeychainService {}func deleteKey(for providerID: String) throws {- var keys = try loadStoredKeys()+ self.ioLock.lock()+ defer { self.ioLock.unlock() }+ var keys = try self.loadStoredKeys(forceRefresh: true)guard keys.removeValue(forKey: providerID) != nil else { return }try self.saveStoredKeys(keys)}@@ -61,11 +90,21 @@ final class KeychainService {try self.loadStoredKeys()}+ /// Refreshes the process cache after the user returns to FluidVoice, so+ /// Keychain Access or another app instance cannot leave credentials stale.+ /// Callers should run this away from the main thread because Keychain I/O+ /// may wait for the login keychain to become available.+ func refreshCachedKeys() throws {+ _ = try self.loadStoredKeys(forceRefresh: true)+ }+func storeAllKeys(_ values: [String: String]) throws {try self.saveStoredKeys(values)}func legacyProviderEntries() throws -> [String: String] {+ self.ioLock.lock()+ defer { self.ioLock.unlock() }var result: [String: String] = [:]let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,@@ -113,6 +152,8 @@ final class KeychainService {}func removeLegacyEntries(providerIDs: [String] = []) throws {+ self.ioLock.lock()+ defer { self.ioLock.unlock() }let targets: [String]if !providerIDs.isEmpty {targets = providerIDs@@ -130,7 +171,25 @@ final class KeychainService {// MARK: - Private helpers- private func loadStoredKeys() throws -> [String: String] {+ private func loadStoredKeys(forceRefresh: Bool = false) throws -> [String: String] {+ if !forceRefresh, case let .loaded(keys) = self.cachedState() { return keys }++ self.ioLock.lock()+ defer { self.ioLock.unlock() }+ // A concurrent cold read may have populated the cache while this caller+ // waited for I/O ownership. Forced refreshes intentionally bypass it.+ if !forceRefresh, case let .loaded(keys) = self.cachedState() { return keys }++ let keys = try self.readStoredKeys()+ self.setCachedKeys(keys)+ return keys+ }++ private func readStoredKeys() throws -> [String: String] {+ if let testingBackend {+ return try testingBackend.load()+ }+var query = self.aggregatedQuery()query[kSecReturnData as String] = kCFBooleanTruequery[kSecMatchLimit as String] = kSecMatchLimitOne@@ -143,9 +202,7 @@ final class KeychainService {guard let data = item as? Data else {throw KeychainServiceError.invalidData}- if data.isEmpty {- return [:]- }+ if data.isEmpty { return [:] }do {return try JSONDecoder().decode([String: String].self, from: data)} catch {@@ -159,6 +216,14 @@ final class KeychainService {}private func saveStoredKeys(_ keys: [String: String]) throws {+ self.ioLock.lock()+ defer { self.ioLock.unlock() }+ if let testingBackend {+ try testingBackend.save(keys)+ self.setCachedKeys(keys)+ return+ }+let data = try JSONEncoder().encode(keys)var attributes = self.aggregatedQuery()@@ -168,6 +233,7 @@ final class KeychainService {switch status {case errSecSuccess:+ self.setCachedKeys(keys)try self.removeLegacyEntries()returncase errSecDuplicateItem:@@ -181,12 +247,25 @@ final class KeychainService {guard updateStatus == errSecSuccess else {throw KeychainServiceError.unhandled(updateStatus)}+ self.setCachedKeys(keys)try self.removeLegacyEntries()default:throw KeychainServiceError.unhandled(status)}}+ private func cachedState() -> KeyCache {+ self.cacheLock.lock()+ defer { self.cacheLock.unlock() }+ return self.keyCache+ }++ private func setCachedKeys(_ keys: [String: String]) {+ self.cacheLock.lock()+ self.keyCache = .loaded(keys)+ self.cacheLock.unlock()+ }+private func aggregatedQuery() -> [String: Any] {[kSecClass as String: kSecClassGenericPassword,diff --git a/Sources/Fluid/Persistence/TranscriptionHistoryDatabase.swift b/Sources/Fluid/Persistence/TranscriptionHistoryDatabase.swiftnew file mode 100644index 00000000..8c4d7249--- /dev/null+++ b/Sources/Fluid/Persistence/TranscriptionHistoryDatabase.swift@@ -0,0 +1,203 @@+import Foundation+import SQLite3++/// Owned by the history writer's serial queue. One JSON payload per entry, not per history.+final class TranscriptionHistoryDatabase {+ struct Record: Equatable {+ let id: UUID+ let payload: Data+ }++ private let connection: OpaquePointer++ init(url: URL) throws {+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ var handle: OpaquePointer?+ let status = sqlite3_open_v2(url.path, &handle, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX, nil)+ guard status == SQLITE_OK, let handle else {+ let message = handle.map { String(cString: sqlite3_errmsg($0)) } ?? "Could not open history."+ if let handle { sqlite3_close(handle) }+ throw NSError(domain: "HistoryDatabase", code: Int(status), userInfo: [NSLocalizedDescriptionKey: message])+ }+ self.connection = handle+ do {+ try self.execute("PRAGMA busy_timeout=2000")+ try self.execute("PRAGMA journal_mode=WAL")+ try self.execute("PRAGMA synchronous=FULL")+ try self.execute("PRAGMA secure_delete=ON")+ try self.execute("CREATE TABLE IF NOT EXISTS history (id TEXT PRIMARY KEY, payload BLOB NOT NULL)")+ try self.execute("CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY)")+ } catch {+ sqlite3_close(handle)+ throw error+ }+ }++ deinit { sqlite3_close(self.connection) }++ var isMigrated: Bool {+ get throws {+ let statement = try self.prepare("SELECT 1 FROM metadata WHERE key='legacy_imported'")+ defer { sqlite3_finalize(statement) }+ let result = sqlite3_step(statement)+ guard result == SQLITE_ROW || result == SQLITE_DONE else { throw self.error() }+ return result == SQLITE_ROW+ }+ }++ func migrate(_ records: [Record]) throws {+ guard try !self.isMigrated else { return }+ try self.transaction {+ for record in records {+ try self.upsert(record)+ }+ try self.execute("INSERT INTO metadata(key) VALUES ('legacy_imported')")+ }+ }++ func read() throws -> [Record] {+ let statement = try self.prepare("SELECT id, payload FROM history")+ defer { sqlite3_finalize(statement) }+ var records: [Record] = []+ while true {+ let result = sqlite3_step(statement)+ if result == SQLITE_DONE { return records }+ guard result == SQLITE_ROW,+ let text = sqlite3_column_text(statement, 0),+ let id = UUID(uuidString: String(cString: text)),+ let bytes = sqlite3_column_blob(statement, 1)+ else { throw self.error() }+ records.append(Record(id: id, payload: Data(bytes: bytes, count: Int(sqlite3_column_bytes(statement, 1)))))+ }+ }++ func write(upserts: [Record], deletes: [UUID], replacing: Bool) throws {+ try self.transaction {+ if replacing { try self.execute("DELETE FROM history") }+ for id in deletes {+ // UUID's canonical representation contains no SQL metacharacters.+ try self.execute("DELETE FROM history WHERE id='\(id.uuidString)'")+ }+ for record in upserts {+ try self.upsert(record)+ }+ }+ }++ private func upsert(_ record: Record) throws {+ let statement = try self.prepare("INSERT OR REPLACE INTO history(id,payload) VALUES ('\(record.id.uuidString)',?)")+ defer { sqlite3_finalize(statement) }+ let result = record.payload.withUnsafeBytes { bytes in+ sqlite3_bind_blob(statement, 1, bytes.baseAddress, Int32(bytes.count), unsafeBitCast(-1, to: sqlite3_destructor_type.self))+ }+ guard result == SQLITE_OK, sqlite3_step(statement) == SQLITE_DONE else { throw self.error() }+ }++ private func transaction(_ body: () throws -> Void) throws {+ try self.execute("BEGIN IMMEDIATE")+ do {+ try body()+ try self.execute("COMMIT")+ } catch {+ try? self.execute("ROLLBACK")+ throw error+ }+ }++ private func prepare(_ sql: String) throws -> OpaquePointer {+ var statement: OpaquePointer?+ guard sqlite3_prepare_v2(self.connection, sql, -1, &statement, nil) == SQLITE_OK, let statement else {+ throw self.error()+ }+ return statement+ }++ private func execute(_ sql: String) throws {+ guard sqlite3_exec(self.connection, sql, nil, nil, nil) == SQLITE_OK else { throw self.error() }+ }++ private func error() -> Error {+ NSError(domain: "HistoryDatabase", code: Int(sqlite3_errcode(self.connection)), userInfo: [+ NSLocalizedDescriptionKey: String(cString: sqlite3_errmsg(self.connection)),+ ])+ }+}++/// All disk queries and Codable work happen here, including the one-time legacy import.+final class TranscriptionHistoryWriter: @unchecked Sendable {+ private let queue = DispatchQueue(label: "fluid.history.persistence", qos: .utility)+ private var database: TranscriptionHistoryDatabase?+ private var writeError: Error?+ private let defaults: UserDefaults+ private let url: URL+ private let legacyKey = "TranscriptionHistoryEntries"++ init(defaults: UserDefaults = .standard, url: URL? = nil) {+ self.defaults = defaults+ self.url = url ?? URL(fileURLWithPath: NSHomeDirectory())+ .appendingPathComponent("Library/Application Support/FluidVoice/TranscriptionHistory.sqlite3")+ }++ func load() async throws -> [TranscriptionHistoryEntry] {+ try await withCheckedThrowingContinuation { continuation in+ self.queue.async {+ do {+ let database = try self.database ?? TranscriptionHistoryDatabase(url: self.url)+ self.database = database+ if try !database.isMigrated {+ let legacy = try self.defaults.data(forKey: self.legacyKey).map {+ try JSONDecoder().decode([TranscriptionHistoryEntry].self, from: $0)+ } ?? []+ try database.migrate(legacy.map { try self.record($0) })+ }+ let entries = try database.read().map {+ try JSONDecoder().decode(TranscriptionHistoryEntry.self, from: $0.payload)+ }.sorted { $0.timestamp > $1.timestamp }+ // The transaction is committed and every payload decoded before retiring legacy storage.+ self.defaults.removeObject(forKey: self.legacyKey)+ DebugLogger.shared.info("HISTORY_BENCH loaded entries=\(entries.count) storage=sqlite", source: "TranscriptionHistoryStore")+ continuation.resume(returning: entries)+ } catch {+ continuation.resume(throwing: error)+ }+ }+ }+ }++ func write(+ upserts: [TranscriptionHistoryEntry], deletes: [UUID] = [], replacing: Bool = false,+ completion: @escaping @Sendable (Error?) -> Void+ ) {+ self.queue.async {+ let startedAt = ProcessInfo.processInfo.systemUptime+ do {+ guard let database = self.database else {+ throw NSError(domain: "HistoryDatabase", code: 1, userInfo: [NSLocalizedDescriptionKey: "History is not loaded."])+ }+ let records = try upserts.map { try self.record($0) }+ try database.write(upserts: records, deletes: deletes, replacing: replacing)+ if replacing { self.writeError = nil }+ let finishedAt = ProcessInfo.processInfo.systemUptime+ DebugLogger.shared.info(+ "HISTORY_BENCH t=\(finishedAt) background=true upserts=\(upserts.count) deletes=\(deletes.count) " ++ "replace=\(replacing) bytes=\(records.reduce(0) { $0 + $1.payload.count }) totalMs=\((finishedAt - startedAt) * 1000)",+ source: "TranscriptionHistoryStore"+ )+ completion(nil)+ } catch {+ self.writeError = error+ completion(error)+ }+ }+ }++ func drain() async -> Error? {+ await withCheckedContinuation { continuation in+ self.queue.async { continuation.resume(returning: self.writeError) }+ }+ }++ private func record(_ entry: TranscriptionHistoryEntry) throws -> TranscriptionHistoryDatabase.Record {+ try TranscriptionHistoryDatabase.Record(id: entry.id, payload: JSONEncoder().encode(entry))+ }+}diff --git a/Sources/Fluid/Persistence/TranscriptionHistoryStore.swift b/Sources/Fluid/Persistence/TranscriptionHistoryStore.swiftindex 26bdf650..c5a3524d 100644--- a/Sources/Fluid/Persistence/TranscriptionHistoryStore.swift+++ b/Sources/Fluid/Persistence/TranscriptionHistoryStore.swift@@ -5,12 +5,22 @@// Persistence manager for Transcription Mode history//+import AppKitimport Combineimport Foundation+nonisolated struct AudioBudgetMeasurementGate: Equatable, Sendable {+ let revision: UInt64+ let budgetBytes: Int64++ func accepts(currentRevision: UInt64, currentBudgetBytes: Int64) -> Bool {+ self.revision == currentRevision && self.budgetBytes == currentBudgetBytes+ }+}+// MARK: - Transcription History Entry Model-struct TranscriptionHistoryEntry: Codable, Identifiable, Equatable {+struct TranscriptionHistoryEntry: Codable, Identifiable, Equatable, Sendable {let id: UUIDlet timestamp: Datelet rawText: String@@ -199,19 +209,48 @@ struct TranscriptionHistoryEntry: Codable, Identifiable, Equatable {final class TranscriptionHistoryStore: ObservableObject {static let shared = TranscriptionHistoryStore()- private let defaults = UserDefaults.standard-- private enum Keys {- static let transcriptionHistory = "TranscriptionHistoryEntries"- }+ private let writer: TranscriptionHistoryWriter+ private var loadTask: Task<Void, Never>?+ private var hasLoaded = false+ private var pendingUpserts: [UUID: TranscriptionHistoryEntry] = [:]+ private var pendingDeletes: Set<UUID> = []+ private var pendingReplacement = false+ @Published private(set) var isLoading = true+ @Published private(set) var persistenceError: String?@Published private(set) var entries: [TranscriptionHistoryEntry] = []@Published var selectedEntryID: UUID?+ /// Last completed snapshot while a coalesced background refresh is pending.+ /// Rendering must never scan history or schedule work.+ @Published private(set) var todaySummary = TodaySummary(words: 0, transcriptions: 0)+ private var todaySummaryTask: Task<Void, Never>?+ private var todaySummaryRevision: UInt64 = 0+ private var todaySummaryDay: DateInterval?+ private var audioBudgetRevision: UInt64 = 0+ private var automaticAudioBudgetTask: Task<Void, Never>?+ private(set) var audioSaveGeneration: UInt64 = 0+ private var calendarObservers: [NSObjectProtocol] = []+ private let summaryNow: () -> Date+ private let summaryCalendar: () -> Calendar- private init() {+ init(+ writer: TranscriptionHistoryWriter = TranscriptionHistoryWriter(),+ summaryNow: @escaping () -> Date = Date.init,+ summaryCalendar: @escaping () -> Calendar = { Calendar.current }+ ) {+ self.writer = writer+ self.summaryNow = summaryNow+ self.summaryCalendar = summaryCalendar+ self.observeSummaryCalendarChanges()self.loadEntries()}+ deinit {+ for observer in self.calendarObservers {+ NotificationCenter.default.removeObserver(observer)+ }+ }+// MARK: - Public Methods/// Get selected entry@@ -261,10 +300,11 @@ final class TranscriptionHistoryStore: ObservableObject {// Insert at beginning (newest first)self.entries.insert(entry, at: 0)+ self.refreshTodaySummary()- self.saveEntries()+ self.persist(upserts: [entry])if audio != nil {- self.pruneAudioToBudget()+ self.scheduleAutomaticAudioPruneToBudget()}DebugLogger.shared.debug("Added transcription to history (total: \(self.entries.count))", source: "TranscriptionHistoryStore")@@ -272,41 +312,54 @@ final class TranscriptionHistoryStore: ObservableObject {/// Delete a specific entryfunc deleteEntry(id: UUID) {+ self.invalidateAutomaticAudioBudgetMeasurement()if let audio = self.entries.first(where: { $0.id == id })?.audio {DictationAudioHistoryStore.shared.deleteAudio(fileName: audio.fileName)}+ let previousCount = self.entries.countself.entries.removeAll { $0.id == id }+ if self.entries.count != previousCount {+ self.refreshTodaySummary()+ }// Clear selection if deletedif self.selectedEntryID == id {self.selectedEntryID = self.entries.first?.id}- self.saveEntries()+ self.persist(deletes: [id])}/// Delete multiple entriesfunc deleteEntries(ids: Set<UUID>) {+ self.invalidateAutomaticAudioBudgetMeasurement()for entry in self.entries where ids.contains(entry.id) {if let audio = entry.audio {DictationAudioHistoryStore.shared.deleteAudio(fileName: audio.fileName)}}+ let previousCount = self.entries.countself.entries.removeAll { ids.contains($0.id) }+ if self.entries.count != previousCount {+ self.refreshTodaySummary()+ }if let selected = selectedEntryID, ids.contains(selected) {self.selectedEntryID = self.entries.first?.id}- self.saveEntries()+ self.persist(deletes: Array(ids))}/// Clear all historyfunc clearAllHistory() {+ self.audioSaveGeneration &+= 1+ self.invalidateAutomaticAudioBudgetMeasurement()DictationAudioHistoryStore.shared.deleteAllAudioFiles()self.entries.removeAll()+ self.refreshTodaySummary()self.selectedEntryID = nil- self.saveEntries()+ self.persist(replacing: true)DebugLogger.shared.info("Cleared all transcription history", source: "TranscriptionHistoryStore")}@@ -346,39 +399,62 @@ final class TranscriptionHistoryStore: ObservableObject {}func restore(from payload: [TranscriptionHistoryEntry]) {+ self.audioSaveGeneration &+= 1+ self.invalidateAutomaticAudioBudgetMeasurement()self.entries = payload.sorted { $0.timestamp > $1.timestamp }+ self.refreshTodaySummary()self.selectedEntryID = self.entries.first?.id- self.saveEntries()+ self.persist(upserts: self.entries, replacing: true)}- func attachAudio(_ audio: DictationAudioMetadata, to entryID: UUID) {+ func attachAudio(+ _ audio: DictationAudioMetadata,+ to entryID: UUID,+ expectedSaveGeneration: UInt64? = nil+ ) {+ if let expectedSaveGeneration, expectedSaveGeneration != self.audioSaveGeneration {+ DictationAudioHistoryStore.shared.deleteAudio(fileName: audio.fileName)+ return+ }guard let index = self.entries.firstIndex(where: { $0.id == entryID }) else {DictationAudioHistoryStore.shared.deleteAudio(fileName: audio.fileName)return}self.entries[index] = self.entries[index].replacingAudio(audio)- self.saveEntries()- self.pruneAudioToBudget()+ self.persist(upserts: [self.entries[index]])+ self.scheduleAutomaticAudioPruneToBudget()}@discardableResultfunc deleteAllSavedAudio() -> Int {+ guard self.hasLoaded else { return 0 }+ self.audioSaveGeneration &+= 1+ self.invalidateAutomaticAudioBudgetMeasurement()let removedCount = self.entries.filter { $0.audio != nil }.countDictationAudioHistoryStore.shared.deleteAllAudioFiles()+ let changed = self.entries.filter { $0.audio != nil }.map { $0.replacingAudio(nil) }self.entries = self.entries.map { $0.replacingAudio(nil) }- self.saveEntries()+ self.persist(upserts: changed)DebugLogger.shared.info("Deleted saved dictation audio (\(removedCount) entries)", source: "TranscriptionHistoryStore")return removedCount}@discardableResultfunc pruneAudioToBudget() -> Int {+ // An incomplete startup snapshot must never classify older recordings as orphaned.+ guard self.hasLoaded else { return 0 }+ self.invalidateAutomaticAudioBudgetMeasurement()let budgetBytes = SettingsStore.shared.audioHistoryBudgetBytes+ let currentBytes = DictationAudioHistoryStore.shared.audioUsageBytes()+ return self.pruneAudioToBudget(currentBytes: currentBytes, budgetBytes: budgetBytes)+ }++ private func pruneAudioToBudget(currentBytes initialCurrentBytes: Int64, budgetBytes: Int64) -> Int {guard budgetBytes > 0 else {return self.deleteAllSavedAudio()}- var currentBytes = DictationAudioHistoryStore.shared.audioUsageBytes()+ var currentBytes = initialCurrentBytesguard currentBytes > budgetBytes else { return 0 }var updatedEntries = self.entries@@ -391,11 +467,13 @@ final class TranscriptionHistoryStore: ObservableObject {guard currentBytes > budgetBytes else { return 0 }var prunedCount = 0+ var changed: [TranscriptionHistoryEntry] = []for index in updatedEntries.indices.reversed() {guard let audio = updatedEntries[index].audio else { continue }let removedBytes = DictationAudioHistoryStore.shared.deleteAudio(fileName: audio.fileName)currentBytes = max(0, currentBytes - removedBytes)updatedEntries[index] = updatedEntries[index].replacingAudio(nil)+ changed.append(updatedEntries[index])prunedCount += 1if currentBytes <= budgetBytes {break@@ -404,36 +482,201 @@ final class TranscriptionHistoryStore: ObservableObject {if prunedCount > 0 {self.entries = updatedEntries- self.saveEntries()+ self.persist(upserts: changed)DebugLogger.shared.info("Pruned saved dictation audio (\(prunedCount) entries)", source: "TranscriptionHistoryStore")}return prunedCount}+ private func invalidateAutomaticAudioBudgetMeasurement() {+ self.audioBudgetRevision &+= 1+ }++ private func scheduleAutomaticAudioPruneToBudget() {+ self.audioBudgetRevision &+= 1+ guard self.hasLoaded, self.automaticAudioBudgetTask == nil else { return }++ self.automaticAudioBudgetTask = Task { @MainActor [weak self] in+ guard let self else { return }+ while true {+ let gate = AudioBudgetMeasurementGate(+ revision: self.audioBudgetRevision,+ budgetBytes: SettingsStore.shared.audioHistoryBudgetBytes+ )+ let currentBytes = await Task.detached(priority: .utility) {+ DictationAudioHistoryStore.shared.audioUsageBytes()+ }.value+ guard gate.accepts(+ currentRevision: self.audioBudgetRevision,+ currentBudgetBytes: SettingsStore.shared.audioHistoryBudgetBytes+ ) else {+ continue+ }++ _ = self.pruneAudioToBudget(+ currentBytes: currentBytes,+ budgetBytes: gate.budgetBytes+ )+ self.automaticAudioBudgetTask = nil+ return+ }+ }+ }+// MARK: - Private Methodsprivate func loadEntries() {- guard let data = defaults.data(forKey: Keys.transcriptionHistory),- let decoded = try? JSONDecoder().decode([TranscriptionHistoryEntry].self, from: data)- else {- self.entries = []+ self.isLoading = true+ self.loadTask = Task { @MainActor in+ do {+ let loaded = try await self.writer.load()+ var merged = self.pendingReplacement ? [] : loaded.filter { !self.pendingDeletes.contains($0.id) && self.pendingUpserts[$0.id] == nil }+ merged.append(contentsOf: self.pendingUpserts.values)+ self.entries = merged.sorted { $0.timestamp > $1.timestamp }+ self.refreshTodaySummary()+ self.hasLoaded = true+ self.persistenceError = nil+ if self.pendingReplacement || !self.pendingUpserts.isEmpty || !self.pendingDeletes.isEmpty {+ self.persist(upserts: Array(self.pendingUpserts.values), deletes: Array(self.pendingDeletes), replacing: self.pendingReplacement)+ }+ self.pendingUpserts.removeAll()+ self.pendingDeletes.removeAll()+ self.pendingReplacement = false+ } catch {+ self.persistenceError = "History could not be loaded. New dictations are kept in memory until you retry. \(error.localizedDescription)"+ }+ self.isLoading = false+ }+ }++ /// Only immutable changed entries cross to the writer. No full-history encoding on the main actor.+ private func persist(upserts: [TranscriptionHistoryEntry] = [], deletes: [UUID] = [], replacing: Bool = false) {+ let startedAt = ProcessInfo.processInfo.systemUptime+ guard self.hasLoaded else {+ if replacing {+ self.pendingReplacement = true+ self.pendingUpserts.removeAll()+ self.pendingDeletes.removeAll()+ }+ for id in deletes {+ self.pendingUpserts.removeValue(forKey: id)+ self.pendingDeletes.insert(id)+ }+ for entry in upserts {+ self.pendingDeletes.remove(entry.id)+ self.pendingUpserts[entry.id] = entry+ }+ return+ }+ self.writer.write(upserts: upserts, deletes: deletes, replacing: replacing) { error in+ guard let error else { return }+ Task { @MainActor in+ self.persistenceError = "History could not be saved. Keep FluidVoice open and retry. \(error.localizedDescription)"+ }+ }+ DebugLogger.shared.info(+ "HISTORY_BENCH enqueueMs=\((ProcessInfo.processInfo.systemUptime - startedAt) * 1000) upserts=\(upserts.count) deletes=\(deletes.count)",+ source: "TranscriptionHistoryStore"+ )+ }++ func retryPersistence() {+ guard !self.isLoading else { return }+ guard self.hasLoaded else {+ self.loadEntries()return}- self.entries = decoded+ self.writer.write(upserts: self.entries, replacing: true) { error in+ Task { @MainActor in+ self.persistenceError = error.map { "History could not be saved. \($0.localizedDescription)" }+ }+ }+ }++ func waitUntilLoaded() async throws {+ await self.loadTask?.value+ guard self.hasLoaded else {+ throw NSError(domain: "HistoryPersistence", code: 1, userInfo: [NSLocalizedDescriptionKey: self.persistenceError ?? "History is unavailable."])+ }+ }++ func finishPendingWrites() async {+ await self.loadTask?.value+ if let error = await self.writer.drain() {+ self.persistenceError = "History could not be saved. Keep FluidVoice open and retry. \(error.localizedDescription)"+ }}- private func saveEntries() {- if let encoded = try? JSONEncoder().encode(entries) {- self.defaults.set(encoded, forKey: Keys.transcriptionHistory)+ // MARK: - Event-driven Today Snapshot++ private func observeSummaryCalendarChanges() {+ let names: [Notification.Name] = [+ .NSCalendarDayChanged, .NSSystemTimeZoneDidChange, .NSSystemClockDidChange,+ NSLocale.currentLocaleDidChangeNotification, NSApplication.didBecomeActiveNotification,+ ]+ self.calendarObservers = names.map { name in+ NotificationCenter.default.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in+ Task { @MainActor [weak self] in+ self?.refreshTodaySummaryForCalendarChange()+ }+ }}- objectWillChange.send()+ }++ func refreshTodaySummaryForCalendarChange() {+ let day = self.summaryCalendar().dateInterval(of: .day, for: self.summaryNow())+ guard day != self.todaySummaryDay else { return }+ self.refreshTodaySummary()+ }++ private func refreshTodaySummary() {+ self.todaySummaryRevision &+= 1+ guard self.todaySummaryTask == nil else { return }+ self.todaySummaryTask = Task { @MainActor [weak self] in+ // Coalesce synchronous load/restore/delete bursts into one immutable snapshot.+ await Task.yield()+ guard let self else { return }+ while true {+ let revision = self.todaySummaryRevision+ let day = self.summaryCalendar().dateInterval(of: .day, for: self.summaryNow())+ let snapshot = self.entries+ let summary = await Task.detached(priority: .utility) {+ Self.calculateTodaySummary(entries: snapshot, day: day)+ }.value+ guard revision == self.todaySummaryRevision,+ day == self.summaryCalendar().dateInterval(of: .day, for: self.summaryNow())+ else { continue }+ self.todaySummaryDay = day+ if self.todaySummary != summary {+ self.todaySummary = summary+ }+ // Published subscribers may synchronously mutate history again.+ guard revision == self.todaySummaryRevision else { continue }+ self.todaySummaryTask = nil+ return+ }+ }+ }++ func waitForTodaySummary() async {+ await self.todaySummaryTask?.value+ }++ private nonisolated static func calculateTodaySummary(entries: [TranscriptionHistoryEntry], day: DateInterval?) -> TodaySummary {+ guard let day else { return TodaySummary(words: 0, transcriptions: 0) }+ let totals = entries.reduce(into: (words: 0, transcriptions: 0)) { result, entry in+ guard entry.timestamp >= day.start, entry.timestamp < day.end else { return }+ result.words += Self.countWords(in: entry.processedText)+ result.transcriptions += 1+ }+ return TodaySummary(words: totals.words, transcriptions: totals.transcriptions)}}// MARK: - Stats Computation Extensionextension TranscriptionHistoryStore {- struct TodaySummary {+ nonisolated struct TodaySummary: Equatable, Sendable {let words: Intlet transcriptions: Int@@ -469,6 +712,10 @@ extension TranscriptionHistoryStore {/// Count words in a string (handles multiple spaces, newlines)private func wordCount(in text: String) -> Int {+ Self.countWords(in: text)+ }++ private nonisolated static func countWords(in text: String) -> Int {let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)guard !trimmed.isEmpty else { return 0 }@@ -482,18 +729,6 @@ extension TranscriptionHistoryStore {self.entries.reduce(0) { $0 + self.wordCount(in: $1.processedText) }}- /// Summary for today's activity, calculated in one pass.- var todaySummary: TodaySummary {- let calendar = Calendar.current- let today = calendar.startOfDay(for: Date())- let totals = self.entries.reduce(into: (words: 0, transcriptions: 0)) { result, entry in- guard calendar.isDate(entry.timestamp, inSameDayAs: today) else { return }- result.words += self.wordCount(in: entry.processedText)- result.transcriptions += 1- }- return TodaySummary(words: totals.words, transcriptions: totals.transcriptions)- }-/// Words transcribed todayvar wordsToday: Int {self.todaySummary.wordsdiff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swiftindex c8dfa708..6a930f0a 100644--- a/Sources/Fluid/Services/ASRService.swift+++ b/Sources/Fluid/Services/ASRService.swift@@ -15,11 +15,14 @@ private actor TranscriptionExecutor {private var lastTask: Task<Void, Never>?private var operationCancellations: [UUID: () -> Void] = [:]- func run<T>(_ operation: @escaping () async throws -> T) async throws -> T {+ func run<T>(benchmarkSessionID: Int? = nil, _ operation: @escaping () async throws -> T) async throws -> T {+ logTranscriptionExecutorPhase("entered", sessionID: benchmarkSessionID)let previous = self.lastTasklet operationID = UUID()let task = Task<T, Error> {+ logTranscriptionExecutorPhase("task_started", sessionID: benchmarkSessionID)_ = await previous?.result+ logTranscriptionExecutorPhase("previous_finished", sessionID: benchmarkSessionID)try Task.checkCancellation()return try await operation()}@@ -39,6 +42,300 @@ private actor TranscriptionExecutor {}}+private nonisolated func logTranscriptionExecutorPhase(_ phase: String, sessionID: Int?) {+ guard let sessionID else { return }+ let timestamp = ProcessInfo.processInfo.systemUptime+ DebugLogger.shared.info(+ "ASR_BENCH t=\(timestamp) session=\(sessionID) final_queue_\(phase) mainThread=\(Thread.isMainThread)",+ source: "ASRBenchmark"+ )+}++private nonisolated func logStreamingProviderOperationReturn(+ sessionID: Int,+ operationID: UUID,+ route: String+) {+ let returnedAt = ProcessInfo.processInfo.systemUptime+ DebugLogger.shared.info(+ "ASR_BENCH t=\(returnedAt) streaming_provider_operation_return " ++ "session=\(sessionID) operation=\(operationID.uuidString) route=\(route)",+ source: "ASRBenchmark"+ )+}++/// Keeps a stop-state UI refresh from entering the main-actor queue ahead of+/// final transcription. The owner must always finish the gate; repeated finishes+/// are harmless so early-return paths can share one cleanup.+struct ASRStopUIInvalidationGate {+ private(set) var isDeferring = false+ private var hasOutputPipelineHold = false+ private var stopDidFinish = false++ mutating func holdForOutputPipeline() {+ self.isDeferring = true+ self.hasOutputPipelineHold = true+ }++ mutating func begin() {+ self.isDeferring = true+ }++ mutating func finish() -> Bool {+ guard self.isDeferring else { return false }+ self.stopDidFinish = true+ return self.completeIfReady()+ }++ mutating func releaseOutputPipelineHold() -> Bool {+ self.hasOutputPipelineHold = false+ guard self.stopDidFinish else {+ let wasDeferring = self.isDeferring+ self.isDeferring = false+ return wasDeferring+ }+ return self.completeIfReady()+ }++ mutating func forceFinish() -> Bool {+ self.hasOutputPipelineHold = false+ self.stopDidFinish = true+ return self.completeIfReady()+ }++ private mutating func completeIfReady() -> Bool {+ guard self.isDeferring, self.stopDidFinish, self.hasOutputPipelineHold == false else { return false }+ self.isDeferring = false+ self.stopDidFinish = false+ return true+ }+}++@MainActor+func scheduleDeferredMainActorOperation(+ afterNanoseconds delayNanoseconds: UInt64,+ shouldRun: @escaping @MainActor () -> Bool = { true },+ operation: @escaping @MainActor () -> Void+) -> Task<Void, Never> {+ Task { @MainActor in+ do {+ try await Task.sleep(nanoseconds: delayNanoseconds)+ } catch {+ return+ }+ guard Task.isCancelled == false, shouldRun() else { return }+ operation()+ }+}++/// Identifies the recording and provider generation allowed to publish a live preview.+/// Operation completion uses the narrower operation identity so stale cleanup cannot+/// clear state owned by a newer chunk.+struct StreamingTranscriptionWorkState {+ private(set) var sessionID: Int?+ private(set) var activeOperationID: UUID?+ private(set) var providerGeneration: UInt64 = 0++ mutating func beginSession(_ sessionID: Int) {+ self.sessionID = sessionID+ self.activeOperationID = nil+ }++ mutating func beginOperation(+ sessionID: Int,+ operationID: UUID+ ) -> UInt64? {+ guard self.sessionID == sessionID, self.activeOperationID == nil else { return nil }+ self.activeOperationID = operationID+ return self.providerGeneration+ }++ func ownsOperation(sessionID: Int, operationID: UUID) -> Bool {+ self.sessionID == sessionID && self.activeOperationID == operationID+ }++ func canPublish(+ sessionID: Int,+ operationID: UUID,+ providerGeneration: UInt64+ ) -> Bool {+ self.ownsOperation(sessionID: sessionID, operationID: operationID) &&+ self.providerGeneration == providerGeneration+ }++ func canPublishPreview(+ sessionID: Int,+ operationID: UUID,+ providerGeneration: UInt64,+ isRunning: Bool,+ schedulingSessionID: Int?+ ) -> Bool {+ isRunning &&+ schedulingSessionID == sessionID &&+ self.canPublish(+ sessionID: sessionID,+ operationID: operationID,+ providerGeneration: providerGeneration+ )+ }++ mutating func finishOperation(sessionID: Int, operationID: UUID) -> Bool {+ guard self.ownsOperation(sessionID: sessionID, operationID: operationID) else { return false }+ self.activeOperationID = nil+ return true+ }++ mutating func invalidateProvider() {+ self.providerGeneration &+= 1+ }++ mutating func endSession(_ sessionID: Int) {+ guard self.sessionID == sessionID, self.activeOperationID == nil else { return }+ self.sessionID = nil+ }+}++/// Blocks a new recording only while the previous recording still owns the shared PCM buffer.+/// Cancelling a pending start releases its waiter without completing the active handoff.+@MainActor+final class RecordingBufferHandoffGate {+ struct Token: Equatable {+ private let id = UUID()+ }++ private var activeToken: Token?+ private var waiters: [CheckedContinuation<Void, Never>] = []+ private(set) var isRecovering = false++ var isActive: Bool { self.activeToken != nil }+ var pendingWaiterCount: Int { self.waiters.count }++ func begin() -> Token? {+ guard self.activeToken == nil else { return nil }+ let token = Token()+ self.activeToken = token+ return token+ }++ func waitUntilAvailable() async {+ guard self.activeToken != nil else { return }+ await withCheckedContinuation { continuation in+ self.waiters.append(continuation)+ }+ }++ func releasePendingWaiters() {+ let waiters = self.waiters+ self.waiters.removeAll(keepingCapacity: false)+ waiters.forEach { $0.resume() }+ }++ func complete(_ token: Token) {+ guard self.activeToken == token else { return }+ self.activeToken = nil+ self.isRecovering = false+ self.releasePendingWaiters()+ }++ func markTimedOut(_ token: Token) {+ guard self.activeToken == token else { return }+ self.isRecovering = true+ // Wake starts already waiting so they fail visibly instead of hanging.+ self.releasePendingWaiters()+ }+}++/// Owns the cancellable idle delay separately from provider work. Normal recording+/// stop cancels only the delay; an active provider operation is allowed to settle.+@MainActor+final class StreamingTaskLifecycle {+ private var scheduler: (id: UUID, task: Task<Void, Never>)?+ private var active: (sessionID: Int, operationID: UUID, task: Task<Void, Never>)?+ private var drainWaiters: [UUID: (operationID: UUID, continuation: CheckedContinuation<Bool, Never>, timer: Task<Void, Never>)] = [:]++ var hasScheduledIdleWork: Bool { self.scheduler != nil }+ var hasActiveWork: Bool { self.active != nil }+ var pendingDrainCount: Int { self.drainWaiters.count }++ @discardableResult+ func schedule(+ sessionID: Int,+ delayNanoseconds: UInt64,+ operation: @escaping @MainActor (UUID) async -> Void,+ completion: @escaping @MainActor (UUID) -> Void+ ) -> Bool {+ guard self.scheduler == nil, self.active == nil else { return false }+ let schedulerID = UUID()+ let task = Task { @MainActor [weak self] in+ if delayNanoseconds > 0 {+ do {+ try await Task.sleep(nanoseconds: delayNanoseconds)+ } catch {+ return+ }+ }+ guard let self,+ Task.isCancelled == false,+ self.scheduler?.id == schedulerID+ else { return }++ self.scheduler = nil+ let operationID = UUID()+ let activeTask = Task { @MainActor [weak self] in+ await operation(operationID)+ guard let self,+ self.active?.sessionID == sessionID,+ self.active?.operationID == operationID+ else { return }+ self.active = nil+ completion(operationID)+ let completedWaiters = self.drainWaiters.filter { $0.value.operationID == operationID }+ for id in completedWaiters.keys {+ self.finishDrain(id: id, completed: true)+ }+ }+ self.active = (sessionID, operationID, activeTask)+ }+ self.scheduler = (schedulerID, task)+ return true+ }++ @discardableResult+ func cancelScheduler() -> Bool {+ guard let scheduler = self.scheduler else { return false }+ self.scheduler = nil+ scheduler.task.cancel()+ return true+ }++ func activeTaskToDrain(sessionID: Int) -> Task<Void, Never>? {+ guard let active = self.active, active.sessionID == sessionID else { return nil }+ return active.task+ }++ /// Deadline bounds the caller only. Never cancel or release a provider still+ /// using incremental state. Completion removes the timer; timeout removes the waiter.+ func drain(sessionID: Int, timeoutNanoseconds: UInt64) async -> Bool {+ guard let active = self.active, active.sessionID == sessionID else { return true }+ let id = UUID()+ return await withCheckedContinuation { continuation in+ let timer = Task { @MainActor [weak self] in+ do {+ try await Task.sleep(nanoseconds: timeoutNanoseconds)+ } catch { return }+ self?.finishDrain(id: id, completed: false)+ }+ self.drainWaiters[id] = (active.operationID, continuation, timer)+ }+ }++ private func finishDrain(id: UUID, completed: Bool) {+ guard let waiter = self.drainWaiters.removeValue(forKey: id) else { return }+ waiter.timer.cancel()+ waiter.continuation.resume(returning: completed)+ }+}+struct ShortAudioSilenceAssessment: Equatable {let durationMilliseconds: Intlet isEligible: Bool@@ -93,6 +390,9 @@ enum ASRStopOutcome: Equatable {/// Models are cached locally to avoid repeated downloads.@MainActorfinal class ASRService: ObservableObject {+ private static let finalTranscriptionStatusDelayNanoseconds: UInt64 = 100_000_000+ private static let streamingDrainTimeoutNanoseconds: UInt64 = 30_000_000_000+nonisolated static func shouldAssessShortAudioSilence(isEnabled: Bool,useDictionaryTrainingPath: Bool,@@ -194,7 +494,23 @@ final class ASRService: ObservableObject {@Published private(set) var isDictionaryTrainingCaptureActive: Bool = false@Published private(set) var isMicrophonePreviewActive: Bool = false@Published private(set) var microphonePreviewError: String?- @Published private(set) var audioCaptureStateSettledTick: UInt64 = 0+ /// Narrow lifecycle event used only by onboarding microphone preview.+ /// This must not invalidate every ASR-observing view after each capture.+ let audioCaptureStateDidSettle = PassthroughSubject<Void, Never>()+ let deferredStopUIInvalidationDidFlush = PassthroughSubject<Void, Never>()+ private var stopUIInvalidationGate = ASRStopUIInvalidationGate()+ private var stopUIInvalidationTimeoutTask: Task<Void, Never>?+ private var stopUIInvalidationHoldGeneration: UInt64 = 0+ private var activeStopUIInvalidationHold: UInt64?+ private var isStoppingFinalTranscription = false+ var defersStopUIInvalidation: Bool {+ self.stopUIInvalidationGate.isDeferring+ }++ var isFinalTranscriptionReady: Bool {+ self.isAsrReady && self.transcriptionProvider.isReady+ }+private var microphonePreviewOperationGeneration: UInt64 = 0private var isMicrophonePreviewRequested = falseprivate(set) var lastDictionaryTrainingResult: ASRTranscriptionResult?@@ -336,6 +652,7 @@ final class ASRService: ObservableObject {_ = await preparationTask?.result_ = await downloadTask?.resultawait self.providerResetDrain?.task.value+ self.streamingWorkState.invalidateProvider()await self.transcriptionExecutor.cancelAndAwaitPending()self.fluidAudioProvider = nil@@ -606,9 +923,16 @@ final class ASRService: ObservableObject {/// Call this when the transcription provider setting changes to reset statefunc resetTranscriptionProvider() {+ guard !self.recordingBufferHandoffGate.isRecovering else {+ self.resetProviderAfterStreamingRecovery = true+ return+ }let newModel = SettingsStore.shared.selectedSpeechModelDebugLogger.shared.info("ASRService: Switching to '\(newModel.displayName)', resetting provider state...", source: "ASRService")+ // Any in-flight preview belongs to the provider being retired. Its operation+ // still drains through the executor, but must not publish into this session.+ self.streamingWorkState.invalidateProvider()self.isAsrReady = falseself.modelsExistOnDisk = falseself.isLoadingModel = false@@ -1106,7 +1430,14 @@ final class ASRService: ObservableObject {private var lastCompletedAudioSnapshot: DictationAudioSnapshot?// Streaming transcription state (no VAD)- private var streamingTask: Task<Void, Never>?+ private let streamingTaskLifecycle = StreamingTaskLifecycle()+ private var streamingWorkState = StreamingTranscriptionWorkState()+ private var streamingSchedulingSessionID: Int?+ private let recordingBufferHandoffGate = RecordingBufferHandoffGate()+ private var timedOutStreamingHandoff: (sessionID: Int, token: RecordingBufferHandoffGate.Token)?+ private var resetProviderAfterStreamingRecovery = false+ private var streamingHealthCheckCount: Int = 0+ private var streamingHealthLastBufferCount: Int = 0private var lastProcessedSampleCount: Int = 0private var isProcessingChunk: Bool = falseprivate var skipNextChunk: Bool = false@@ -1199,7 +1530,10 @@ final class ASRService: ObservableObject {onCaptureHealth: { [weak self] sessionID, attemptID, audioMs, sampleCount, rms, peak inDispatchQueue.main.async { [weak self] inguard let self else { return }- guard sessionID == self.benchmarkSessionID, self.isRunning else { return }+ guard sessionID == self.benchmarkSessionID,+ self.isRunning,+ self.isStoppingFinalTranscription == false+ else { return }let silent = rms < 0.002 && peak < 0.01self.benchmarkLog("capture_health attempt=\(attemptID) audioMs=\(audioMs) " +@@ -1730,6 +2064,10 @@ final class ASRService: ObservableObject {DebugLogger.shared.error("❌ START() blocked - mic not authorized", source: "ASRService")return .failed}+ guard !self.recordingBufferHandoffGate.isRecovering else {+ self.presentStreamingRecoveryError()+ return .failed+ }guard self.isRunning == false, self.isStarting == false else {DebugLogger.shared.warning("⚠️ START() blocked - already running (started: \(self.isRunning), starting: \(self.isStarting))", source: "ASRService")return .alreadyActive@@ -1743,6 +2081,26 @@ final class ASRService: ObservableObject {self.isStarting = truedefer { self.finishAudioCaptureStart() }+ // A prior stop may already have disabled capture while its final live-preview+ // operation still owns the shared PCM buffer. Reserve this start immediately,+ // but do not clear or enable the buffer until that bounded handoff completes.+ while self.recordingBufferHandoffGate.isActive {+ await self.recordingBufferHandoffGate.waitUntilAvailable()+ guard !self.recordingBufferHandoffGate.isRecovering else {+ self.presentStreamingRecoveryError()+ return .failed+ }+ guard startGeneration == self.audioCaptureStartGeneration,+ self.isTerminating == false+ else {+ DebugLogger.shared.debug(+ "Audio capture start cancelled while waiting for the previous buffer handoff",+ source: "ASRService"+ )+ return .failed+ }+ }+// Reserve the start before relinquishing preview ownership so a// press-and-hold release can cancel the handoff. Keep the running input// alive; startConfiguredAudioCapture reuses it for zero-stop first PCM.@@ -1776,6 +2134,9 @@ final class ASRService: ObservableObject {self.isProcessingChunk = falseself.skipNextChunk = falseself.benchmarkSessionID += 1+ self.streamingWorkState.beginSession(self.benchmarkSessionID)+ self.streamingHealthCheckCount = 0+ self.streamingHealthLastBufferCount = 0self.silentPCMRecoveryWatchdog = AudioCaptureIdlePolicy.SilentPCMRecoveryWatchdog()let captureSessionID = self.benchmarkSessionIDself.audioCaptureAttemptID &+= 1@@ -2003,7 +2364,7 @@ final class ASRService: ObservableObject {// handled explicitly below.if SettingsStore.shared.pauseMediaDuringTranscription {let didPause = await MediaPlaybackService.shared.pauseIfPlaying()- guard self.isRunning else {+ guard self.isRunning, self.isStoppingFinalTranscription == false else {if didPause {await MediaPlaybackService.shared.resumeIfWePaused(true)}@@ -2202,6 +2563,9 @@ final class ASRService: ObservableObject {func cancelPendingAudioCaptureStart(reason: String) async {guard self.isStarting, self.isRunning == false else { return }self.audioCaptureStartGeneration &+= 1+ // A start waiting for the previous session's PCM handoff must wake to+ // observe the generation change; the old stop keeps ownership of the gate.+ self.recordingBufferHandoffGate.releasePendingWaiters()let cancelledSessionID = self.benchmarkSessionIDself.benchmarkLog("capture_start_cancel reason=\(reason) session=\(cancelledSessionID) " +@@ -2217,7 +2581,7 @@ final class ASRService: ObservableObject {private func finishAudioCaptureStart() {self.isStarting = falselet deferredRecovery = self.deferredBluetoothStartupRouteRecovery.take()- self.audioCaptureStateSettledTick &+= 1+ self.audioCaptureStateDidSettle.send()let waiters = self.audioCaptureStartWaitersself.audioCaptureStartWaiters.removeAll(keepingCapacity: false)waiters.forEach { $0.resume() }@@ -2328,8 +2692,12 @@ final class ASRService: ObservableObject {/// final transcription pass. Use this for immediate stop cues that/// shouldn't wait on finalization. Only invoked when capture was actually/// running (i.e. not when `stop()` early-returns because `isRunning` is false).+ /// - Parameter onFinalTranscriptionStarted: Optional main-actor callback+ /// shown only when final transcription outlives the short status delay.+ /// Fast finalization proceeds without queuing transient UI work ahead of its result.func stop(onCaptureStopped: (@MainActor () -> Void)? = nil,+ onFinalTranscriptionStarted: (@MainActor () -> Void)? = nil,forDictionaryTraining: Bool = false) async -> String {DebugLogger.shared.info("🛑 STOP() called - beginning shutdown sequence", source: "ASRService")@@ -2350,6 +2718,24 @@ final class ASRService: ObservableObject {DebugLogger.shared.warning("⚠️ STOP() - not running, returning empty string", source: "ASRService")return ""}+ let stoppingSessionID = self.benchmarkSessionID+ guard let bufferHandoffToken = self.recordingBufferHandoffGate.begin() else {+ DebugLogger.shared.warning("STOP() ignored - recording buffer handoff already active", source: "ASRService")+ return ""+ }+ self.isStoppingFinalTranscription = true+ var completedBufferHandoff = false+ defer {+ if completedBufferHandoff == false {+ self.recordingBufferHandoffGate.complete(bufferHandoffToken)+ }+ self.publishStoppedState(for: stoppingSessionID)+ self.finishDeferredStopUIInvalidation()+ if self.benchmarkSessionID == stoppingSessionID {+ self.isStoppingFinalTranscription = false+ }+ }+ self.stopStreamingScheduler(sessionID: stoppingSessionID)let useDictionaryTrainingPath = forDictionaryTraining || self.isDictionaryTrainingCaptureActivedefer {self.applyPendingParakeetVocabularyReloadIfNeeded()@@ -2357,6 +2743,11 @@ final class ASRService: ObservableObject {}await self.cancelAudioRouteRecoveryAndWait()+ guard self.isRunning, self.benchmarkSessionID == stoppingSessionID else {+ self.recordingBufferHandoffGate.complete(bufferHandoffToken)+ completedBufferHandoff = true+ return ""+ }// Capture media pause state before we reset it, for resuming at the endlet shouldResumeMedia = self.didPauseMediaForThisSession@@ -2370,19 +2761,16 @@ final class ASRService: ObservableObject {// without appending audio from the next session.self.audioCapturePipeline.markRecordingEnd(atHostTime: mach_absolute_time())- // Set isRunning to false before teardown so in-flight ASR chunks stop safely.- DebugLogger.shared.debug("🚫 Setting isRunning = false...", source: "ASRService")- self.isRunning = false- DebugLogger.shared.debug("✅ isRunning disabled", source: "ASRService")-// Stop monitoring device to prevent callbacks after stopDebugLogger.shared.debug("👁️ Stopping device monitoring...", source: "ASRService")self.stopMonitoringDevice()DebugLogger.shared.debug("✅ Device monitoring stopped", source: "ASRService")+ self.benchmarkLog("capture_stop_await_begin")await self.stopActiveAudioCapture(reason: "recording_stop")+ self.benchmarkLog("capture_stop_await_return")self.audioCapturePipeline.finishRecording()- self.audioCaptureStateSettledTick &+= 1+ self.benchmarkLog("capture_pipeline_finished")// A prepared direct IOProc owns only fixed memory and registration; it// does not run hardware, show the mic indicator, or hold Bluetooth in@@ -2402,7 +2790,13 @@ final class ASRService: ObservableObject {// Capture has fully ended — invoke the callback so callers can play a// stop cue or release capture-dependent UI without waiting on the// (potentially slow) final transcription pass.- await MainActor.run { onCaptureStopped?() }+ self.benchmarkLog("capture_stopped_callback_request")+ // stop() is MainActor-isolated; calling directly avoids needlessly+ // yielding and re-enqueuing this callback behind unrelated UI work.+ self.benchmarkLog("capture_stopped_callback_begin")+ onCaptureStopped?()+ self.benchmarkLog("capture_stopped_callback_end")+ self.benchmarkLog("capture_stopped_callback_return")let directCaptureSnapshot = self.directAudioLifecycleController.snapshotself.benchmarkLog(@@ -2410,13 +2804,21 @@ final class ASRService: ObservableObject {"phase=\(directCaptureSnapshot.phase.rawValue) generation=\(directCaptureSnapshot.generation)")- // CRITICAL FIX: Await completion of streaming task AND any pending transcriptions- // This prevents use-after-free crashes (EXC_BAD_ACCESS) when clearing buffer- DebugLogger.shared.debug("⏳ Awaiting stopStreamingTimerAndAwait()...", source: "ASRService")+ // The idle scheduler was cancelled before teardown. Only real provider work+ // can still own the PCM buffer here, so drain that operation without sending+ // cancellation into incremental provider state.+ DebugLogger.shared.debug("⏳ Awaiting active streaming work...", source: "ASRService")let streamingStopStartedAt = Date().timeIntervalSince1970- await self.stopStreamingTimerAndAwait()+ guard await self.drainActiveStreamingWork(sessionID: stoppingSessionID) else {+ self.beginStreamingDrainRecovery(sessionID: stoppingSessionID, token: bufferHandoffToken)+ completedBufferHandoff = true // Recovery owns the PCM handoff until real work ends.+ self.lastStopOutcome = .failed+ if shouldResumeMedia { await MediaPlaybackService.shared.resumeIfWePaused(true) }+ self.benchmarkLog("stop_end result=error reason=streaming_drain_timeout")+ return ""+ }self.benchmarkLog("stop_streaming_wait elapsedMs=\(self.elapsedMilliseconds(since: streamingStopStartedAt))")- DebugLogger.shared.debug("✅ stopStreamingTimerAndAwait() completed", source: "ASRService")+ DebugLogger.shared.debug("✅ Active streaming work completed", source: "ASRService")self.isProcessingChunk = falseself.skipNextChunk = false@@ -2427,6 +2829,12 @@ final class ASRService: ObservableObject {var pcm = self.audioBuffer.getAll()self.audioBuffer.clear()let capturedPCM = pcm+ let hasRecognizedStreamingPreview = !self.partialTranscription+ .trimmingCharacters(in: .whitespacesAndNewlines)+ .isEmpty+ self.streamingWorkState.endSession(stoppingSessionID)+ self.recordingBufferHandoffGate.complete(bufferHandoffToken)+ completedBufferHandoff = trueself.benchmarkLog("stop_audio_drained samples=\(pcm.count) audioMs=\(Int((Double(pcm.count) / 16_000.0 * 1000).rounded()))")// Drop recordings with no audio at all — nothing to transcribe.@@ -2447,9 +2855,6 @@ final class ASRService: ObservableObject {return ""}- let hasRecognizedStreamingPreview = !self.partialTranscription- .trimmingCharacters(in: .whitespacesAndNewlines)- .isEmptyif Self.shouldAssessShortAudioSilence(isEnabled: SettingsStore.shared.skipSilentRecordingsEnabled,useDictionaryTrainingPath: useDictionaryTrainingPath,@@ -2507,6 +2912,7 @@ final class ASRService: ObservableObject {if self.isAsrReady, provider.isReady {self.benchmarkLog("stop_ensure_ready skipped=true elapsedMs=0")} else {+ self.publishStoppedState(for: stoppingSessionID)DebugLogger.shared.debug("🔍 Calling ensureAsrReady()...", source: "ASRService")try await self.ensureAsrReady()provider = self.transcriptionProvider@@ -2532,14 +2938,42 @@ final class ASRService: ObservableObject {let finalSource: Stringif useDictionaryTrainingPath {result = try await self.transcriptionExecutor.run { [provider] in- try await provider.transcribeDictionaryTraining(pcm)+ self.publishStoppedState(for: stoppingSessionID)+ return try await provider.transcribeDictionaryTraining(pcm)}self.lastDictionaryTrainingResult = resultfinalSource = "dictionaryTraining"} else {- result = try await self.transcriptionExecutor.run { [provider] in- try await provider.transcribeFinal(pcm)+ let vocabularyProvider = provider as? FluidAudioProvider+ self.benchmarkLog(+ "final_executor_request model=\(SettingsStore.shared.selectedSpeechModel.rawValue) " ++ "samples=\(pcm.count) vocabEnabled=\(vocabularyProvider?.isWordBoostingActive == true) " ++ "vocabTerms=\(vocabularyProvider?.boostedVocabularyTermsCount ?? 0)"+ )+ let delayedFinalStatusTask = scheduleDeferredMainActorOperation(+ afterNanoseconds: Self.finalTranscriptionStatusDelayNanoseconds,+ shouldRun: { [weak self] in self?.benchmarkSessionID == stoppingSessionID }+ ) { [weak self] in+ guard let self else { return }+ self.publishStoppedState(for: stoppingSessionID)+ if let onFinalTranscriptionStarted {+ self.benchmarkLog("final_started_callback_begin trigger=delayed_status")+ onFinalTranscriptionStarted()+ self.benchmarkLog("final_started_callback_end trigger=delayed_status")+ }+ }+ defer { delayedFinalStatusTask.cancel() }+ result = try await self.transcriptionExecutor.run(benchmarkSessionID: self.benchmarkSessionID) { [provider] in+ let executionStartedAt = ProcessInfo.processInfo.systemUptime+ DebugLogger.shared.info("ASR_BENCH t=\(executionStartedAt) final_executor_begin mainThread=\(Thread.isMainThread)", source: "ASRBenchmark")+ defer {+ DebugLogger.shared.info("ASR_BENCH t=\(ProcessInfo.processInfo.systemUptime) final_executor_end", source: "ASRBenchmark")+ }+ return try await provider.transcribeFinal(pcm)}+ delayedFinalStatusTask.cancel()+ self.publishStoppedState(for: stoppingSessionID)+ self.benchmarkLog("final_executor_return")finalSource = "full"}let finalElapsedMs = self.elapsedMilliseconds(since: finalStartedAt)@@ -2642,6 +3076,71 @@ final class ASRService: ObservableObject {}}+ private func beginDeferredStopUIInvalidation() {+ self.stopUIInvalidationGate.begin()+ self.stopUIInvalidationTimeoutTask?.cancel()+ self.stopUIInvalidationTimeoutTask = Task { @MainActor [weak self] in+ try? await Task.sleep(nanoseconds: 1_000_000_000)+ guard Task.isCancelled == false else { return }+ self?.forceFinishDeferredStopUIInvalidation()+ }+ }++ /// Keeps whole-view invalidation from rebuilding SwiftUI between final ASR+ /// and output dispatch. The generation makes stale pipeline cleanup harmless.+ func holdStopUIInvalidationForOutputPipeline() -> UInt64 {+ self.stopUIInvalidationHoldGeneration &+= 1+ let generation = self.stopUIInvalidationHoldGeneration+ self.activeStopUIInvalidationHold = generation+ self.stopUIInvalidationGate.holdForOutputPipeline()+ return generation+ }++ func releaseStopUIInvalidationForOutputPipeline(_ generation: UInt64) {+ guard self.activeStopUIInvalidationHold == generation else { return }+ self.activeStopUIInvalidationHold = nil+ self.flushDeferredStopUIInvalidation(+ shouldFlush: self.stopUIInvalidationGate.releaseOutputPipelineHold()+ )+ }++ /// Publishes the stopped state only after final ASR has entered its+ /// executor. Streaming ownership is revoked earlier by the scheduler and+ /// buffer handoff gates, so this keeps SwiftUI work off hardware teardown.+ private func publishStoppedState(for sessionID: Int) {+ guard self.benchmarkSessionID == sessionID, self.isRunning else { return }+ DebugLogger.shared.debug("🚫 Publishing isRunning = false...", source: "ASRService")+ self.beginDeferredStopUIInvalidation()+ self.isRunning = false+ self.isStoppingFinalTranscription = false+ DebugLogger.shared.debug("✅ isRunning disabled", source: "ASRService")+ Task { @MainActor [weak self] in+ await Task.yield()+ guard let self,+ self.benchmarkSessionID == sessionID,+ self.isRunning == false+ else { return }+ self.audioCaptureStateDidSettle.send()+ }+ }++ private func finishDeferredStopUIInvalidation() {+ self.flushDeferredStopUIInvalidation(shouldFlush: self.stopUIInvalidationGate.finish())+ }++ private func forceFinishDeferredStopUIInvalidation() {+ self.activeStopUIInvalidationHold = nil+ self.flushDeferredStopUIInvalidation(shouldFlush: self.stopUIInvalidationGate.forceFinish())+ }++ private func flushDeferredStopUIInvalidation(shouldFlush: Bool) {+ guard shouldFlush else { return }+ self.stopUIInvalidationTimeoutTask?.cancel()+ self.stopUIInvalidationTimeoutTask = nil+ self.objectWillChange.send()+ self.deferredStopUIInvalidationDidFlush.send()+ }+func transcribeSamplesForAPI(_ inputSamples: [Float]) async throws -> ASRTranscriptionResult {var samples = inputSamplesguard !samples.isEmpty else {@@ -2781,12 +3280,26 @@ final class ASRService: ObservableObject {await self.cancelPendingAudioCaptureStart(reason: "stop_without_transcription")}guard self.isRunning else { return }+ let stoppingSessionID = self.benchmarkSessionID+ guard let bufferHandoffToken = self.recordingBufferHandoffGate.begin() else { return }+ var completedBufferHandoff = false+ defer {+ if completedBufferHandoff == false {+ self.recordingBufferHandoffGate.complete(bufferHandoffToken)+ }+ }+ self.stopStreamingScheduler(sessionID: stoppingSessionID)defer {self.applyPendingParakeetVocabularyReloadIfNeeded()self.isDictionaryTrainingCaptureActive = false}await self.cancelAudioRouteRecoveryAndWait()+ guard self.isRunning, self.benchmarkSessionID == stoppingSessionID else {+ self.recordingBufferHandoffGate.complete(bufferHandoffToken)+ completedBufferHandoff = true+ return+ }// Capture media pause state before we reset it, for resuming at the endlet shouldResumeMedia = self.didPauseMediaForThisSession@@ -2809,14 +3322,20 @@ final class ASRService: ObservableObject {// Cancel/no-transcription paths stay conservative and retire the engine.await self.retireAudioEngineAndWait(reason: "stop_without_transcription")- self.audioCaptureStateSettledTick &+= 1+ self.audioCaptureStateDidSettle.send()- // CRITICAL FIX: Await completion of streaming task AND any pending transcriptions- // This prevents use-after-free crashes (EXC_BAD_ACCESS) when clearing buffer- await self.stopStreamingTimerAndAwait()+ guard await self.drainActiveStreamingWork(sessionID: stoppingSessionID) else {+ self.beginStreamingDrainRecovery(sessionID: stoppingSessionID, token: bufferHandoffToken)+ completedBufferHandoff = true+ if shouldResumeMedia { await MediaPlaybackService.shared.resumeIfWePaused(true) }+ return+ }// NOW it's safe to clear the bufferself.audioBuffer.clear()+ self.streamingWorkState.endSession(stoppingSessionID)+ self.recordingBufferHandoffGate.complete(bufferHandoffToken)+ completedBufferHandoff = trueself.partialTranscription.removeAll()self.previousFullTranscription.removeAll()self.lastBoostHitTerm = nil@@ -4162,6 +4681,7 @@ final class ASRService: ObservableObject {source: AnalyticsModelDownloadSource,progressHandler: ((Double) -> Void)? = nil) async throws {+ try self.requireStreamingProviderAvailable()guard self.modelDownloadTask == nil else {throw NSError(domain: "ASRService",@@ -4629,16 +5149,21 @@ final class ASRService: ObservableObject {// MARK: - Cache managementfunc clearModelCache() async throws {+ try self.requireStreamingProviderAvailable()DebugLogger.shared.debug("Clearing model cache via transcription provider", source: "ASRService")+ self.streamingWorkState.invalidateProvider()+ self.isAsrReady = falseawait self.transcriptionExecutor.cancelAndAwaitPending()try await self.transcriptionProvider.clearCache()- self.isAsrReady = falseself.modelsExistOnDisk = false}func clearModelCache(for model: SettingsStore.SpeechModel) async throws {+ try self.requireStreamingProviderAvailable()DebugLogger.shared.debug("Clearing model cache for \(model.displayName)", source: "ASRService")if SettingsStore.shared.selectedSpeechModel == model {+ self.streamingWorkState.invalidateProvider()+ self.isAsrReady = falseawait self.transcriptionExecutor.cancelAndAwaitPending()}let provider = self.getProvider(for: model)@@ -4656,61 +5181,90 @@ final class ASRService: ObservableObject {// MARK: - Timer-based Streaming Transcription (No VAD)private func startStreamingTranscription() {- self.streamingTask?.cancel()+ self.streamingSchedulingSessionID = nil+ _ = self.streamingTaskLifecycle.cancelScheduler()guard self.isAsrReady else { return }+ self.streamingSchedulingSessionID = self.benchmarkSessionIDDebugLogger.shared.debug("Starting streaming transcription task (interval: \(self.streamingChunkDurationSeconds)s, minSamples: \(self.minimumStreamingPreviewSamples))",source: "ASRService")-- self.streamingTask = Task { [weak self] in- await self?.runStreamingLoop()- }+ self.scheduleNextStreamingChunk(sessionID: self.benchmarkSessionID, delayNanoseconds: 0)}- @MainActor- private func runStreamingLoop() async {- DebugLogger.shared.debug("🔄 runStreamingLoop() - ENTERED", source: "ASRService")- var loopCount = 0- var lastBufferCount = 0-- while !Task.isCancelled {- DebugLogger.shared.debug("🔄 runStreamingLoop() - calling processStreamingChunk()", source: "ASRService")- await self.processStreamingChunk()- DebugLogger.shared.debug("🔄 runStreamingLoop() - processStreamingChunk() returned", source: "ASRService")-- if Task.isCancelled || self.isRunning == false {- break+ private func scheduleNextStreamingChunk(sessionID: Int, delayNanoseconds: UInt64) {+ guard self.isRunning,+ self.benchmarkSessionID == sessionID,+ self.streamingSchedulingSessionID == sessionID+ else { return }+ self.streamingTaskLifecycle.schedule(+ sessionID: sessionID,+ delayNanoseconds: delayNanoseconds+ ) { [weak self] operationID in+ await self?.processStreamingChunk(sessionID: sessionID, operationID: operationID)+ self?.benchmarkLog(+ "streaming_active_exit session=\(sessionID) operation=\(operationID.uuidString)"+ )+ } completion: { [weak self] operationID in+ let isLateCompletion = self?.isRunning == false || self?.streamingSchedulingSessionID != sessionID+ if isLateCompletion {+ self?.benchmarkLog(+ "streaming_active_cleanup_begin session=\(sessionID) operation=\(operationID.uuidString)"+ )}-- // Health check: detect if audio is not being captured- loopCount += 1- if loopCount >= 3 { // After 3 loops (~6 seconds with 2s interval)- let currentBufferCount = self.audioBuffer.count- if currentBufferCount == lastBufferCount, currentBufferCount < 16_000 {- DebugLogger.shared.warning(- "Audio buffer not growing after \(loopCount * 2) seconds (count: \(currentBufferCount)). " +- "Audio capture may have failed. Check if engine is running and tap is installed.",- source: "ASRService"- )- }- lastBufferCount = currentBufferCount- loopCount = 0+ self?.streamingChunkDidFinish(sessionID: sessionID, operationID: operationID)+ if isLateCompletion {+ self?.benchmarkLog(+ "streaming_active_cleanup_end session=\(sessionID) operation=\(operationID.uuidString)"+ )}+ }+ }- do {- try await Task.sleep(nanoseconds: UInt64(self.streamingChunkDurationSeconds * 1_000_000_000))- } catch {- DebugLogger.shared.debug("Streaming transcription task cancelled", source: "ASRService")- break+ private func streamingChunkDidFinish(sessionID: Int, operationID: UUID) {+ guard self.streamingWorkState.finishOperation(+ sessionID: sessionID,+ operationID: operationID+ ) else { return }+ self.isProcessingChunk = false+ self.finishStreamingDrainRecovery(sessionID: sessionID)+ guard self.isRunning,+ self.benchmarkSessionID == sessionID,+ self.streamingSchedulingSessionID == sessionID+ else { return }++ self.streamingHealthCheckCount += 1+ if self.streamingHealthCheckCount >= 3 {+ let currentBufferCount = self.audioBuffer.count+ if currentBufferCount == self.streamingHealthLastBufferCount,+ currentBufferCount < 16_000+ {+ DebugLogger.shared.warning(+ "Audio buffer not growing after three streaming intervals (count: \(currentBufferCount)). " ++ "Audio capture may have failed. Check if engine is running and tap is installed.",+ source: "ASRService"+ )}+ self.streamingHealthLastBufferCount = currentBufferCount+ self.streamingHealthCheckCount = 0}++ self.scheduleNextStreamingChunk(+ sessionID: sessionID,+ delayNanoseconds: UInt64(self.streamingChunkDurationSeconds * 1_000_000_000)+ )}- @MainActor- private func processStreamingChunk() async {- guard self.isRunning else { return }+ private func processStreamingChunk(sessionID: Int, operationID: UUID) async {+ guard self.isRunning,+ self.benchmarkSessionID == sessionID,+ self.streamingSchedulingSessionID == sessionID,+ let providerGeneration = self.streamingWorkState.beginOperation(+ sessionID: sessionID,+ operationID: operationID+ )+ else { return }self.benchmarkStreamingChunkIndex += 1let chunkIndex = self.benchmarkStreamingChunkIndexlet chunkAgeMs = self.elapsedMilliseconds(since: self.benchmarkRecordingStartedAt)@@ -4779,7 +5333,6 @@ final class ASRService: ObservableObject {}self.isProcessingChunk = true- defer { isProcessingChunk = false }let startTime = Date()let startedAt = startTime.timeIntervalSince1970@@ -4799,35 +5352,83 @@ final class ASRService: ObservableObject {if incrementalDeltaStart != nil, let incrementalProvider {do {result = try await self.transcriptionExecutor.run {- try await incrementalProvider.transcribeStreamingDelta(+ let result = try await incrementalProvider.transcribeStreamingDelta(chunk,totalSampleCount: currentSampleCount)+ logStreamingProviderOperationReturn(+ sessionID: sessionID,+ operationID: operationID,+ route: "incremental_delta"+ )+ return result}} catch {if Task.isCancelled || error is CancellationError {throw CancellationError()}+ guard self.streamingWorkState.canPublishPreview(+ sessionID: sessionID,+ operationID: operationID,+ providerGeneration: providerGeneration,+ isRunning: self.isRunning,+ schedulingSessionID: self.streamingSchedulingSessionID+ ) else { return }DebugLogger.shared.warning("Incremental delta preview failed; retrying with the full prefix",source: "ASRService")let fullPrefix = self.audioBuffer.getPrefix(currentSampleCount)result = try await self.transcriptionExecutor.run { [provider = self.transcriptionProvider] in- try await provider.transcribeStreaming(fullPrefix)+ let result = try await provider.transcribeStreaming(fullPrefix)+ logStreamingProviderOperationReturn(+ sessionID: sessionID,+ operationID: operationID,+ route: "incremental_fallback_full"+ )+ return result}}} else {result = try await self.transcriptionExecutor.run { [provider = self.transcriptionProvider] in- try await provider.transcribeStreaming(chunk)+ let result = try await provider.transcribeStreaming(chunk)+ logStreamingProviderOperationReturn(+ sessionID: sessionID,+ operationID: operationID,+ route: "full_prefix"+ )+ return result}}#elseresult = try await self.transcriptionExecutor.run { [provider = self.transcriptionProvider] in- try await provider.transcribeStreaming(chunk)+ let result = try await provider.transcribeStreaming(chunk)+ logStreamingProviderOperationReturn(+ sessionID: sessionID,+ operationID: operationID,+ route: "full_prefix"+ )+ return result}#endif+ let canPublishPreview = self.streamingWorkState.canPublishPreview(+ sessionID: sessionID,+ operationID: operationID,+ providerGeneration: providerGeneration,+ isRunning: self.isRunning,+ schedulingSessionID: self.streamingSchedulingSessionID+ )+ if canPublishPreview == false {+ let scheduledSession = self.streamingSchedulingSessionID.map(String.init) ?? "none"+ self.benchmarkLog(+ "streaming_executor_return publish=false index=\(chunkIndex) session=\(sessionID) " ++ "operation=\(operationID.uuidString) running=\(self.isRunning) " ++ "scheduledSession=\(scheduledSession)"+ )+ return+ }+let duration = Date().timeIntervalSince(startTime)DebugLogger.shared.debug("Streaming chunk transcription finished in \(String(format: "%.2f", duration))s",@@ -4844,11 +5445,9 @@ final class ASRService: ObservableObject {// Mark first transcription as complete to clear loading stateif !self.hasCompletedFirstTranscription {self.hasCompletedFirstTranscription = true- DispatchQueue.main.async {- self.isLoadingModel = false- self.modelPreparationPhase = nil- DebugLogger.shared.info("✅ Model warmed up - first streaming transcription completed", source: "ASRService")- }+ self.isLoadingModel = false+ self.modelPreparationPhase = nil+ DebugLogger.shared.info("✅ Model warmed up - first streaming transcription completed", source: "ASRService")}if !newText.isEmpty {@@ -4875,10 +5474,20 @@ final class ASRService: ObservableObject {)self.skipNextChunk = true}- } catch {+ } catch where self.streamingWorkState.canPublishPreview(+ sessionID: sessionID,+ operationID: operationID,+ providerGeneration: providerGeneration,+ isRunning: self.isRunning,+ schedulingSessionID: self.streamingSchedulingSessionID+ ) {DebugLogger.shared.error("❌ Streaming failed: \(error)", source: "ASRService")self.benchmarkLog("chunk_fail index=\(chunkIndex) elapsedMs=\(self.elapsedMilliseconds(since: startedAt)) samples=\(currentSampleCount) inputSamples=\(chunk.count) error=\(error.localizedDescription)")self.skipNextChunk = true+ } catch {+ self.benchmarkLog(+ "chunk_stale_failure index=\(chunkIndex) session=\(sessionID) operation=\(operationID.uuidString)"+ )}}@@ -4926,7 +5535,8 @@ final class ASRService: ObservableObject {_ plan: DictationLiteralOutputPlan,preferredTargetPID: pid_t?,textReadyAt: TimeInterval? = nil,- tracksDictionaryCorrections: Bool = false+ tracksDictionaryCorrections: Bool = false,+ completion: (@MainActor (TypingService.DeliveryOutcome) -> Void)? = nil) {let requestedAt = ProcessInfo.processInfo.systemUptimelet textReadyAge = textReadyAt.map { Int(((requestedAt - $0) * 1000).rounded()) }@@ -4940,7 +5550,8 @@ final class ASRService: ObservableObject {plan,preferredTargetPID: preferredTargetPID,textReadyAt: textReadyAt,- tracksDictionaryCorrections: tracksDictionaryCorrections+ tracksDictionaryCorrections: tracksDictionaryCorrections,+ completion: completion)let dispatchedAt = ProcessInfo.processInfo.systemUptimelet textReadyToDispatchMs = textReadyAt.map {@@ -5222,29 +5833,103 @@ private extension SettingsStore.SpeechModel {}private extension ASRService {- /// Stops the streaming timer and waits for the task to complete.- /// This prevents race conditions where the buffer is cleared while- /// a transcription task is still running.- func stopStreamingTimerAndAwait() async {- guard let task = self.streamingTask else {- self.benchmarkLog("streaming_timer_stop no_task=true")- return+ /// Cancels only the idle delay. Active provider work is intentionally not+ /// cancelled because incremental providers use cancellation to discard state+ /// needed by the final pass.+ func stopStreamingScheduler(sessionID: Int) {+ let startedAt = Date().timeIntervalSince1970+ if self.streamingSchedulingSessionID == sessionID {+ self.streamingSchedulingSessionID = nil}+ let cancelled = self.streamingTaskLifecycle.cancelScheduler()+ self.benchmarkLog(+ "streaming_scheduler_cancel session=\(sessionID) hadIdleTask=\(cancelled) " ++ "elapsedMs=\(self.elapsedMilliseconds(since: startedAt))"+ )+ }++ /// Drains only real in-flight provider work before the shared PCM buffer is+ /// handed off. An idle scheduler never participates in this await.+ func drainActiveStreamingWork(sessionID: Int) async -> Bool {let startedAt = Date().timeIntervalSince1970- self.benchmarkLog("streaming_timer_stop begin")- task.cancel()- // Wait for the task to actually finish - this is critical!- // The task may be in the middle of processStreamingChunk()- _ = await task.result- self.streamingTask = nil- self.benchmarkLog("streaming_timer_stop end elapsedMs=\(self.elapsedMilliseconds(since: startedAt)) completedChunks=\(self.benchmarkCompletedStreamingChunks)")- }-- /// Legacy sync version for cases where we can't await (e.g., stopWithoutTranscription)- /// WARNING: This can cause crashes if buffer is cleared immediately after!- func stopStreamingTimer() {- self.streamingTask?.cancel()- self.streamingTask = nil+ guard self.streamingTaskLifecycle.activeTaskToDrain(sessionID: sessionID) != nil else {+ self.benchmarkLog(+ "streaming_timer_stop begin phase=idle session=\(sessionID)"+ )+ self.benchmarkLog(+ "streaming_timer_stop end phase=idle session=\(sessionID) elapsedMs=0 " ++ "completedChunks=\(self.benchmarkCompletedStreamingChunks)"+ )+ return true+ }+ self.benchmarkLog(+ "streaming_timer_stop begin phase=active session=\(sessionID)"+ )+ // Keep the idle fast path synchronous; only real work gets a deadline.+ let completed = await self.streamingTaskLifecycle.drain(+ sessionID: sessionID,+ timeoutNanoseconds: Self.streamingDrainTimeoutNanoseconds+ )+ self.benchmarkLog(+ "streaming_active_drain_resume session=\(sessionID)"+ )+ self.benchmarkLog(+ "streaming_timer_stop end phase=active session=\(sessionID) completed=\(completed) " ++ "elapsedMs=\(self.elapsedMilliseconds(since: startedAt)) " ++ "completedChunks=\(self.benchmarkCompletedStreamingChunks)"+ )+ return completed+ }++ static var streamingRecoveryMessage: String {+ "Speech recognition took too long to finish. This recording could not be transcribed. " ++ "Wait for the model to recover, or restart FluidVoice before recording again."+ }++ func presentStreamingRecoveryError() {+ self.errorTitle = "Speech recognition needs recovery"+ self.errorMessage = Self.streamingRecoveryMessage+ self.showError = true+ }++ func requireStreamingProviderAvailable() throws {+ guard self.recordingBufferHandoffGate.isRecovering else { return }+ throw NSError(domain: "ASRService", code: -2002, userInfo: [+ NSLocalizedDescriptionKey: Self.streamingRecoveryMessage,+ ])+ }++ func beginStreamingDrainRecovery(sessionID: Int, token: RecordingBufferHandoffGate.Token) {+ self.timedOutStreamingHandoff = (sessionID, token)+ self.recordingBufferHandoffGate.markTimedOut(token)+ self.presentStreamingRecoveryError()+ // Completion may have won the main-actor turn after the deadline fired.+ if self.streamingTaskLifecycle.activeTaskToDrain(sessionID: sessionID) == nil {+ self.finishStreamingDrainRecovery(sessionID: sessionID)+ }+ }++ func finishStreamingDrainRecovery(sessionID: Int) {+ guard let recovery = self.timedOutStreamingHandoff, recovery.sessionID == sessionID else { return }+ self.timedOutStreamingHandoff = nil+ // The provider has actually returned. Only now may its PCM and state be retired.+ if self.benchmarkSessionID == sessionID {+ self.audioBuffer.clear()+ self.streamingWorkState.endSession(sessionID)+ self.partialTranscription = ""+ self.previousFullTranscription = ""+ self.isProcessingChunk = false+ self.skipNextChunk = false+ }+ self.recordingBufferHandoffGate.complete(recovery.token)+ if self.resetProviderAfterStreamingRecovery {+ self.resetProviderAfterStreamingRecovery = false+ self.resetTranscriptionProvider()+ }+ if self.errorMessage == Self.streamingRecoveryMessage {+ self.errorMessage = "The speech model has recovered. Please record your dictation again."+ }+ self.benchmarkLog("streaming_drain_recovered session=\(sessionID)")}}diff --git a/Sources/Fluid/Services/AppServices.swift b/Sources/Fluid/Services/AppServices.swiftindex bbcc7a08..499b3b02 100644--- a/Sources/Fluid/Services/AppServices.swift+++ b/Sources/Fluid/Services/AppServices.swift@@ -102,7 +102,10 @@ final class AppServices: ObservableObject {private func setupASRForwarding() {guard let asr = _asr else { return }asr.objectWillChange- .sink { [weak self] _ in self?.objectWillChange.send() }+ .sink { [weak self, weak asr] _ in+ guard asr?.defersStopUIInvalidation == false else { return }+ self?.objectWillChange.send()+ }.store(in: &self.cancellables)}diff --git a/Sources/Fluid/Services/AudioCaptureReadinessGate.swift b/Sources/Fluid/Services/AudioCaptureReadinessGate.swiftindex fabccdc8..80b5eeb0 100644--- a/Sources/Fluid/Services/AudioCaptureReadinessGate.swift+++ b/Sources/Fluid/Services/AudioCaptureReadinessGate.swift@@ -125,6 +125,14 @@ final nonisolated class AudioCaptureReadinessGate: @unchecked Sendable {)}+ #if DEBUG+ func hasRegisteredWaiter(sessionID: Int, attemptID: UInt64) -> Bool {+ self.lock.withLock {+ self.key == Key(sessionID: sessionID, attemptID: attemptID) && self.waiter != nil+ }+ }+ #endif+private func finish(key: Key,waiterID: UUID? = nil,diff --git a/Sources/Fluid/Services/DebugLogger.swift b/Sources/Fluid/Services/DebugLogger.swiftindex 917601a4..52e3b135 100644--- a/Sources/Fluid/Services/DebugLogger.swift+++ b/Sources/Fluid/Services/DebugLogger.swift@@ -1,8 +1,12 @@import Foundation-class DebugLogger {+final nonisolated class DebugLogger: @unchecked Sendable {static let shared = DebugLogger()+ /// Request-local correlation survives actor hops without mutable global state.+ /// Capture explicitly before handing work to a DispatchQueue or detached task.+ @TaskLocal static var pipelineID: String?+private let queue = DispatchQueue(label: "debug.logger", qos: .utility)private static let logFormatter: DateFormatter = {@@ -23,25 +27,48 @@ class DebugLogger {private init() {}func log(_ message: String, level: LogLevel = .info, source: String = "App") {+ let pipelineID = Self.pipelineIDself.queue.async {- let timestamp = Date()- let timestampString = Self.logFormatter.string(from: timestamp)-- let formattedLine = self.formatLogLine(timestamp: timestampString, level: level, source: source, message: message)+ self.write(message, level: level, source: source, pipelineID: pipelineID)+ }+ }- // Always persist diagnostics so issues can be debugged even if UI debug mode is off.- FileLogger.shared.append(line: formattedLine)- print(formattedLine)+ /// Defers expensive diagnostic string construction until after latency-sensitive+ /// work has continued on the caller's executor.+ func logLazy(+ level: LogLevel = .info,+ source: String = "App",+ _ message: @escaping @Sendable () -> String+ ) {+ let pipelineID = Self.pipelineID+ self.queue.async {+ self.write(message(), level: level, source: source, pipelineID: pipelineID)}}- private func formatLogLine(timestamp: String, level: LogLevel, source: String, message: String) -> String {- "[\(timestamp)] [\(level.rawValue)] [\(source)] \(message)"+ private func write(_ message: String, level: LogLevel, source: String, pipelineID: String?) {+ let timestampString = Self.logFormatter.string(from: Date())+ let formattedLine = self.formatLogLine(+ timestamp: timestampString,+ level: level,+ source: source,+ message: message,+ pipelineID: pipelineID+ )++ // Always persist diagnostics so issues can be debugged even if UI debug mode is off.+ FileLogger.shared.append(line: formattedLine)+ print(formattedLine)+ }++ private func formatLogLine(timestamp: String, level: LogLevel, source: String, message: String, pipelineID: String?) -> String {+ let correlation = pipelineID.map { "pipelineID=\($0) " } ?? ""+ return "[\(timestamp)] [\(level.rawValue)] [\(source)] \(correlation)\(message)"}}// Convenience functions for easier logging-extension DebugLogger {+nonisolated extension DebugLogger {func info(_ message: String, source: String = "App") {self.log(message, level: .info, source: source)}diff --git a/Sources/Fluid/Services/DictationPostProcessingService.swift b/Sources/Fluid/Services/DictationPostProcessingService.swiftindex 978a5f55..c7666919 100644--- a/Sources/Fluid/Services/DictationPostProcessingService.swift+++ b/Sources/Fluid/Services/DictationPostProcessingService.swift@@ -106,6 +106,7 @@ struct DictationProviderRoute: Equatable {static func resolve(settings: SettingsStore, providerID: String, model: String) -> Self {let trimmedProviderID = providerID.trimmingCharacters(in: .whitespacesAndNewlines)let trimmedModel = model.trimmingCharacters(in: .whitespacesAndNewlines)+ let providerKeys = settings.providerAPIKeysif let saved = settings.savedProviders.first(where: { $0.id == trimmedProviderID }) {let key = "custom:\(saved.id)"return Self(@@ -113,7 +114,7 @@ struct DictationProviderRoute: Equatable {providerKey: key,baseURL: saved.baseURL,model: trimmedModel,- apiKey: settings.providerAPIKeys[key] ?? settings.providerAPIKeys[trimmedProviderID] ?? ""+ apiKey: providerKeys[key] ?? providerKeys[trimmedProviderID] ?? "")}return Self(@@ -121,7 +122,7 @@ struct DictationProviderRoute: Equatable {providerKey: trimmedProviderID,baseURL: ModelRepository.shared.defaultBaseURL(for: trimmedProviderID),model: trimmedModel,- apiKey: settings.providerAPIKeys[trimmedProviderID] ?? ""+ apiKey: providerKeys[trimmedProviderID] ?? "")}diff --git a/Sources/Fluid/Services/FluidAudioProvider.swift b/Sources/Fluid/Services/FluidAudioProvider.swiftindex 4c7f610d..64d3d988 100644--- a/Sources/Fluid/Services/FluidAudioProvider.swift+++ b/Sources/Fluid/Services/FluidAudioProvider.swift@@ -350,7 +350,15 @@ final class FluidAudioProvider: TranscriptionProvider {}func transcribeFinal(_ samples: [Float]) async throws -> ASRTranscriptionResult {- defer { self.resetIncrementalSession() }+ defer {+ let resetStartedAt = ProcessInfo.processInfo.systemUptime+ self.resetIncrementalSession()+ let resetFinishedAt = ProcessInfo.processInfo.systemUptime+ DebugLogger.shared.info(+ "ASR_BENCH t=\(resetFinishedAt) incremental_reset_done elapsedMs=\((resetFinishedAt - resetStartedAt) * 1000)",+ source: "ASRBenchmark"+ )+ }guard let manager = self.finalAsrManager ?? self.streamingAsrManager else {throw NSError(domain: "FluidAudioProvider",@@ -370,7 +378,8 @@ final class FluidAudioProvider: TranscriptionProvider {samples: samples,text: result.text,startedAt: startedAt,- usedFallback: false+ usedFallback: false,+ source: "incremental")return result} catch {@@ -439,18 +448,28 @@ final class FluidAudioProvider: TranscriptionProvider {userInfo: [NSLocalizedDescriptionKey: "Incremental ASR session cannot finalize this recording"])}- if samples.count > self.incrementalAcceptedSampleCount {+ let startedAt = ProcessInfo.processInfo.systemUptime+ let acceptedBeforeFinal = self.incrementalAcceptedSampleCount+ if samples.count > acceptedBeforeFinal {try await self.appendIncrementalSamples(samples, to: session)}+ let appendFinishedAt = ProcessInfo.processInfo.systemUptimelet result = try await session.finish(finalAudioSamples: samples)- let reusedWindows = await session.finalizedWindowCount+ let finishFinishedAt = ProcessInfo.processInfo.systemUptimeDebugLogger.shared.info(- "FluidAudioProvider: Incremental final reused \(reusedWindows) stable Parakeet windows",- source: "FluidAudioProvider"+ "ASR_BENCH incremental_final_split acceptedBefore=\(acceptedBeforeFinal) " ++ "appended=\(samples.count - acceptedBeforeFinal) " ++ "appendMs=\(Self.milliseconds(from: startedAt, to: appendFinishedAt)) " ++ "finishMs=\(Self.milliseconds(from: appendFinishedAt, to: finishFinishedAt))",+ source: "ASRBenchmark")return ASRTranscriptionResult(text: result.text, confidence: result.confidence)}+ private static func milliseconds(from start: TimeInterval, to end: TimeInterval) -> String {+ String(format: "%.1f", (end - start) * 1000)+ }+private func appendIncrementalSamples(_ samples: [Float],to session: ParakeetIncrementalSessiondiff --git a/Sources/Fluid/Services/LLMClient.swift b/Sources/Fluid/Services/LLMClient.swiftindex 03982e9d..31038b49 100644--- a/Sources/Fluid/Services/LLMClient.swift+++ b/Sources/Fluid/Services/LLMClient.swift@@ -2,7 +2,7 @@ import Foundation// MARK: - Error Types-enum LLMError: Error, LocalizedError {+nonisolated enum LLMError: Error, LocalizedError, @unchecked Sendable {case invalidURLcase invalidResponsecase httpError(Int, String)@@ -58,8 +58,9 @@ enum LLMError: Error, LocalizedError {/// Unified LLM communication layer for all modes (Transcription, Command, Rewrite)./// Handles HTTP requests, SSE streaming, thinking token extraction, and tool call parsing.-@MainActor-final class LLMClient {+/// Stateless, thread-safe transport. Keeping streaming decode off MainActor prevents+/// provider token bursts from delaying dictation UI and final text delivery.+final nonisolated class LLMClient: @unchecked Sendable {static let shared = LLMClient()/// Default timeout for LLM requests (30 seconds)@@ -82,7 +83,7 @@ final class LLMClient {// MARK: - Response Types- struct Response {+ struct Response: @unchecked Sendable {/// Extracted <think>...</think> content (nil if none)let thinking: String?/// Main response content with thinking tags stripped@@ -91,7 +92,7 @@ final class LLMClient {let toolCalls: [ToolCall]}- struct ToolCall {+ struct ToolCall: @unchecked Sendable {let id: Stringlet name: Stringlet arguments: [String: Any]@@ -117,7 +118,7 @@ final class LLMClient {// MARK: - Configuration- struct Config {+ struct Config: @unchecked Sendable {let messages: [[String: Any]]let model: Stringlet baseURL: String@@ -133,6 +134,9 @@ final class LLMClient {/// These are model-specific and come from user settingsvar extraParameters: [String: Any]+ /// Optional dictation pipeline correlation for bounded latency diagnostics.+ let benchmarkID: String?+// Retry configurationvar maxRetries: Int = 3var retryDelayMs: Int = 200@@ -141,11 +145,11 @@ final class LLMClient {var timeoutSeconds: TimeInterval?// Optional real-time callbacks (for streaming UI updates)- var onThinkingStart: (() -> Void)?- var onThinkingChunk: ((String) -> Void)?- var onThinkingEnd: (() -> Void)?- var onContentChunk: ((String) -> Void)?- var onToolCallStart: ((String) -> Void)?+ var onThinkingStart: (@Sendable () -> Void)?+ var onThinkingChunk: (@Sendable (String) -> Void)?+ var onThinkingEnd: (@Sendable () -> Void)?+ var onContentChunk: (@Sendable (String) -> Void)?+ var onToolCallStart: (@Sendable (String) -> Void)?init(messages: [[String: Any]],@@ -156,7 +160,8 @@ final class LLMClient {tools: [[String: Any]] = [],temperature: Double? = nil,maxTokens: Int? = nil,- extraParameters: [String: Any] = [:]+ extraParameters: [String: Any] = [:],+ benchmarkID: String? = nil) {self.messages = messagesself.model = model@@ -167,6 +172,7 @@ final class LLMClient {self.temperature = temperatureself.maxTokens = maxTokensself.extraParameters = extraParameters+ self.benchmarkID = benchmarkID}}@@ -175,20 +181,27 @@ final class LLMClient {/// Make an LLM API call with the given configuration./// Supports both streaming and non-streaming modes./// Handles thinking token extraction, tool call parsing, and retries.- func call(_ config: Config) async throws -> Response {+ @concurrent func call(_ config: Config) async throws -> Response {+ self.benchmark(config, "call_enter")var request = try buildRequest(config)+ self.benchmark(config, "request_built bodyBytes=\(request.httpBody?.count ?? 0)")// Apply timeout to the request itselflet timeout = config.timeoutSeconds ?? Self.defaultTimeoutSecondsrequest.timeoutInterval = timeout- self.logRequest(request)-// Execute the request. We rely on URLRequest/URLSession timeouts (30s default) rather// than racing a separate "timeout task". A task-group timeout wrapper can accidentally// keep the caller suspended until the full timeout elapses, which is the exact stall// we want to eliminate for overlay responsiveness.- return try await self.executeWithRetry(request: request, config: config)+ do {+ let response = try await self.executeWithRetry(request: request, config: config)+ self.benchmark(config, "call_return")+ return response+ } catch {+ self.benchmark(config, "call_fail")+ throw error+ }}/// Execute request with retry logic (extracted for timeout wrapper)@@ -196,13 +209,14 @@ final class LLMClient {var lastError: Error?for attempt in 1...config.maxRetries {do {+ self.benchmark(config, "attempt_start attempt=\(attempt)")if config.streaming {if self.isResponsesRequest(request) {return try await self.processResponsesStreaming(request: request, config: config)}return try await self.processStreaming(request: request, config: config)} else {- return try await self.processNonStreaming(request: request)+ return try await self.processNonStreaming(request: request, config: config)}} catch let error as URLError where self.isRetryableError(error) {lastError = LLMError.networkError(error)@@ -249,13 +263,6 @@ final class LLMClient {throw LLMError.encodingError}- // Log the request for debugging- let messageCount = config.messages.count- if let bodyStr = String(data: jsonData, encoding: .utf8) {- let truncated = bodyStr.count > 500 ? String(bodyStr.prefix(500)) + "..." : bodyStr- DebugLogger.shared.debug("LLMClient: Request (\(messageCount) messages, model=\(config.model), streaming=\(config.streaming)): \(truncated)", source: "LLMClient")- }-// Build URLRequestvar request = URLRequest(url: url)request.httpMethod = "POST"@@ -268,6 +275,12 @@ final class LLMClient {request.httpBody = jsonData+ DebugLogger.shared.debug(+ "LLMClient: Request ready url=\(endpoint) messages=\(config.messages.count) "+ + "model=\(config.model) streaming=\(config.streaming) bodyBytes=\(jsonData.count)",+ source: "LLMClient"+ )+return request}@@ -348,7 +361,7 @@ final class LLMClient {// Final Layer: Common parameters with model-specific keysif let tokens = config.maxTokens {- if SettingsStore.shared.isReasoningModel(config.model) {+ if Self.usesReasoningCompletionTokenParameter(config.model) {body["max_completion_tokens"] = tokens} else {body["max_tokens"] = tokens@@ -358,6 +371,20 @@ final class LLMClient {return body}+ private static func usesReasoningCompletionTokenParameter(_ model: String) -> Bool {+ var modelLower = model.lowercased()+ if let slash = modelLower.firstIndex(of: "/") {+ modelLower = String(modelLower[modelLower.index(after: slash)...])+ }+ return modelLower.hasPrefix("gpt-5") ||+ modelLower.contains("gpt-5.") ||+ modelLower.hasPrefix("o1") ||+ modelLower.hasPrefix("o3") ||+ modelLower.hasPrefix("o4") ||+ modelLower.contains("gpt-oss") ||+ (modelLower.contains("deepseek") && modelLower.contains("reasoner"))+ }+func buildResponsesBody(_ config: Config) -> [String: Any] {var body: [String: Any] = ["model": config.model,@@ -467,10 +494,11 @@ final class LLMClient {// MARK: - Non-Streaming Response- private func processNonStreaming(request: URLRequest) async throws -> Response {+ private func processNonStreaming(request: URLRequest, config: Config) async throws -> Response {DebugLogger.shared.debug("LLMClient: Making non-streaming request to \(request.url?.absoluteString ?? "unknown")", source: "LLMClient")let (data, response) = try await self.session.data(for: request)+ self.benchmark(config, "response_data bytes=\(data.count)")if let http = response as? HTTPURLResponse, http.statusCode >= 400 {let errText = String(data: data, encoding: .utf8) ?? "Unknown error"@@ -484,22 +512,25 @@ final class LLMClient {throw LLMError.invalidResponse}+ let parsed: Responseif self.isResponsesRequest(request) {- return try self.parseResponsesResponse(json)+ parsed = try self.parseResponsesResponse(json)+ } else {+ guard let choices = json["choices"] as? [[String: Any]],+ let choice = choices.first,+ let message = choice["message"] as? [String: Any]+ else { throw LLMError.invalidResponse }+ parsed = self.parseMessageResponse(message)}-- guard let choices = json["choices"] as? [[String: Any]],- let choice = choices.first,- let message = choice["message"] as? [String: Any]- else { throw LLMError.invalidResponse }-- return self.parseMessageResponse(message)+ self.benchmark(config, "response_decoded")+ return parsed}private func processResponsesStreaming(request: URLRequest, config: Config) async throws -> Response {DebugLogger.shared.debug("LLMClient: Starting Responses streaming request to \(request.url?.absoluteString ?? "unknown")", source: "LLMClient")let (bytes, response) = try await self.session.bytes(for: request)+ self.benchmark(config, "response_headers")if let http = response as? HTTPURLResponse, http.statusCode >= 400 {var errorData = Data()@@ -512,6 +543,7 @@ final class LLMClient {var contentBuffer: [String] = []var toolCallsByIndex: [Int: ResponsesToolCallAccumulator] = [:]+ var didLogFirstContent = falsefor try await rawLine in bytes.lines {let line = rawLine.trimmingCharacters(in: .whitespaces)@@ -535,6 +567,10 @@ final class LLMClient {switch type {case "response.output_text.delta":if let delta = event["delta"] as? String {+ if !didLogFirstContent, !delta.isEmpty {+ didLogFirstContent = true+ self.benchmark(config, "first_content")+ }contentBuffer.append(delta)config.onContentChunk?(delta)}@@ -592,17 +628,20 @@ final class LLMClient {)}- return Response(+ let parsed = Response(thinking: nil,content: contentBuffer.joined().trimmingCharacters(in: .whitespacesAndNewlines),toolCalls: toolCalls)+ self.benchmark(config, "response_decoded")+ return parsed}private func processStreaming(request: URLRequest, config: Config) async throws -> Response {DebugLogger.shared.debug("LLMClient: Starting streaming request to \(request.url?.absoluteString ?? "unknown")", source: "LLMClient")let (bytes, response) = try await self.session.bytes(for: request)+ self.benchmark(config, "response_headers")// Check for HTTP errorsif let http = response as? HTTPURLResponse, http.statusCode >= 400 {@@ -623,6 +662,7 @@ final class LLMClient {var contentBuffer: [String] = []var tagDetectionBuffer = ""var usesSeparateReasoningFields = false+ var didLogFirstContent = false// Tool call accumulationvar toolCallId: String?@@ -651,11 +691,12 @@ final class LLMClient {continue}- // DEBUG LOG: Show full delta to see all fields (e.g., 'reasoning', 'thought', 'delta_reasoning', etc.)- if let deltaData = try? JSONSerialization.data(withJSONObject: delta, options: [.fragmentsAllowed]),- let deltaString = String(data: deltaData, encoding: .utf8)- {- DebugLogger.shared.debug("LLMClient: Full Delta: \(deltaString)", source: "LLMClient")+ // Preserve bounded raw diagnostics without re-serializing every token.+ if thinkingBuffer.count + contentBuffer.count < 8 || delta["tool_calls"] != nil {+ let rawDelta = jsonString+ DebugLogger.shared.logLazy(level: .debug, source: "LLMClient") {+ "LLMClient: Full Delta: \(rawDelta)"+ }}// Handle separate reasoning fields (OpenAI 'reasoning', 'reasoning_content', DeepSeek, etc.)@@ -681,6 +722,10 @@ final class LLMClient {state = .inContentconfig.onThinkingEnd?()}+ if !didLogFirstContent, !content.isEmpty {+ didLogFirstContent = true+ self.benchmark(config, "first_content")+ }contentBuffer.append(content)config.onContentChunk?(content)} else {@@ -725,6 +770,10 @@ final class LLMClient {config.onThinkingChunk?(thinkChunk)}if !contentChunk.isEmpty {+ if !didLogFirstContent {+ didLogFirstContent = true+ self.benchmark(config, "first_content")+ }contentBuffer.append(contentChunk)config.onContentChunk?(contentChunk)}@@ -787,11 +836,13 @@ final class LLMClient {DebugLogger.shared.debug("LLMClient: Returning response. Content length: \(contentText.count), Has thinking: \(thinkingText.isEmpty ? "No" : "Yes (\(thinkingText.count) chars)")", source: "LLMClient")- return Response(+ let parsed = Response(thinking: thinkingText.isEmpty ? nil : thinkingText,content: contentText,toolCalls: parsedToolCalls)+ self.benchmark(config, "response_decoded")+ return parsed}// MARK: - Parse Non-Streaming Message@@ -1011,21 +1062,12 @@ final class LLMClient {// MARK: - Logging Helpers- private func logRequest(_ request: URLRequest) {- guard let url = request.url, let method = request.httpMethod else { return }-- var bodyString = ""- if let body = request.httpBody {- bodyString = String(data: body, encoding: .utf8) ?? ""- }-- var curl = "curl -X \(method) \"\(url.absoluteString)\" \\\n"- for (key, value) in request.allHTTPHeaderFields ?? [:] {- let maskedValue = key.lowercased().contains("auth") ? "Bearer [REDACTED]" : value- curl += " -H \"\(key): \(maskedValue)\" \\\n"- }- curl += " -d '\(bodyString)'"-- DebugLogger.shared.info("LLMClient: Full Request as cURL:\n\(curl)", source: "LLMClient")+ private func benchmark(_ config: Config, _ message: String) {+ guard let id = config.benchmarkID else { return }+ DebugLogger.shared.benchmark(+ "LLM_BENCH",+ message: "id=\(id) \(message)",+ source: "LLMBenchmark"+ )}}diff --git a/Sources/Fluid/Services/LocalAPI/HistoryAPIController.swift b/Sources/Fluid/Services/LocalAPI/HistoryAPIController.swiftindex 25f783f4..afea1b7f 100644--- a/Sources/Fluid/Services/LocalAPI/HistoryAPIController.swift+++ b/Sources/Fluid/Services/LocalAPI/HistoryAPIController.swift@@ -29,6 +29,11 @@ struct HistoryAPIController: LocalAPIRouteHandler {}let limit = LocalAPI.boundedLimit(from: request)+ do {+ try await TranscriptionHistoryStore.shared.waitUntilLoaded()+ } catch {+ return LocalAPI.error("History is unavailable. Retry from History in FluidVoice.", status: 503)+ }let items = TranscriptionHistoryStore.shared.entries.prefix(limit).map { entry indiff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swiftindex f50fd358..c76c65d1 100644--- a/Sources/Fluid/Services/MenuBarManager.swift+++ b/Sources/Fluid/Services/MenuBarManager.swift@@ -26,6 +26,8 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {// References to app stateprivate weak var asrService: ASRService?private var cancellables = Set<AnyCancellable>()+ private var hasDeferredStopMenuRefresh = false+ private var hasDeferredStoppedRecordingState = falseprivate var configuredASRIdentifier: ObjectIdentifier?/// Overlay management (persistent, independent of window lifecycle)@@ -105,12 +107,38 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {asrService.$isRunning.receive(on: DispatchQueue.main).sink { [weak self] isRunning in- self?.isRecording = isRunning- self?.updateMenuBarIcon()- self?.updateMenu()+ guard let self else { return }+ if isRunning == false, self.isProcessingActive {+ self.hasDeferredStoppedRecordingState = true+ self.overlayBench("recording_state_deferred reason=processing_active")+ self.handleOverlayState(isRunning: false, asrService: asrService)+ return+ }+ if isRunning {+ self.hasDeferredStoppedRecordingState = false+ }+ self.isRecording = isRunning+ self.updateMenuBarIcon()+ if asrService.defersStopUIInvalidation {+ self.hasDeferredStopMenuRefresh = true+ } else {+ self.updateMenu()+ }// Handle overlay lifecycle (independent of window state)- self?.handleOverlayState(isRunning: isRunning, asrService: asrService)+ self.handleOverlayState(isRunning: isRunning, asrService: asrService)+ }+ .store(in: &self.cancellables)++ asrService.deferredStopUIInvalidationDidFlush+ .receive(on: DispatchQueue.main)+ .sink { [weak self] in+ guard let self,+ self.hasDeferredStopMenuRefresh,+ self.hasDeferredStoppedRecordingState == false+ else { return }+ self.hasDeferredStopMenuRefresh = false+ self.updateMenu()}.store(in: &self.cancellables)@@ -348,19 +376,26 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {NotchOverlayManager.shared.setMode(mode)}+ /// Keeps the recording overlay owned by the active pipeline without+ /// publishing processing UI. The latency-critical stop path uses this so+ /// SwiftUI work cannot queue ahead of final transcription.+ func reserveProcessingOverlay() {+ self.overlayBench(+ "reserve_processing overlayVisible=\(self.overlayVisible) active=\(self.isProcessingActive)"+ )+ self.isProcessingActive = true+ self.pendingProcessingShowOperation?.cancel()+ self.pendingProcessingShowOperation = nil+ self.pendingHideOperation?.cancel()+ self.pendingHideOperation = nil+ self.overlayVisible = true+ }+func setProcessing(_ processing: Bool) {self.overlayBench("set_processing_request processing=\(processing) overlayVisible=\(self.overlayVisible) active=\(self.isProcessingActive)")- // Track processing state to prevent hide during AI refinement- self.isProcessingActive = processing- self.updateMenuItemsText()-if processing {- self.pendingProcessingShowOperation?.cancel()- // Cancel any pending hide - we want to keep the overlay visible for AI processing- self.pendingHideOperation?.cancel()- self.pendingHideOperation = nil- self.overlayVisible = true+ self.reserveProcessingOverlay()let showItem = DispatchWorkItem { [weak self] inguard let self = self, self.isProcessingActive else { return }@@ -372,6 +407,8 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {self.pendingProcessingShowOperation = showItemDispatchQueue.main.asyncAfter(deadline: .now() + self.processingVisualDelay, execute: showItem)} else {+ defer { self.flushDeferredStoppedRecordingState() }+ self.isProcessingActive = falseself.pendingProcessingShowOperation?.cancel()self.pendingProcessingShowOperation = nil// When processing ends, schedule the hide (unless expanded output is showing)@@ -407,18 +444,29 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {}}+ /// Removes the successful recording overlay after insertion completes. There+ /// is intentionally no separate exit animation on this latency-critical path.+ func beginProcessingCompletionAndHideOverlay() {+ let startedAt = ProcessInfo.processInfo.systemUptime+ self.prepareForProcessingCompletion()+ self.overlayBench("finish_hide_request mode=immediate")+ NotchOverlayManager.shared.hideImmediately()+ self.flushDeferredStoppedRecordingState()+ self.overlayBench(+ "finish_hide_complete mode=immediate elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - startedAt) * 1000).rounded()))"+ )+ }+/// Ends processing and waits for the recording overlay's exit transition.- /// Output paths normally call this asynchronously after insertion dispatch- /// so the exit animation cannot delay text delivery.+ /// Use only when the caller must know the overlay has fully disappeared.func finishProcessingAndHideOverlay() async {let startedAt = ProcessInfo.processInfo.systemUptime- self.cancelPendingProcessingCompletionOperations()- self.isProcessingActive = false- self.overlayVisible = false+ self.prepareForProcessingCompletion()NotchOverlayManager.shared.setProcessing(false)- self.overlayBench("finish_hide_request")+ self.overlayBench("finish_hide_request mode=awaited")let hideOutcome = await NotchOverlayManager.shared.hideAndWait()+ self.flushDeferredStoppedRecordingState()self.overlayBench("finish_hide_complete outcome=\(hideOutcome) elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - startedAt) * 1000).rounded()))")@@ -433,9 +481,26 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {// ownership so the next recording can establish a fresh lifecycle.self.overlayVisible = falseNotchOverlayManager.shared.setProcessing(false)+ self.flushDeferredStoppedRecordingState()self.overlayBench("finish_keep_visible")}+ /// Recording-state observers rebuild AppKit/SwiftUI surfaces. Hold that work+ /// while a fast ASR/AI result is in flight, then publish it after output.+ /// Slow paths call this when their processing status becomes visible.+ func flushDeferredStoppedRecordingState() {+ guard self.hasDeferredStoppedRecordingState else { return }+ let startedAt = ProcessInfo.processInfo.systemUptime+ self.hasDeferredStoppedRecordingState = false+ self.hasDeferredStopMenuRefresh = false+ self.isRecording = false+ self.updateMenuBarIcon()+ self.updateMenu()+ self.overlayBench(+ "recording_state_flushed elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - startedAt) * 1000).rounded()))"+ )+ }+private func cancelPendingProcessingCompletionOperations() {self.pendingProcessingShowOperation?.cancel()self.pendingProcessingShowOperation = nil@@ -445,6 +510,12 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {self.pendingShowOperation = nil}+ private func prepareForProcessingCompletion() {+ self.cancelPendingProcessingCompletionOperations()+ self.isProcessingActive = false+ self.overlayVisible = false+ }+private func overlayBench(_ message: String) {DebugLogger.shared.benchmark("OVERLAY_BENCH", message: "manager \(message)", source: "OverlayBenchmark")}diff --git a/Sources/Fluid/Services/NotchOverlayManager.swift b/Sources/Fluid/Services/NotchOverlayManager.swiftindex 6a754fae..c1015328 100644--- a/Sources/Fluid/Services/NotchOverlayManager.swift+++ b/Sources/Fluid/Services/NotchOverlayManager.swift@@ -316,6 +316,9 @@ final class NotchOverlayManager {self.generation &+= 1let currentGeneration = self.generationself.activeHideGeneration = currentGeneration+ if self.isBottomOverlayVisible {+ BottomOverlayWindowController.shared.hide()+ }Task { [weak self] inguard let self else { return }let outcome = await self.performHideAndWait(generation: currentGeneration)@@ -323,6 +326,41 @@ final class NotchOverlayManager {}}+ /// Removes a successfully completed recording overlay synchronously so it+ /// cannot outlive the text insertion that follows.+ func hideImmediately() {+ let startedAt = ProcessInfo.processInfo.systemUptime+ self.generation &+= 1+ let currentGeneration = self.generation++ self.activeHideGeneration = nil+ self.isHideInProgress = false+ let waiters = self.hideWaiters+ self.hideWaiters.removeAll(keepingCapacity: true)++ if self.isBottomOverlayVisible {+ BottomOverlayWindowController.shared.hideImmediately()+ self.isBottomOverlayVisible = false+ }++ if self.notch != nil || self.state != .idle {+ self.retireCurrentNotchImmediately(reason: "completed_output")+ }++ waiters.forEach { $0.resume(returning: .hidden) }+ Self.overlayBench("hide_immediate_complete elapsedMs=\(Self.elapsedMs(since: startedAt))")++ Task { @MainActor [weak self] in+ await Task.yield()+ guard let self, self.generation == currentGeneration else { return }+ ActiveAppMonitor.shared.stopMonitoring()+ NotchContentState.shared.setProcessing(false)+ NotchContentState.shared.updateTranscription("")+ NotchContentState.shared.setSpokenSendIndicatorState(.hidden)+ Self.overlayBench("hide_immediate_cleanup_complete")+ }+ }+/// Reports whether the active overlay finished hiding or a newer/// presentation superseded this request.func hideAndWait() async -> RecordingOverlayHideOutcome {diff --git a/Sources/Fluid/Services/PasteKeyCodeCache.swift b/Sources/Fluid/Services/PasteKeyCodeCache.swiftnew file mode 100644index 00000000..4d569606--- /dev/null+++ b/Sources/Fluid/Services/PasteKeyCodeCache.swift@@ -0,0 +1,66 @@+import AppKit+import Carbon.HIToolbox++/// One process-wide snapshot, refreshed at launch and on input-source notifications.+/// Paste requests only read the snapshot and never dispatch to the main queue.+final class PasteKeyCodeCache: @unchecked Sendable {+ private let lock = NSLock()+ private var keyCode: CGKeyCode = 9+ private var observer: NSObjectProtocol?+ private let resolve: () -> CGKeyCode+ private let notificationName: Notification.Name+ private var refreshScheduled = false++ init(+ notificationName: Notification.Name = Notification.Name(kTISNotifySelectedKeyboardInputSourceChanged as String),+ resolve: @escaping () -> CGKeyCode+ ) {+ self.notificationName = notificationName+ self.resolve = resolve+ }++ func start() {+ precondition(Thread.isMainThread)+ guard self.observer == nil else { return }+ self.observer = DistributedNotificationCenter.default().addObserver(+ forName: self.notificationName,+ object: nil,+ queue: .main+ ) { [weak self] _ in+ self?.scheduleRefresh()+ }+ self.refresh()+ }++ private func scheduleRefresh() {+ precondition(Thread.isMainThread)+ guard !self.refreshScheduled else { return }+ self.refreshScheduled = true+ // Let TIS process the source-change event before reading its current layout.+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ self.refreshScheduled = false+ self.refresh()+ }+ }++ private func refresh() {+ precondition(Thread.isMainThread)+ let updated = self.resolve()+ self.lock.lock()+ self.keyCode = updated+ self.lock.unlock()+ }++ func snapshot() -> CGKeyCode {+ self.lock.lock()+ defer { self.lock.unlock() }+ return self.keyCode+ }++ deinit {+ if let observer {+ DistributedNotificationCenter.default().removeObserver(observer)+ }+ }+}diff --git a/Sources/Fluid/Services/PasteKeyCodeResolver.swift b/Sources/Fluid/Services/PasteKeyCodeResolver.swiftnew file mode 100644index 00000000..2f9a1c75--- /dev/null+++ b/Sources/Fluid/Services/PasteKeyCodeResolver.swift@@ -0,0 +1,41 @@+import Carbon.HIToolbox+import Foundation++enum PasteKeyCodeResolver {+ /// Resolve the shortcut with Command held, not the unmodified typing character.+ /// Dvorak-QWERTY Command and non-Latin layouts can use different shortcut mappings.+ static func current() -> CGKeyCode {+ precondition(Thread.isMainThread)+ guard let source = TISCopyCurrentKeyboardLayoutInputSource()?.takeRetainedValue(),+ let pointer = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData)+ else { return 9 }+ let data = Unmanaged<CFData>.fromOpaque(pointer).takeUnretainedValue() as Data+ return self.resolve(layoutData: data, keyboardType: UInt32(LMGetKbdType()))+ }++ static func resolve(layoutData: Data?, keyboardType: UInt32) -> CGKeyCode {+ guard let layoutData, !layoutData.isEmpty else { return 9 }+ return layoutData.withUnsafeBytes { bytes -> CGKeyCode in+ guard let layout = bytes.baseAddress?.assumingMemoryBound(to: UCKeyboardLayout.self) else { return 9 }+ var characters = [UniChar](repeating: 0, count: 4)+ for key: UInt16 in 0..<128 {+ var dead: UInt32 = 0+ var length = 0+ let status = UCKeyTranslate(+ layout,+ key,+ UInt16(kUCKeyActionDisplay),+ UInt32(cmdKey >> 8),+ keyboardType,+ UInt32(kUCKeyTranslateNoDeadKeysMask),+ &dead,+ characters.count,+ &length,+ &characters+ )+ if status == noErr, length == 1, characters[0] == 118 { return key }+ }+ return 9+ }+ }+}diff --git a/Sources/Fluid/Services/PrivateAIIntegrationService.swift b/Sources/Fluid/Services/PrivateAIIntegrationService.swiftindex 16ab4578..bd1356ae 100644--- a/Sources/Fluid/Services/PrivateAIIntegrationService.swift+++ b/Sources/Fluid/Services/PrivateAIIntegrationService.swift@@ -2,6 +2,7 @@ import Foundationactor PrivateAIIntegrationService {static let shared = PrivateAIIntegrationService()+ private nonisolated let dictationProviderOverride: (any PrivateAIIntegrationProviding)?static var selectedModelDefaultsKey: String {PrivateAIProviderFeature.shared.selectedModelDefaultsKey@@ -55,7 +56,15 @@ actor PrivateAIIntegrationService {let message: String?}- private init() {}+ private init() {+ self.dictationProviderOverride = nil+ }++ #if DEBUG+ init(testingProvider: any PrivateAIIntegrationProviding) {+ self.dictationProviderOverride = testingProvider+ }+ #endifprivate nonisolated static var provider: any PrivateAIIntegrationProviding {PrivateAIProviderFeature.shared.isAvailable@@ -63,6 +72,10 @@ actor PrivateAIIntegrationService {: UnavailableAIIntegrationShim.shared}+ private nonisolated var dictationProvider: any PrivateAIIntegrationProviding {+ self.dictationProviderOverride ?? Self.provider+ }+nonisolated static var configuredModelID: String {provider.configuredModelID}@@ -240,31 +253,40 @@ actor PrivateAIIntegrationService {await Self.provider.shutdownForTermination()}- func enhanceDictation(+ nonisolated func enhanceDictation(_ inputText: String,runtime: RuntimeConfiguration,context: AppContext) async throws -> EnhancementResult {- try Self.validateDictationHeadroom(inputText, contextTokenLimit: runtime.contextTokenLimit)- return try await Self.provider.enhanceDictation(inputText, runtime: runtime, context: context)+ let budget = try Self.validatedDictationBudget(inputText, contextTokenLimit: runtime.contextTokenLimit)+ return try await self.dictationProvider.enhanceDictation(+ inputText,+ runtime: runtime,+ context: context,+ maxOutputTokens: budget.maxOutputTokens+ )}- func enhanceDictation(+ nonisolated func enhanceDictation(_ inputText: String,runtime: RuntimeConfiguration,context: AppContext,streamHandler: PrivateAIStreamHandler?) async throws -> EnhancementResult {- try Self.validateDictationHeadroom(inputText, contextTokenLimit: runtime.contextTokenLimit)- return try await Self.provider.enhanceDictation(+ let budget = try Self.validatedDictationBudget(inputText, contextTokenLimit: runtime.contextTokenLimit)+ return try await self.dictationProvider.enhanceDictation(inputText,runtime: runtime,context: context,+ maxOutputTokens: budget.maxOutputTokens,streamHandler: streamHandler)}- private nonisolated static func validateDictationHeadroom(_ inputText: String, contextTokenLimit: Int) throws {+ private nonisolated static func validatedDictationBudget(+ _ inputText: String,+ contextTokenLimit: Int+ ) throws -> SettingsStore.PrivateAIDictationTokenBudget {let budget = SettingsStore.privateAIDictationTokenBudget(forInputText: inputText,contextTokenLimit: contextTokenLimit@@ -272,6 +294,7 @@ actor PrivateAIIntegrationService {guard budget.hasSufficientHeadroom else {throw AIProcessingError.dictationExceedsAIContextWindow}+ return budget}func rewrite(@@ -348,10 +371,11 @@ private struct UnavailableAIIntegrationShim: PrivateAIIntegrationProviding {func unloadCachedRuntime(reason _: String) async {}- func enhanceDictation(+ nonisolated func enhanceDictation(_ inputText: String,runtime _: PrivateAIIntegrationService.RuntimeConfiguration,- context _: PrivateAIIntegrationService.AppContext+ context _: PrivateAIIntegrationService.AppContext,+ maxOutputTokens _: Int) async throws -> PrivateAIIntegrationService.EnhancementResult {PrivateAIIntegrationService.EnhancementResult(outputText: inputText,diff --git a/Sources/Fluid/Services/PrivateAIProvider.swift b/Sources/Fluid/Services/PrivateAIProvider.swiftindex 3b4ffbc9..6e6b9486 100644--- a/Sources/Fluid/Services/PrivateAIProvider.swift+++ b/Sources/Fluid/Services/PrivateAIProvider.swift@@ -260,15 +260,17 @@ protocol PrivateAIIntegrationProviding: Sendable {func prewarmDictation() asyncfunc unloadCachedRuntime(reason: String) asyncfunc shutdownForTermination() async- func enhanceDictation(+ nonisolated func enhanceDictation(_ inputText: String,runtime: PrivateAIIntegrationService.RuntimeConfiguration,- context: PrivateAIIntegrationService.AppContext+ context: PrivateAIIntegrationService.AppContext,+ maxOutputTokens: Int) async throws -> PrivateAIIntegrationService.EnhancementResult- func enhanceDictation(+ nonisolated func enhanceDictation(_ inputText: String,runtime: PrivateAIIntegrationService.RuntimeConfiguration,context: PrivateAIIntegrationService.AppContext,+ maxOutputTokens: Int,streamHandler: PrivateAIStreamHandler?) async throws -> PrivateAIIntegrationService.EnhancementResultfunc rewrite(@@ -318,13 +320,19 @@ extension PrivateAIIntegrationProviding {await self.unloadCachedRuntime(reason: "termination")}- func enhanceDictation(+ nonisolated func enhanceDictation(_ inputText: String,runtime: PrivateAIIntegrationService.RuntimeConfiguration,context: PrivateAIIntegrationService.AppContext,+ maxOutputTokens: Int,streamHandler _: PrivateAIStreamHandler?) async throws -> PrivateAIIntegrationService.EnhancementResult {- try await self.enhanceDictation(inputText, runtime: runtime, context: context)+ try await self.enhanceDictation(+ inputText,+ runtime: runtime,+ context: context,+ maxOutputTokens: maxOutputTokens+ )}func rewrite(@@ -509,10 +517,11 @@ private struct UnavailablePrivateAIIntegrationProvider: PrivateAIIntegrationProvfunc unloadCachedRuntime(reason _: String) async {}- func enhanceDictation(+ nonisolated func enhanceDictation(_ inputText: String,runtime _: PrivateAIIntegrationService.RuntimeConfiguration,- context _: PrivateAIIntegrationService.AppContext+ context _: PrivateAIIntegrationService.AppContext,+ maxOutputTokens _: Int) async throws -> PrivateAIIntegrationService.EnhancementResult {PrivateAIIntegrationService.EnhancementResult(outputText: inputText,diff --git a/Sources/Fluid/Services/ThinkingParsers.swift b/Sources/Fluid/Services/ThinkingParsers.swiftindex 5cff3cac..625fbd40 100644--- a/Sources/Fluid/Services/ThinkingParsers.swift+++ b/Sources/Fluid/Services/ThinkingParsers.swift@@ -4,7 +4,7 @@ import Foundation/// Protocol for parsing thinking tokens from LLM streaming responses./// Different model families have different patterns for thinking tokens.-protocol ThinkingParser {+nonisolated protocol ThinkingParser {/// Process a content chunk during streaming./// - Parameters:/// - chunk: The new content chunk from the stream@@ -29,7 +29,7 @@ protocol ThinkingParser {// MARK: - Parser State-enum ThinkingParserState {+nonisolated enum ThinkingParserState {case initial // Haven't determined if we're in thinking or content yetcase inThinking // Currently inside thinking sectioncase inContent // Currently in main content@@ -38,7 +38,7 @@ enum ThinkingParserState {// MARK: - Parser Factory/// Factory to create the appropriate parser and extra parameters based on model name-enum ThinkingParserFactory {+nonisolated enum ThinkingParserFactory {/// Create a parser appropriate for the given modelstatic func createParser(for model: String) -> ThinkingParser {let modelLower = model.lowercased()@@ -61,10 +61,15 @@ enum ThinkingParserFactory {return SeparateFieldThinkingParser()}- // OpenAI reasoning models (o1, o3, gpt-5): use SeparateFieldThinkingParser- if SettingsStore.shared.isReasoningModel(model) &&- (modelLower.contains("gpt-5") || modelLower.contains("o1") || modelLower.contains("o3") || modelLower.contains("gpt-oss"))- {+ // OpenAI reasoning models (o1, o3, o4, gpt-5): use SeparateFieldThinkingParser+ var family = modelLower+ if let slash = family.firstIndex(of: "/") {+ family = String(family[family.index(after: slash)...])+ }+ let isOpenAIReasoningModel = family.hasPrefix("gpt-5") ||+ family.contains("gpt-5.") || family.hasPrefix("o1") ||+ family.hasPrefix("o3") || family.hasPrefix("o4") || family.contains("gpt-oss")+ if isOpenAIReasoningModel {DebugLogger.shared.debug("ThinkingParser: Using SeparateFieldParser for reasoning model '\(model)'", source: "LLMClient")return SeparateFieldThinkingParser()}@@ -107,7 +112,7 @@ enum ThinkingParserFactory {/// Standard parser for models that use `<think>...</think>` or `<thinking>...</thinking>` tags./// Used by: DeepSeek, Qwen, Claude (when thinking enabled), most open models-struct StandardThinkingParser: ThinkingParser {+nonisolated struct StandardThinkingParser: ThinkingParser {mutating func processChunk(_ chunk: String,currentState: ThinkingParserState,@@ -194,7 +199,7 @@ struct StandardThinkingParser: ThinkingParser {/// Parser for Nemotron/Nemo models that output thinking WITHOUT an opening <think> tag./// Pattern: `thinking content</think>actual response`/// Everything before `</think>` is thinking, everything after is content.-struct NemoThinkingParser: ThinkingParser {+nonisolated struct NemoThinkingParser: ThinkingParser {mutating func processChunk(_ chunk: String,currentState: ThinkingParserState,@@ -278,7 +283,7 @@ struct NemoThinkingParser: ThinkingParser {/// Parser for models that don't use thinking tokens at all./// Everything is content.-struct NoThinkingParser: ThinkingParser {+nonisolated struct NoThinkingParser: ThinkingParser {mutating func processChunk(_ chunk: String,currentState: ThinkingParserState,@@ -298,7 +303,7 @@ struct NoThinkingParser: ThinkingParser {/// Parser for models that use separate fields (reasoning_content, thought, etc.)/// instead of inline tags like <think>./// Used by: OpenAI o1/o3/gpt-5, DeepSeek (official API).-struct SeparateFieldThinkingParser: ThinkingParser {+nonisolated struct SeparateFieldThinkingParser: ThinkingParser {mutating func processChunk(_ chunk: String,currentState: ThinkingParserState,diff --git a/Sources/Fluid/Services/TypingService.swift b/Sources/Fluid/Services/TypingService.swiftindex 4ee2ac38..a3849cfc 100644--- a/Sources/Fluid/Services/TypingService.swift+++ b/Sources/Fluid/Services/TypingService.swift@@ -131,69 +131,28 @@ final class TypingService {// MARK: - Layout-aware key code lookup- /// Returns the virtual key code that produces `character` under the current keyboard layout.- /// Uses the TIS (Text Input Services) API which must run on the main thread, so the lookup- /// is dispatched there when called from a background thread. Falls back to `qwertyFallback`- /// if the layout data is unavailable.- private static func virtualKeyCode(for character: Character, qwertyFallback: CGKeyCode) -> CGKeyCode {- if Thread.isMainThread {- return self.tisLookup(for: character, qwertyFallback: qwertyFallback)- }- var result = qwertyFallback- DispatchQueue.main.sync {- result = self.tisLookup(for: character, qwertyFallback: qwertyFallback)- }- return result+ private static let pasteKeyCache = PasteKeyCodeCache {+ let key = PasteKeyCodeResolver.current()+ DebugLogger.shared.benchmark("TYPING_BENCH", message: "paste_key_cache_refresh keyCode=\(key)", source: "TypingBenchmark")+ return key}- /// Performs the actual TIS + UCKeyTranslate scan. Must be called on the main thread.- private static func tisLookup(for character: Character, qwertyFallback: CGKeyCode) -> CGKeyCode {- guard let targetScalar = character.unicodeScalars.first else { return qwertyFallback }-- guard let sourceRef = TISCopyCurrentKeyboardLayoutInputSource()?.takeRetainedValue(),- let rawPtr = TISGetInputSourceProperty(sourceRef, kTISPropertyUnicodeKeyLayoutData)- else {- return qwertyFallback- }- let layoutData = Unmanaged<CFData>.fromOpaque(rawPtr).takeUnretainedValue() as Data-- return layoutData.withUnsafeBytes { buffer -> CGKeyCode in- guard let layoutPtr = buffer.baseAddress?.assumingMemoryBound(to: UCKeyboardLayout.self) else {- return qwertyFallback- }- var deadKeyState: UInt32 = 0- var chars = [UniChar](repeating: 0, count: 4)- var length = 0- let kbType = UInt32(LMGetKbdType())-- for keyCode: UInt16 in 0..<128 {- deadKeyState = 0- length = 0- let status = UCKeyTranslate(- layoutPtr,- keyCode,- UInt16(kUCKeyActionDisplay),- 0,- kbType,- UInt32(kUCKeyTranslateNoDeadKeysMask),- &deadKeyState,- chars.count,- &length,- &chars- )- guard status == noErr, length > 0 else { continue }- if Unicode.Scalar(chars[0]) == targetScalar {- return CGKeyCode(keyCode)- }- }- return qwertyFallback- }+ /// Called during application launch, before any paste requests can arrive.+ static func startKeyboardLayoutTracking() {+ self.pasteKeyCache.start()}/// The virtual key code for "v" in the current keyboard layout (used for Cmd+V paste).- /// Re-evaluated on every call so runtime keyboard layout switches are picked up immediately.+ /// Refreshed by the input-source notification, never by a background paste request.private static var pasteVirtualKeyCode: CGKeyCode {- virtualKeyCode(for: "v", qwertyFallback: 9)+ let startedAt = ProcessInfo.processInfo.systemUptime+ let key = self.pasteKeyCache.snapshot()+ DebugLogger.shared.benchmark(+ "TYPING_BENCH",+ message: "paste_key_lookup queueMs=0 lookupMs=\((ProcessInfo.processInfo.systemUptime - startedAt) * 1000) returnMs=0 cached=true keyCode=\(key)",+ source: "TypingBenchmark"+ )+ return key}// MARK: - Focus helpers (shared)@@ -423,7 +382,7 @@ final class TypingService {tracksDictionaryCorrections: Bool = false,postInsertionKey: SettingsStore.SpokenSendKey? = nil,requiredFocusTarget: CapturedFocusTarget? = nil,- completion: ((DeliveryOutcome) -> Void)? = nil+ completion: (@MainActor (DeliveryOutcome) -> Void)? = nil) {let requestedAt = ProcessInfo.processInfo.systemUptimelet text = plan.plainText@@ -468,96 +427,110 @@ final class TypingService {self.log("[TypingService] Accessibility check passed, proceeding with text injection")self.isCurrentlyTyping = true+ let pipelineID = DebugLogger.pipelineIDDispatchQueue.global(qos: .userInitiated).async {- var outcome: DeliveryOutcome = .insertionFailed- let workerStartedAt = ProcessInfo.processInfo.systemUptime- self.bench("worker_start queueDelayMs=\(Self.elapsedMs(from: requestedAt, to: workerStartedAt))")-- defer {- let completedAt = ProcessInfo.processInfo.systemUptime- self.isCurrentlyTyping = false- self.bench(- "complete totalMs=\(Self.elapsedMs(from: requestedAt, to: completedAt)) textReadyToCompleteMs=\(textReadyAt.map { String(Self.elapsedMs(from: $0, to: completedAt)) } ?? "nil")"- )- self.log("[TypingService] Typing operation completed, isCurrentlyTyping set to false")- completion?(outcome)- }+ DebugLogger.$pipelineID.withValue(pipelineID) {+ var outcome: DeliveryOutcome = .insertionFailed+ let workerStartedAt = ProcessInfo.processInfo.systemUptime+ self.bench("worker_start queueDelayMs=\(Self.elapsedMs(from: requestedAt, to: workerStartedAt))")++ defer {+ let completedAt = ProcessInfo.processInfo.systemUptime+ self.isCurrentlyTyping = false+ self.bench(+ "complete totalMs=\(Self.elapsedMs(from: requestedAt, to: completedAt)) textReadyToCompleteMs=\(textReadyAt.map { String(Self.elapsedMs(from: $0, to: completedAt)) } ?? "nil")"+ )+ self.log("[TypingService] Typing operation completed, isCurrentlyTyping set to false")+ let completedOutcome = outcome+ Task { @MainActor in+ self.bench(+ "delivery_main_begin queueMs=\(Self.elapsedMs(from: completedAt, to: ProcessInfo.processInfo.systemUptime))"+ )+ // Delivery UI must finish before correction tracking performs+ // any synchronous Accessibility queries on the main thread.+ completion?(completedOutcome)+ self.bench("delivery_main_callback_return")+ if tracksDictionaryCorrections,+ postInsertionKey == nil,+ completedOutcome.didInsert+ {+ AutomaticDictionaryCorrectionTracker.shared.beginObservingInsertion(+ text,+ targetPID: preferredTargetPID+ )+ self.bench("dictionary_tracking_scheduled afterDeliveryCallback=true")+ }+ }+ }- self.log("[TypingService] Starting async text insertion process")- if settleDelayMs > 0 {- usleep(useconds_t(settleDelayMs * 1000))- }- self.bench("settle_delay_done delayMs=\(settleDelayMs) elapsedMs=\(Self.elapsedMs(since: requestedAt))")- let hasTextToInsert = !text.isEmpty- if postInsertionKey != nil {+ self.log("[TypingService] Starting async text insertion process")+ if settleDelayMs > 0 {+ usleep(useconds_t(settleDelayMs * 1000))+ }+ self.bench("settle_delay_done delayMs=\(settleDelayMs) elapsedMs=\(Self.elapsedMs(since: requestedAt))")+ let hasTextToInsert = !text.isEmpty+ if postInsertionKey != nil {+ guard let preferredTargetPID, let requiredFocusTarget else {+ outcome = .actionSuppressed+ return+ }+ // A held dictation modifier must suppress only the key action,+ // not the dictated text. The longer check below waits for+ // modifiers after insertion before deciding whether to send.+ guard Self.canInsertBeforePostInsertionAction(+ preferredTargetPID: preferredTargetPID,+ requiredTargetPID: requiredFocusTarget.pid,+ isSecureTextField: requiredFocusTarget.isSecureTextField,+ exactFocusIsActive: Self.isExactFocusTargetActive(requiredFocusTarget)+ ) else {+ outcome = .actionSuppressed+ return+ }+ }++ if hasTextToInsert {+ self.log("[TypingService] Delay completed, calling insertTextInstantly")+ let insertStartedAt = ProcessInfo.processInfo.systemUptime+ self.bench("insert_call")+ let inserted = self.insertTextInstantly(text, preferredTargetPID: preferredTargetPID)+ self.bench(+ "insert_return elapsedMs=\(Self.elapsedMs(since: insertStartedAt)) totalMs=\(Self.elapsedMs(since: requestedAt))"+ )+ guard inserted else {+ outcome = .insertionFailed+ return+ }++ outcome = .inserted+ }++ guard let postInsertionKey else { return }guard let preferredTargetPID, let requiredFocusTarget else {- outcome = .actionSuppressed+ outcome = hasTextToInsert ? .insertedActionSuppressed : .actionSuppressedreturn}- // A held dictation modifier must suppress only the key action,- // not the dictated text. The longer check below waits for- // modifiers after insertion before deciding whether to send.- guard Self.canInsertBeforePostInsertionAction(+ let modifiersReleased = self.waitForPhysicalModifiersToRelease(timeout: 2)+ let exactFocusIsActive = Self.isExactFocusTargetActive(requiredFocusTarget)+ guard Self.canDispatchPostInsertionAction(preferredTargetPID: preferredTargetPID,requiredTargetPID: requiredFocusTarget.pid,isSecureTextField: requiredFocusTarget.isSecureTextField,- exactFocusIsActive: Self.isExactFocusTargetActive(requiredFocusTarget)+ modifiersReleased: modifiersReleased,+ exactFocusIsActive: exactFocusIsActive) else {- outcome = .actionSuppressed+ outcome = hasTextToInsert ? .insertedActionSuppressed : .actionSuppressedreturn}- }- if hasTextToInsert {- self.log("[TypingService] Delay completed, calling insertTextInstantly")- let insertStartedAt = ProcessInfo.processInfo.systemUptime- self.bench("insert_call")- let inserted = self.insertTextInstantly(text, preferredTargetPID: preferredTargetPID)- self.bench(- "insert_return elapsedMs=\(Self.elapsedMs(since: insertStartedAt)) totalMs=\(Self.elapsedMs(since: requestedAt))"- )- guard inserted else {- outcome = .insertionFailed+ usleep(50_000)+ guard Self.isExactFocusTargetActive(requiredFocusTarget),+ self.postReturnKey(postInsertionKey, targetPID: preferredTargetPID)+ else {+ outcome = hasTextToInsert ? .insertedActionSuppressed : .actionSuppressedreturn}-- outcome = .inserted- if tracksDictionaryCorrections, postInsertionKey == nil {- Task { @MainActor in- AutomaticDictionaryCorrectionTracker.shared.beginObservingInsertion(- text,- targetPID: preferredTargetPID- )- }- }+ outcome = hasTextToInsert ? .insertedAndActionDispatched : .actionDispatched}-- guard let postInsertionKey else { return }- guard let preferredTargetPID, let requiredFocusTarget else {- outcome = hasTextToInsert ? .insertedActionSuppressed : .actionSuppressed- return- }- let modifiersReleased = self.waitForPhysicalModifiersToRelease(timeout: 2)- let exactFocusIsActive = Self.isExactFocusTargetActive(requiredFocusTarget)- guard Self.canDispatchPostInsertionAction(- preferredTargetPID: preferredTargetPID,- requiredTargetPID: requiredFocusTarget.pid,- isSecureTextField: requiredFocusTarget.isSecureTextField,- modifiersReleased: modifiersReleased,- exactFocusIsActive: exactFocusIsActive- ) else {- outcome = hasTextToInsert ? .insertedActionSuppressed : .actionSuppressed- return- }-- usleep(50_000)- guard Self.isExactFocusTargetActive(requiredFocusTarget),- self.postReturnKey(postInsertionKey, targetPID: preferredTargetPID)- else {- outcome = hasTextToInsert ? .insertedActionSuppressed : .actionSuppressed- return- }- outcome = hasTextToInsert ? .insertedAndActionDispatched : .actionDispatched}}@@ -783,6 +756,10 @@ final class TypingService {private static func logFocusState(_ prefix: String) {guard self.isLoggingEnabled else { return }+ let startedAt = ProcessInfo.processInfo.systemUptime+ defer {+ DebugLogger.shared.info("TYPING_BENCH t=\(ProcessInfo.processInfo.systemUptime) focus_debug_query elapsedMs=\(Self.elapsedMs(since: startedAt))", source: "TypingBenchmark")+ }DebugLogger.shared.debug("\(prefix) | \(self.currentFocusDebugDescription())", source: "TypingService")}@@ -858,7 +835,9 @@ final class TypingService {restoreDelayMicros: useconds_t,action: () -> Bool) -> Bool {+ let pasteboardWaitStartedAt = ProcessInfo.processInfo.systemUptimeSelf.pasteboardSessionSemaphore.wait()+ self.bench("pasteboard_lock_acquired elapsedMs=\(Self.elapsedMs(since: pasteboardWaitStartedAt))")var releasesPasteboardSessionOnReturn = truedefer {if releasesPasteboardSessionOnReturn {@@ -867,8 +846,11 @@ final class TypingService {}let pasteboard = NSPasteboard.general+ let snapshotStartedAt = ProcessInfo.processInfo.systemUptimelet snapshot = self.capturePasteboardSnapshot(pasteboard)+ self.bench("pasteboard_snapshot_done elapsedMs=\(Self.elapsedMs(since: snapshotStartedAt)) items=\(snapshot.items.count)")+ let writeStartedAt = ProcessInfo.processInfo.systemUptimepasteboard.clearContents()guard pasteboard.writeObjects([Self.makeTransientPasteboardItem(text)]) else {self.log("[TypingService] ERROR: Failed to set temporary clipboard string")@@ -876,8 +858,13 @@ final class TypingService {return false}let temporaryChangeCount = pasteboard.changeCount+ self.bench("pasteboard_write_done elapsedMs=\(Self.elapsedMs(since: writeStartedAt))")+ let focusSnapshotStartedAt = ProcessInfo.processInfo.systemUptimelet focusedTextSnapshot = self.captureFocusedTextSnapshot()+ self.bench("paste_focus_snapshot_done elapsedMs=\(Self.elapsedMs(since: focusSnapshotStartedAt))")+ let actionStartedAt = ProcessInfo.processInfo.systemUptimelet actionResult = action()+ self.bench("paste_dispatch_done elapsedMs=\(Self.elapsedMs(since: actionStartedAt)) success=\(actionResult)")guard actionResult else {self.restorePasteboardSnapshot(snapshot, to: pasteboard)self.log("[TypingService] Restored previous clipboard snapshot after paste dispatch failure")@@ -916,16 +903,21 @@ final class TypingService {return false}+ let targetStartedAt = ProcessInfo.processInfo.systemUptimeif activateTargetFirst, NSWorkspace.shared.frontmostApplication?.processIdentifier != targetPID {_ = Self.activateApp(pid: targetPID)usleep(80_000)}+ self.bench("paste_target_prepared elapsedMs=\(Self.elapsedMs(since: targetStartedAt))")return self.withTemporaryPasteboardString(text, restoreDelayMicros: 5_000_000) {+ let dispatchStartedAt = ProcessInfo.processInfo.systemUptimelet vKey = Self.pasteVirtualKeyCode+ let keyResolvedAt = ProcessInfo.processInfo.systemUptimeguard let cmdVDown = CGEvent(keyboardEventSource: nil, virtualKey: vKey, keyDown: true),let cmdVUp = CGEvent(keyboardEventSource: nil, virtualKey: vKey, keyDown: false)else {+ self.bench("paste_dispatch_failed route=pid stage=event_creation elapsedMs=\(Self.elapsedMs(since: keyResolvedAt))")self.log("[TypingService] ERROR: Failed to create Cmd+V events for PID insertion")return false}@@ -933,9 +925,19 @@ final class TypingService {cmdVDown.flags = .maskCommandcmdVUp.flags = .maskCommand+ let eventsCreatedAt = ProcessInfo.processInfo.systemUptimecmdVDown.postToPid(targetPID)+ let keyDownFinishedAt = ProcessInfo.processInfo.systemUptimeusleep(10_000)+ let waitFinishedAt = ProcessInfo.processInfo.systemUptimecmdVUp.postToPid(targetPID)+ let keyUpFinishedAt = ProcessInfo.processInfo.systemUptime+ self.bench(+ "paste_dispatch_phases route=pid keyLookupMs=\((keyResolvedAt - dispatchStartedAt) * 1000) " ++ "eventCreateMs=\((eventsCreatedAt - keyResolvedAt) * 1000) keyDownMs=\((keyDownFinishedAt - eventsCreatedAt) * 1000) " ++ "sleepMs=\((waitFinishedAt - keyDownFinishedAt) * 1000) keyUpMs=\((keyUpFinishedAt - waitFinishedAt) * 1000) " ++ "totalMs=\((keyUpFinishedAt - dispatchStartedAt) * 1000)"+ )self.log("[TypingService] Cmd+V posted to PID \(targetPID)")return true}@@ -1034,10 +1036,13 @@ final class TypingService {private func insertTextViaClipboard(_ text: String) -> Bool {self.log("[TypingService] Starting clipboard-based insertion")return self.withTemporaryPasteboardString(text, restoreDelayMicros: 5_000_000) {+ let dispatchStartedAt = ProcessInfo.processInfo.systemUptimelet vKey = Self.pasteVirtualKeyCode+ let keyResolvedAt = ProcessInfo.processInfo.systemUptimeguard let cmdVDown = CGEvent(keyboardEventSource: nil, virtualKey: vKey, keyDown: true),let cmdVUp = CGEvent(keyboardEventSource: nil, virtualKey: vKey, keyDown: false)else {+ self.bench("paste_dispatch_failed route=global stage=event_creation elapsedMs=\(Self.elapsedMs(since: keyResolvedAt))")self.log("[TypingService] ERROR: Failed to create Cmd+V events")return false}@@ -1045,9 +1050,19 @@ final class TypingService {cmdVDown.flags = .maskCommandcmdVUp.flags = .maskCommand+ let eventsCreatedAt = ProcessInfo.processInfo.systemUptimecmdVDown.post(tap: .cghidEventTap)+ let keyDownFinishedAt = ProcessInfo.processInfo.systemUptimeusleep(10_000)+ let waitFinishedAt = ProcessInfo.processInfo.systemUptimecmdVUp.post(tap: .cghidEventTap)+ let keyUpFinishedAt = ProcessInfo.processInfo.systemUptime+ self.bench(+ "paste_dispatch_phases route=global keyLookupMs=\((keyResolvedAt - dispatchStartedAt) * 1000) " ++ "eventCreateMs=\((eventsCreatedAt - keyResolvedAt) * 1000) keyDownMs=\((keyDownFinishedAt - eventsCreatedAt) * 1000) " ++ "sleepMs=\((waitFinishedAt - keyDownFinishedAt) * 1000) keyUpMs=\((keyUpFinishedAt - waitFinishedAt) * 1000) " ++ "totalMs=\((keyUpFinishedAt - dispatchStartedAt) * 1000)"+ )self.log("[TypingService] Cmd+V sent via clipboard insertion")return true}diff --git a/Sources/Fluid/UI/AnalyticsPrivacyView.swift b/Sources/Fluid/UI/AnalyticsPrivacyView.swiftindex be39a878..47ecc1bb 100644--- a/Sources/Fluid/UI/AnalyticsPrivacyView.swift+++ b/Sources/Fluid/UI/AnalyticsPrivacyView.swift@@ -32,6 +32,7 @@ struct AnalyticsPrivacyView: View {self.sectionTitle("Always collected")self.bullet("A random installation ID, app version, the operating-system label macOS, and basic hardware info.")self.bullet("One active-use signal per local day after you interact with the app, buffered on this Mac and sent weekly.")+ self.bullet("Beta builds also send one daily aggregate of ASR and Fluid Intelligence timing distributions, including macOS version. No individual timing samples are sent.")self.sectionTitle("When detailed analytics is enabled")self.bullet("Daily totals for Dictation, Command Mode, Edit Mode, and meeting transcription.")@@ -44,15 +45,16 @@ struct AnalyticsPrivacyView: View {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 serial numbers or other unique device identifiers, performance timings, or individual transcription events.")+ self.bullet("Hardware serial numbers, other unique device identifiers, or individual transcription events.")self.sectionTitle("How it’s used")self.bullet("Daily activity measures active installations and retention without requiring accounts.")self.bullet("Optional detailed analytics helps us understand feature adoption, onboarding completion, and model usage.")+ self.bullet("Beta timing summaries help us compare ASR and Fluid Intelligence speed across Mac hardware and macOS versions.")self.sectionTitle("Control")self.bullet("You can disable detailed analytics anytime in Settings → Share Detailed Anonymous Analytics.")- self.bullet("Disabling detailed analytics securely removes its queued and aggregated data from this Mac. The daily activity signal remains enabled.")+ self.bullet("Disabling detailed analytics securely removes its queued and aggregated data from this Mac. Daily activity and beta timing summaries remain enabled.")}.padding(.vertical, 6)}diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swiftindex 53d6d2c0..49ccd857 100644--- a/Sources/Fluid/UI/SettingsView.swift+++ b/Sources/Fluid/UI/SettingsView.swift@@ -966,7 +966,7 @@ struct SettingsView: View {self.optionToggleRow(title: "Share Detailed Anonymous Analytics",description: "Share anonymous daily feature, onboarding, and model metrics. " +- "When off, FluidVoice records one anonymous activity signal per day and sends them weekly to measure active use. " ++ "When off, FluidVoice still records the anonymous daily activity signal and, in beta builds, daily ASR and Fluid Intelligence timing summaries. " +"Never includes transcription text or prompts.",isOn: self.detailedAnalyticsToggleBinding)@@ -1605,7 +1605,7 @@ struct SettingsView: View {guard panel.runModal() == .OK, let url = panel.url else { return }- let document = await BackupService.shared.makeBackupDocument()+ let document = try await BackupService.shared.makeBackupDocument()let data = try BackupService.shared.encode(document)try data.write(to: url, options: .atomic)diff --git a/Sources/Fluid/UI/TranscriptionHistoryView.swift b/Sources/Fluid/UI/TranscriptionHistoryView.swiftindex b3589aca..17b32cea 100644--- a/Sources/Fluid/UI/TranscriptionHistoryView.swift+++ b/Sources/Fluid/UI/TranscriptionHistoryView.swift@@ -31,6 +31,20 @@ struct TranscriptionHistoryView: View {self.searchBar.padding(12)+ if self.historyStore.isLoading {+ ProgressView("Loading history…")+ .padding(12)+ } else if let error = self.historyStore.persistenceError {+ VStack(alignment: .leading, spacing: 8) {+ Text(error)+ .font(.caption)+ Button("Retry saving history") {+ self.historyStore.retryPersistence()+ }+ }+ .padding(12)+ }+Divider().opacity(0.3)@@ -43,6 +57,7 @@ struct TranscriptionHistoryView: View {// Footer with stats and clear buttonself.footerView+ .disabled(self.historyStore.isLoading)}.frame(minWidth: 280, idealWidth: 320, maxWidth: 400).background(self.theme.palette.contentBackground)diff --git a/Sources/Fluid/UI/WelcomeView.swift b/Sources/Fluid/UI/WelcomeView.swiftindex 381c3c18..fceede03 100644--- a/Sources/Fluid/UI/WelcomeView.swift+++ b/Sources/Fluid/UI/WelcomeView.swift@@ -690,7 +690,7 @@ struct OnboardingFlowView: View {self.suspendOnboardingMicrophonePreviewForDictation()}}- .onChange(of: self.asr.audioCaptureStateSettledTick) { _, _ in+ .onReceive(self.asr.audioCaptureStateDidSettle) {guard self.isOnboardingFlowVisible,self.step == .permissions,self.isMicrophoneReadydiff --git a/Sources/Fluid/Views/BottomOverlayView.swift b/Sources/Fluid/Views/BottomOverlayView.swiftindex ebbaa059..f7463aa4 100644--- a/Sources/Fluid/Views/BottomOverlayView.swift+++ b/Sources/Fluid/Views/BottomOverlayView.swift@@ -56,6 +56,9 @@ final class BottomOverlayWindowController {private var isHideInProgress = falseprivate var activeHideGeneration: UInt64?private var hideWaiters: [CheckedContinuation<RecordingOverlayHideOutcome, Never>] = []+ var isVisuallyHiddenForTests: Bool {+ self.window?.isVisible != true || self.window?.alphaValue == 0+ }private init() {NotificationCenter.default.addObserver(forName: NSNotification.Name("OverlayOffsetChanged"), object: nil, queue: .main) { [weak self] _ in@@ -163,6 +166,7 @@ final class BottomOverlayWindowController {self.presentationGeneration &+= 1let currentGeneration = self.presentationGenerationself.activeHideGeneration = currentGeneration+ self.beginDismissalVisualIfPresented(generation: currentGeneration)Task { [weak self] inguard let self else { return }let outcome = await self.performHideAndWait(generation: currentGeneration)@@ -170,6 +174,51 @@ final class BottomOverlayWindowController {}}+ /// Removes the completed-dictation overlay before returning. The panel is+ /// parked rather than destroyed so the next presentation keeps its warm+ /// SwiftUI and WindowServer surface.+ func hideImmediately() {+ let startedAt = ProcessInfo.processInfo.systemUptime+ self.presentationGeneration &+= 1+ let currentGeneration = self.presentationGeneration++ self.activeHideGeneration = nil+ self.isHideInProgress = false+ let waiters = self.hideWaiters+ self.hideWaiters.removeAll(keepingCapacity: true)++ // Remove the panel from WindowServer before any SwiftUI state update can+ // delay paste. Opacity alone is not committed until the next frame.+ self.window?.alphaValue = 0+ Self.overlayBench("bottom_hide_alpha_return elapsedMs=\(Self.elapsedMs(since: startedAt))")+ self.window?.orderOut(nil)+ Self.overlayBench("bottom_hide_order_out_return elapsedMs=\(Self.elapsedMs(since: startedAt))")+ waiters.forEach { $0.resume(returning: .hidden) }++ Self.overlayBench(+ "bottom_hide_immediate_complete elapsedMs=\(Self.elapsedMs(since: startedAt)) visible=\(self.window?.isVisible == true)"+ )++ // Cleanup is not user-visible and must not hold up text insertion.+ Task { @MainActor [weak self] in+ await Task.yield()+ guard let self, self.presentationGeneration == currentGeneration else { return }+ self.clearPresentationStateAfterImmediateHide()+ self.parkWindowOffscreen()+ self.window?.alphaValue = 1+ self.window?.orderFrontRegardless()+ }+ }++ private func clearPresentationStateAfterImmediateHide() {+ NotchContentState.shared.setBottomOverlayPresented(false)+ self.endReleaseTransition(flushDeferredUpdate: false)+ NotchContentState.shared.setBottomOverlayDismissing(false)+ NotchContentState.shared.targetAppIcon = nil+ self.clearPresentationResources()+ Self.overlayBench("bottom_hide_immediate_cleanup_complete")+ }+/// Returns whether the panel finished hiding or a newer presentation/// superseded this request.func hideAndWait() async -> RecordingOverlayHideOutcome {@@ -183,6 +232,7 @@ final class BottomOverlayWindowController {self.presentationGeneration &+= 1let currentGeneration = self.presentationGenerationself.activeHideGeneration = currentGeneration+ self.beginDismissalVisualIfPresented(generation: currentGeneration)let outcome = await self.performHideAndWait(generation: currentGeneration)self.completeHideOperation(generation: currentGeneration, outcome: outcome)return outcome@@ -224,10 +274,6 @@ final class BottomOverlayWindowController {return .hidden}- NotchContentState.shared.setBottomOverlayReleaseTransitioning(true)- NotchContentState.shared.setBottomOverlayDismissOffsetY(8)- NotchContentState.shared.setBottomOverlayDismissing(true)-// SwiftUI owns the dismissal animation. Keeping AppKit alpha at 1// prevents an old implicit window animation from hiding a rapid restart.Self.overlayBench("bottom_hide_animation_start")@@ -255,6 +301,18 @@ final class BottomOverlayWindowController {return .hidden}+ private func beginDismissalVisualIfPresented(generation: UInt64) {+ guard self.presentationGeneration == generation,+ self.window != nil,+ NotchContentState.shared.isBottomOverlayPresented+ else { return }++ NotchContentState.shared.setBottomOverlayReleaseTransitioning(true)+ NotchContentState.shared.setBottomOverlayDismissOffsetY(8)+ NotchContentState.shared.setBottomOverlayDismissing(true)+ Self.overlayBench("bottom_hide_visual_requested")+ }+private func clearPresentationResources() {self.audioSubscription?.cancel()self.audioSubscription = nildiff --git a/Tests/FluidDictationIntegrationTests/AnalyticsDatabaseTests.swift b/Tests/FluidDictationIntegrationTests/AnalyticsDatabaseTests.swiftindex 0e2237a2..151acb4c 100644--- a/Tests/FluidDictationIntegrationTests/AnalyticsDatabaseTests.swift+++ b/Tests/FluidDictationIntegrationTests/AnalyticsDatabaseTests.swift@@ -15,6 +15,133 @@ final class AnalyticsDatabaseTests: XCTestCase {try? FileManager.default.removeItem(at: self.temporaryDirectory)}+ func testBetaPerformanceCollectionUsesInstalledVersion() {+ XCTAssertTrue(AnalyticsBuildPolicy.automaticallyCollectsDictationPerformance(appVersion: "1.6.10-beta.1"))+ XCTAssertTrue(AnalyticsBuildPolicy.automaticallyCollectsDictationPerformance(appVersion: "2.0-BETA"))+ XCTAssertFalse(AnalyticsBuildPolicy.automaticallyCollectsDictationPerformance(appVersion: "1.6.10"))+ XCTAssertFalse(AnalyticsBuildPolicy.automaticallyCollectsDictationPerformance(appVersion: "unknown"))+ }++ func testDictationSummaryIsOneStableLineAndNamesSlowestStage() {+ let line = DictationPerformanceLogSummary.line(+ asrMilliseconds: 52,+ aiMilliseconds: 150,+ readyMilliseconds: 225,+ outcome: "success"+ )++ XCTAssertEqual(+ line,+ "DICTATION_SUMMARY asrMs=52 aiMs=150 appOverheadMs=23 readyMs=225 " ++ "slowest=ai outcome=success"+ )+ XCTAssertFalse(line.contains("\n"))+ }++ func testBetaPerformanceIsAggregatedIntoOneDailyDistribution() throws {+ let database = try self.makeDatabase()+ let firstDay = Date(timeIntervalSince1970: 1_735_689_600)+ let secondDay = firstDay.addingTimeInterval(24 * 60 * 60)++ try database.recordDictationPerformance(+ asrMilliseconds: 20,+ fluidIntelligenceMilliseconds: 100,+ measuredAppVersion: "1.6.10-beta.1",+ at: firstDay+ )+ try database.recordDictationPerformance(+ asrMilliseconds: 60,+ fluidIntelligenceMilliseconds: 900,+ measuredAppVersion: "1.6.10-beta.1",+ at: firstDay.addingTimeInterval(60)+ )+ try database.recordDictationPerformance(+ asrMilliseconds: 1600,+ fluidIntelligenceMilliseconds: nil,+ measuredAppVersion: "1.6.10-beta.1",+ at: firstDay.addingTimeInterval(120)+ )+ try database.finalizeDays(before: secondDay)++ let events = try self.events(in: database).filter {+ $0.name == AnalyticsEvent.dictationPerformanceDailySummary.rawValue+ }+ let summary = try XCTUnwrap(events.first)+ XCTAssertEqual(events.count, 1)+ XCTAssertEqual(summary.properties["measured_app_version"] as? String, "1.6.10-beta.1")+ XCTAssertEqual(summary.properties["measured_os_version"] as? String, "macOS 15.6.1")+ XCTAssertEqual(summary.properties["asr_sample_count"] as? Int, 3)+ XCTAssertEqual(summary.properties["asr_p50_bucket"] as? String, "75")+ XCTAssertEqual(summary.properties["asr_p95_bucket"] as? String, "2000")+ XCTAssertEqual(summary.properties["fluid_intelligence_sample_count"] as? Int, 2)+ XCTAssertEqual(summary.properties["fluid_intelligence_p50_bucket"] as? String, "100")+ XCTAssertEqual(summary.properties["fluid_intelligence_p95_bucket"] as? String, "1000")+ XCTAssertNil(summary.properties["asr_average_ms"])+ XCTAssertNil(summary.properties["asr_max_ms"])+ XCTAssertNil(summary.properties["fluid_intelligence_average_ms"])+ XCTAssertNil(summary.properties["fluid_intelligence_max_ms"])+ XCTAssertNil(summary.properties["os_version"])+ XCTAssertNil(summary.properties["transcript"])+ XCTAssertNil(summary.properties["window_title"])+ }++ func testDetailedOptOutPreservesAutomaticBetaPerformanceSummary() throws {+ let database = try self.makeDatabase()+ let firstDay = Date(timeIntervalSince1970: 1_735_689_600)+ let secondDay = firstDay.addingTimeInterval(24 * 60 * 60)++ try database.recordDictationPerformance(+ asrMilliseconds: 75,+ fluidIntelligenceMilliseconds: 200,+ measuredAppVersion: "1.6.10-beta.1",+ at: firstDay+ )+ try database.purgeDetailedAnalytics()+ try database.finalizeDays(before: secondDay)++ let names = try self.events(in: database).map(\.name)+ XCTAssertEqual(names, [AnalyticsEvent.dictationPerformanceDailySummary.rawValue])+ }++ func testPerformanceSummaryKeepsOSVersionFromMeasurementTime() throws {+ let databaseURL = self.temporaryDirectory.appendingPathComponent("analytics-os.sqlite3")+ let firstDay = Date(timeIntervalSince1970: 1_735_689_600)+ let secondDay = firstDay.addingTimeInterval(24 * 60 * 60)++ do {+ let database = try self.makeDatabase(+ url: databaseURL,+ systemConfiguration: AnalyticsSystemConfiguration(+ ramGB: 24,+ chip: "Apple M3 Pro",+ osVersion: "macOS 15.6.1"+ )+ )+ try database.recordDictationPerformance(+ asrMilliseconds: 75,+ fluidIntelligenceMilliseconds: 200,+ measuredAppVersion: "1.6.10-beta.1",+ at: firstDay+ )+ }++ let upgraded = try self.makeDatabase(+ url: databaseURL,+ systemConfiguration: AnalyticsSystemConfiguration(+ ramGB: 24,+ chip: "Apple M3 Pro",+ osVersion: "macOS 16.0"+ )+ )+ try upgraded.finalizeDays(before: secondDay)+ let summary = try XCTUnwrap(+ try self.events(in: upgraded).first {+ $0.name == AnalyticsEvent.dictationPerformanceDailySummary.rawValue+ }+ )+ XCTAssertEqual(summary.properties["measured_os_version"] as? String, "macOS 15.6.1")+ }+func testActivityIsDeduplicatedAndUsageIsAggregatedByDay() throws {let database = try self.makeDatabase()let firstDay = Date(timeIntervalSince1970: 1_735_689_600) // 2025-01-01 UTC@@ -344,7 +471,14 @@ final class AnalyticsDatabaseTests: XCTestCase {XCTAssertEqual(events.map(\.name), [AnalyticsEvent.activeUser.rawValue])}- private func makeDatabase(url: URL? = nil) throws -> AnalyticsDatabase {+ private func makeDatabase(+ url: URL? = nil,+ systemConfiguration: AnalyticsSystemConfiguration = AnalyticsSystemConfiguration(+ ramGB: 24,+ chip: "Apple M3 Pro",+ osVersion: "macOS 15.6.1"+ )+ ) throws -> AnalyticsDatabase {var calendar = Calendar(identifier: .gregorian)calendar.timeZone = try XCTUnwrap(TimeZone(secondsFromGMT: 0))calendar.firstWeekday = 2@@ -352,7 +486,7 @@ final class AnalyticsDatabaseTests: XCTestCase {url: url ?? self.temporaryDirectory.appendingPathComponent("analytics.sqlite3"),distinctID: "test-install-id",appVersion: "test",- systemConfiguration: AnalyticsSystemConfiguration(ramGB: 24, chip: "Apple M3 Pro"),+ systemConfiguration: systemConfiguration,calendar: calendar)}diff --git a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swiftindex 72a76d27..0e9628ad 100644--- a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift+++ b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift@@ -2823,7 +2823,7 @@ extension DictationE2ETests {]settings.spokenFormattingActionRules = backedUpRules- let document = await BackupService.shared.makeBackupDocument()+ let document = try await BackupService.shared.makeBackupDocument()let encoded = try BackupService.shared.encode(document)let decoded = try BackupService.shared.decode(encoded)XCTAssertEqual(decoded.settings.spokenFormattingActionRules, settings.spokenFormattingActionRules)@@ -2854,6 +2854,36 @@ extension DictationE2ETests {@MainActorfinal class OverlayFailureStateTests: XCTestCase {+ func testAIFailurePresentationOnlyRunsForPersistedFallbackOutput() {+ XCTAssertTrue(+ DictationAIFailurePresentationPolicy.shouldPresent(+ shouldPersistOutputs: true,+ fallbackReason: "offline"+ )+ )+ XCTAssertFalse(+ DictationAIFailurePresentationPolicy.shouldPresent(+ shouldPersistOutputs: false,+ fallbackReason: "offline"+ ),+ "Onboarding sandbox failures must not create retry UI or system notifications"+ )+ XCTAssertFalse(+ DictationAIFailurePresentationPolicy.shouldPresent(+ shouldPersistOutputs: true,+ fallbackReason: nil+ )+ )+ }++ func testConfigurationFailureNotificationPointsToProviderSetup() {+ let message = DictationAIFailurePresentationPolicy.notificationMessage(+ for: AIProcessingError.missingAPIKey(provider: "OpenAI")+ )++ XCTAssertEqual(message, "API key not set for OpenAI. Open AI Providers to configure a provider.")+ }+func testCustomNonRetryableMessage() {let state = NotchContentState.shareddefer {@@ -2877,6 +2907,40 @@ final class OverlayFailureStateTests: XCTestCase {}}+final class AudioBudgetMeasurementGateTests: XCTestCase {+ func testMeasurementRequiresMatchingRevisionAndBudget() {+ let gate = AudioBudgetMeasurementGate(revision: 7, budgetBytes: 1_000)++ XCTAssertTrue(gate.accepts(currentRevision: 7, currentBudgetBytes: 1_000))+ XCTAssertFalse(gate.accepts(currentRevision: 8, currentBudgetBytes: 1_000))+ XCTAssertFalse(gate.accepts(currentRevision: 7, currentBudgetBytes: 2_000))+ }++ func testPendingOrReferencedAudioIsNeverDeletedAsOrphan() {+ XCTAssertFalse(+ DictationAudioHistoryStore.shouldDeleteUnreferencedAudioFile(+ fileName: "pending.wav",+ referencedFileNames: [],+ pendingFileNames: ["pending.wav"]+ )+ )+ XCTAssertFalse(+ DictationAudioHistoryStore.shouldDeleteUnreferencedAudioFile(+ fileName: "saved.wav",+ referencedFileNames: ["saved.wav"],+ pendingFileNames: []+ )+ )+ XCTAssertTrue(+ DictationAudioHistoryStore.shouldDeleteUnreferencedAudioFile(+ fileName: "orphan.wav",+ referencedFileNames: [],+ pendingFileNames: []+ )+ )+ }+}+@MainActorfinal class SimpleUpdaterTests: XCTestCase {func testUpdateOperationGateAllowsOnlyOneActiveInstall() {diff --git a/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift b/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swiftindex f8497f4c..9e72c8fb 100644--- a/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift+++ b/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift@@ -1,9 +1,763 @@+import Combineimport CoreAudio@testable import FluidVoice_Debugimport Foundationimport XCTestfinal class DirectAudioReliabilityTests: XCTestCase {+ func testPipelineCorrelationIsInheritedAndRestoredAcrossConcurrentRequests() async {+ let original = DebugLogger.pipelineID+ let values = await withTaskGroup(of: String?.self, returning: [String?].self) { group in+ for id in ["pipeline-a", "pipeline-b"] {+ group.addTask {+ await DebugLogger.$pipelineID.withValue(id) {+ await Task.yield()+ return await Task { DebugLogger.pipelineID }.value+ }+ }+ }+ var values: [String?] = []+ for await value in group {+ values.append(value)+ }+ return values+ }+ XCTAssertEqual(Set(values.compactMap { $0 }), ["pipeline-a", "pipeline-b"])+ XCTAssertEqual(DebugLogger.pipelineID, original)+ }++ func testPipelineCorrelationCanCrossDispatchWithoutLeakingToNextWork() async {+ let values: [String?] = await DebugLogger.$pipelineID.withValue("pipeline-a") {+ let captured = DebugLogger.pipelineID+ return await withCheckedContinuation { continuation in+ DispatchQueue.global().async {+ let before = DebugLogger.pipelineID+ let inside = DebugLogger.$pipelineID.withValue(captured) { DebugLogger.pipelineID }+ let after = DebugLogger.pipelineID+ continuation.resume(returning: [before, inside, after])+ }+ }+ }+ XCTAssertEqual(values, [nil, "pipeline-a", nil])+ }++ @MainActor+ func testAIStreamPreviewCoalescesBurstIntoOneMainActorUpdate() async {+ var publishedText: [String] = []+ let preview = DictationAIStreamPreviewBuffer(minimumUpdateInterval: 0, initialUpdateDelay: 0) { text in+ publishedText.append(text)+ }++ preview.append("Fluid")+ preview.append("Voice")+ preview.append(" benchmark")+ preview.flush()+ await Task.yield()++ XCTAssertEqual(publishedText, ["FluidVoice benchmark"])+ }++ @MainActor+ func testAIStreamPreviewFlushesShortGenerationWithoutQueuedUIWork() async {+ var publishedText: [String] = []+ let preview = DictationAIStreamPreviewBuffer(minimumUpdateInterval: 60, initialUpdateDelay: 60) { text in+ publishedText.append(text)+ }++ preview.append("Exact output")+ XCTAssertTrue(publishedText.isEmpty)++ preview.flush()+ preview.flush()+ await Task.yield()++ XCTAssertEqual(publishedText, ["Exact output"])+ }++ @MainActor+ func testAIStreamPreviewReturnsToNormalCadenceAfterStartupGrace() async {+ var publishedText: [String] = []+ let preview = DictationAIStreamPreviewBuffer(minimumUpdateInterval: 60, initialUpdateDelay: 0) { text in+ publishedText.append(text)+ }++ preview.append("First")+ await Task.yield()+ preview.append(" second")+ await Task.yield()++ XCTAssertEqual(publishedText, ["First"])+ preview.flush()+ XCTAssertEqual(publishedText, ["First", "First second"])+ }++ @MainActor+ func testCaptureSettledEventDoesNotInvalidateWholeASRService() {+ let service = ASRService()+ var settledEventCount = 0+ var objectChangeCount = 0+ let settledCancellable = service.audioCaptureStateDidSettle.sink {+ settledEventCount += 1+ }+ let objectCancellable = service.objectWillChange.sink {+ objectChangeCount += 1+ }++ service.audioCaptureStateDidSettle.send()++ XCTAssertEqual(settledEventCount, 1)+ XCTAssertEqual(objectChangeCount, 0)+ withExtendedLifetime((settledCancellable, objectCancellable)) {}+ }++ func testStopUIInvalidationGateFinishesExactlyOnce() {+ var gate = ASRStopUIInvalidationGate()++ XCTAssertFalse(gate.isDeferring)+ XCTAssertFalse(gate.finish())+ gate.begin()+ XCTAssertTrue(gate.isDeferring)+ XCTAssertTrue(gate.finish())+ XCTAssertFalse(gate.isDeferring)+ XCTAssertFalse(gate.finish())+ }++ func testStopUIInvalidationGateWaitsForOutputPipelineHold() {+ var gate = ASRStopUIInvalidationGate()++ gate.holdForOutputPipeline()+ gate.begin()++ XCTAssertFalse(gate.finish())+ XCTAssertTrue(gate.isDeferring)+ XCTAssertTrue(gate.releaseOutputPipelineHold())+ XCTAssertFalse(gate.isDeferring)+ XCTAssertFalse(gate.releaseOutputPipelineHold())+ }++ func testStopUIInvalidationGateForceFinishBoundsHeldPipeline() {+ var gate = ASRStopUIInvalidationGate()++ gate.holdForOutputPipeline()+ gate.begin()+ XCTAssertFalse(gate.finish())++ XCTAssertTrue(gate.forceFinish())+ XCTAssertFalse(gate.isDeferring)+ XCTAssertFalse(gate.forceFinish())+ }++ @MainActor+ func testFinalTranscriptionStatusRunsAfterDelay() async {+ var operationCount = 0+ let task = scheduleDeferredMainActorOperation(afterNanoseconds: 0) {+ operationCount += 1+ }++ await task.value++ XCTAssertEqual(operationCount, 1)+ }++ @MainActor+ func testCancelledFinalTranscriptionStatusHasNoSideEffect() async {+ var operationCount = 0+ let task = scheduleDeferredMainActorOperation(afterNanoseconds: 60_000_000_000) {+ operationCount += 1+ }++ task.cancel()+ await task.value++ XCTAssertEqual(operationCount, 0)+ }++ @MainActor+ func testDelayedFinalStatusCannotChangeANewerRecording() async {+ var currentSession = 7+ let stoppingSession = currentSession+ var overlay = "Recording"+ let staleTask = scheduleDeferredMainActorOperation(+ afterNanoseconds: 0,+ shouldRun: { currentSession == stoppingSession }+ ) { overlay = "Transcribing" }+ currentSession = 8+ await staleTask.value+ XCTAssertEqual(overlay, "Recording")++ let currentTask = scheduleDeferredMainActorOperation(+ afterNanoseconds: 0,+ shouldRun: { currentSession == 8 }+ ) { overlay = "Transcribing" }+ await currentTask.value+ XCTAssertEqual(overlay, "Transcribing")+ }++ @MainActor+ func testStalledStreamingDrainIsBoundedWithoutCancellingProvider() async {+ let lifecycle = StreamingTaskLifecycle()+ var providerContinuation: CheckedContinuation<Void, Never>?+ var providerWasCancelled = false+ var completions = 0+ lifecycle.schedule(sessionID: 7, delayNanoseconds: 0) { _ in+ await withCheckedContinuation { providerContinuation = $0 }+ providerWasCancelled = Task.isCancelled+ } completion: { _ in completions += 1 }+ while providerContinuation == nil {+ await Task.yield()+ }++ let completed = await lifecycle.drain(sessionID: 7, timeoutNanoseconds: 1_000_000)+ XCTAssertFalse(completed)+ XCTAssertTrue(lifecycle.hasActiveWork, "Timeout must retain the provider and its incremental state")+ XCTAssertEqual(lifecycle.pendingDrainCount, 0, "Timed-out waiters must be removed")+ XCTAssertEqual(completions, 0)+ XCTAssertFalse(lifecycle.schedule(sessionID: 8, delayNanoseconds: 0) { _ in+ XCTFail("A replacement must not race the stalled provider")+ } completion: { _ in })++ let resumedDrain = Task { @MainActor in+ await lifecycle.drain(sessionID: 7, timeoutNanoseconds: 60_000_000_000)+ }+ await Task.yield()+ providerContinuation?.resume()+ let recovered = await resumedDrain.value+ XCTAssertTrue(recovered)+ XCTAssertFalse(providerWasCancelled)+ XCTAssertEqual(completions, 1)+ XCTAssertFalse(lifecycle.hasActiveWork)+ XCTAssertEqual(lifecycle.pendingDrainCount, 0, "Completion must retire its timer/waiter")+ }++ @MainActor+ func testTimedOutHandoffWakesStartsButKeepsBufferOwnedUntilRecovery() async throws {+ let gate = RecordingBufferHandoffGate()+ let token = try XCTUnwrap(gate.begin())+ var wokeInRecovery = false+ let waitingStart = Task { @MainActor in+ await gate.waitUntilAvailable()+ wokeInRecovery = gate.isRecovering+ }+ while gate.pendingWaiterCount == 0 {+ await Task.yield()+ }+ gate.markTimedOut(token)+ await waitingStart.value+ XCTAssertTrue(wokeInRecovery)+ XCTAssertTrue(gate.isActive)+ XCTAssertNil(gate.begin(), "Timeout must not release the PCM to another capture")+ XCTAssertEqual(gate.pendingWaiterCount, 0)++ let otherGate = RecordingBufferHandoffGate()+ let staleToken = try XCTUnwrap(otherGate.begin())+ gate.complete(staleToken)+ XCTAssertTrue(gate.isRecovering)+ gate.complete(token)+ XCTAssertFalse(gate.isRecovering)+ XCTAssertFalse(gate.isActive)+ let nextToken = try XCTUnwrap(gate.begin())+ gate.markTimedOut(token)+ XCTAssertFalse(gate.isRecovering, "An old timeout cannot affect a fresh recording")+ gate.complete(nextToken)+ }++ @MainActor+ func testStreamingIdleSchedulerCancelsWithoutLaunchingOrActiveDrain() async {+ let lifecycle = StreamingTaskLifecycle()+ var operationStarted = false++ XCTAssertTrue(lifecycle.schedule(+ sessionID: 7,+ delayNanoseconds: 60_000_000_000+ ) { _ in+ operationStarted = true+ } completion: { _ in })+ XCTAssertTrue(lifecycle.hasScheduledIdleWork)++ XCTAssertTrue(lifecycle.cancelScheduler())+ var mainActorSentinelRan = false+ let sentinelTask = Task { @MainActor in+ mainActorSentinelRan = true+ }+ let activeTask = lifecycle.activeTaskToDrain(sessionID: 7)++ XCTAssertNil(activeTask)+ XCTAssertFalse(mainActorSentinelRan, "An idle drain must not yield the main actor")+ await sentinelTask.value+ XCTAssertFalse(operationStarted)+ XCTAssertFalse(lifecycle.hasScheduledIdleWork)+ XCTAssertFalse(lifecycle.hasActiveWork)+ }++ @MainActor+ func testStreamingActiveWorkDrainsWithoutCancellation() async {+ let lifecycle = StreamingTaskLifecycle()+ var operationStarted = false+ var operationWasCancelled = false+ var operationContinuation: CheckedContinuation<Void, Never>?+ var completionCount = 0++ XCTAssertTrue(lifecycle.schedule(+ sessionID: 11,+ delayNanoseconds: 0+ ) { _ in+ operationStarted = true+ await withCheckedContinuation { continuation in+ operationContinuation = continuation+ }+ operationWasCancelled = Task.isCancelled+ } completion: { _ in+ completionCount += 1+ })++ while operationStarted == false {+ await Task.yield()+ }+ XCTAssertTrue(lifecycle.hasActiveWork)+ XCTAssertFalse(lifecycle.cancelScheduler())++ let drainTask = Task { @MainActor in+ await lifecycle.drain(sessionID: 11, timeoutNanoseconds: 60_000_000_000)+ }+ await Task.yield()+ XCTAssertEqual(completionCount, 0)++ operationContinuation?.resume()+ let drainedActiveWork = await drainTask.value+ XCTAssertTrue(drainedActiveWork)++ XCTAssertFalse(operationWasCancelled)+ XCTAssertEqual(completionCount, 1)+ XCTAssertFalse(lifecycle.hasActiveWork)+ }++ func testStreamingWorkStateRejectsStaleProviderAndOperationMutations() throws {+ var state = StreamingTranscriptionWorkState()+ state.beginSession(31)+ let firstOperation = UUID()+ let firstProviderGenerationValue = state.beginOperation(+ sessionID: 31,+ operationID: firstOperation+ )+ let firstProviderGeneration = try XCTUnwrap(firstProviderGenerationValue)+ XCTAssertTrue(state.canPublish(+ sessionID: 31,+ operationID: firstOperation,+ providerGeneration: firstProviderGeneration+ ))++ state.invalidateProvider()+ XCTAssertFalse(state.canPublish(+ sessionID: 31,+ operationID: firstOperation,+ providerGeneration: firstProviderGeneration+ ))+ XCTAssertTrue(state.finishOperation(sessionID: 31, operationID: firstOperation))++ let secondOperation = UUID()+ let secondProviderGeneration = state.beginOperation(+ sessionID: 31,+ operationID: secondOperation+ )+ _ = try XCTUnwrap(secondProviderGeneration)+ XCTAssertFalse(state.finishOperation(sessionID: 31, operationID: firstOperation))+ XCTAssertTrue(state.ownsOperation(sessionID: 31, operationID: secondOperation))++ XCTAssertTrue(state.finishOperation(sessionID: 31, operationID: secondOperation))+ state.endSession(31)+ state.beginSession(32)+ XCTAssertFalse(state.ownsOperation(sessionID: 31, operationID: secondOperation))+ }++ func testStreamingWorkStatePublishesOnlyForRunningCurrentSession() throws {+ var state = StreamingTranscriptionWorkState()+ state.beginSession(41)+ let operationID = UUID()+ let providerGeneration = try XCTUnwrap(state.beginOperation(+ sessionID: 41,+ operationID: operationID+ ))++ XCTAssertTrue(state.canPublishPreview(+ sessionID: 41,+ operationID: operationID,+ providerGeneration: providerGeneration,+ isRunning: true,+ schedulingSessionID: 41+ ))+ XCTAssertFalse(state.canPublishPreview(+ sessionID: 41,+ operationID: operationID,+ providerGeneration: providerGeneration,+ isRunning: false,+ schedulingSessionID: 41+ ))+ XCTAssertFalse(state.canPublishPreview(+ sessionID: 41,+ operationID: operationID,+ providerGeneration: providerGeneration,+ isRunning: true,+ schedulingSessionID: nil+ ))+ XCTAssertFalse(state.canPublishPreview(+ sessionID: 41,+ operationID: operationID,+ providerGeneration: providerGeneration,+ isRunning: true,+ schedulingSessionID: 42+ ))++ state.invalidateProvider()+ XCTAssertFalse(state.canPublishPreview(+ sessionID: 41,+ operationID: operationID,+ providerGeneration: providerGeneration,+ isRunning: true,+ schedulingSessionID: 41+ ))+ }++ @MainActor+ func testStoppedLateStreamingSuccessSkipsPreviewWorkAndStillDrains() async throws {+ let lifecycle = StreamingTaskLifecycle()+ var state = StreamingTranscriptionWorkState()+ state.beginSession(51)+ var isRunning = true+ var schedulingSessionID: Int? = 51+ var operationContinuation: CheckedContinuation<Void, Never>?+ var formatCount = 0+ var publishCount = 0+ var cleanupCount = 0+ var rearmCount = 0++ XCTAssertTrue(lifecycle.schedule(+ sessionID: 51,+ delayNanoseconds: 0+ ) { operationID in+ guard let providerGeneration = state.beginOperation(+ sessionID: 51,+ operationID: operationID+ ) else {+ XCTFail("Expected the late success operation to own the session")+ return+ }+ await withCheckedContinuation { continuation in+ operationContinuation = continuation+ }+ guard state.canPublishPreview(+ sessionID: 51,+ operationID: operationID,+ providerGeneration: providerGeneration,+ isRunning: isRunning,+ schedulingSessionID: schedulingSessionID+ ) else { return }+ formatCount += 1+ publishCount += 1+ } completion: { operationID in+ if state.finishOperation(sessionID: 51, operationID: operationID) {+ cleanupCount += 1+ }+ if isRunning, schedulingSessionID == 51 {+ rearmCount += 1+ }+ })++ while operationContinuation == nil {+ await Task.yield()+ }+ isRunning = false+ schedulingSessionID = nil+ let activeTask = try XCTUnwrap(lifecycle.activeTaskToDrain(sessionID: 51))+ operationContinuation?.resume()+ _ = await activeTask.result++ XCTAssertEqual(formatCount, 0)+ XCTAssertEqual(publishCount, 0)+ XCTAssertEqual(cleanupCount, 1)+ XCTAssertEqual(rearmCount, 0)+ XCTAssertFalse(lifecycle.hasActiveWork)+ }++ @MainActor+ func testStoppedLateStreamingFailureSkipsFailureMutationAndStillDrains() async throws {+ let lifecycle = StreamingTaskLifecycle()+ var state = StreamingTranscriptionWorkState()+ state.beginSession(52)+ var isRunning = true+ var schedulingSessionID: Int? = 52+ var operationContinuation: CheckedContinuation<Void, Never>?+ var fallbackCount = 0+ var failureMutationCount = 0+ var cleanupCount = 0+ var rearmCount = 0++ XCTAssertTrue(lifecycle.schedule(+ sessionID: 52,+ delayNanoseconds: 0+ ) { operationID in+ guard let providerGeneration = state.beginOperation(+ sessionID: 52,+ operationID: operationID+ ) else {+ XCTFail("Expected the late failure operation to own the session")+ return+ }+ await withCheckedContinuation { continuation in+ operationContinuation = continuation+ }+ guard state.canPublishPreview(+ sessionID: 52,+ operationID: operationID,+ providerGeneration: providerGeneration,+ isRunning: isRunning,+ schedulingSessionID: schedulingSessionID+ ) else { return }+ fallbackCount += 1+ failureMutationCount += 1+ } completion: { operationID in+ if state.finishOperation(sessionID: 52, operationID: operationID) {+ cleanupCount += 1+ }+ if isRunning, schedulingSessionID == 52 {+ rearmCount += 1+ }+ })++ while operationContinuation == nil {+ await Task.yield()+ }+ isRunning = false+ schedulingSessionID = nil+ let activeTask = try XCTUnwrap(lifecycle.activeTaskToDrain(sessionID: 52))+ operationContinuation?.resume()+ _ = await activeTask.result++ XCTAssertEqual(fallbackCount, 0)+ XCTAssertEqual(failureMutationCount, 0)+ XCTAssertEqual(cleanupCount, 1)+ XCTAssertEqual(rearmCount, 0)+ XCTAssertFalse(lifecycle.hasActiveWork)+ }++ @MainActor+ func testCancelledPendingStartWakesWithoutCompletingBufferHandoff() async throws {+ let gate = RecordingBufferHandoffGate()+ let token = try XCTUnwrap(gate.begin())+ var waiterReturned = false+ let waiter = Task { @MainActor in+ await gate.waitUntilAvailable()+ waiterReturned = true+ }+ while gate.pendingWaiterCount == 0 {+ await Task.yield()+ }+ XCTAssertFalse(waiterReturned)++ gate.releasePendingWaiters()+ await waiter.value++ XCTAssertTrue(waiterReturned)+ XCTAssertTrue(gate.isActive)+ gate.complete(token)+ XCTAssertFalse(gate.isActive)+ }++ @MainActor+ func testBufferHandoffRejectsStaleCompletionAndReleasesOnOwnerCompletion() async throws {+ let gate = RecordingBufferHandoffGate()+ let ownerToken = try XCTUnwrap(gate.begin())+ let otherGate = RecordingBufferHandoffGate()+ let staleToken = try XCTUnwrap(otherGate.begin())+ var waiterReturned = false+ let waiter = Task { @MainActor in+ await gate.waitUntilAvailable()+ waiterReturned = true+ }+ while gate.pendingWaiterCount == 0 {+ await Task.yield()+ }++ gate.complete(staleToken)+ XCTAssertTrue(gate.isActive)+ XCTAssertFalse(waiterReturned)++ gate.complete(ownerToken)+ await waiter.value+ XCTAssertTrue(waiterReturned)+ XCTAssertFalse(gate.isActive)+ }++ @MainActor+ func testStreamingLifecycleContinuesCadenceAfterOperationCompletion() async {+ let lifecycle = StreamingTaskLifecycle()+ var operationCount = 0+ var completionCount = 0++ XCTAssertTrue(lifecycle.schedule(+ sessionID: 19,+ delayNanoseconds: 0+ ) { _ in+ operationCount += 1+ } completion: { _ in+ completionCount += 1+ _ = lifecycle.schedule(+ sessionID: 19,+ delayNanoseconds: 0+ ) { _ in+ operationCount += 1+ } completion: { _ in+ completionCount += 1+ }+ })++ while completionCount < 2 {+ await Task.yield()+ }+ XCTAssertEqual(operationCount, 2)+ XCTAssertEqual(completionCount, 2)+ XCTAssertFalse(lifecycle.hasScheduledIdleWork)+ XCTAssertFalse(lifecycle.hasActiveWork)+ }++ func testCaptureStoppedCallbackDoesNotReenqueueOnMainActor() throws {+ let repositoryRoot = URL(fileURLWithPath: #filePath)+ .deletingLastPathComponent()+ .deletingLastPathComponent()+ .deletingLastPathComponent()+ let source = try String(+ contentsOf: repositoryRoot+ .appendingPathComponent("Sources/Fluid/Services/ASRService.swift"),+ encoding: .utf8+ )+ let callbackSection = try XCTUnwrap(+ source.components(separatedBy: "capture_stopped_callback_request").last?+ .components(separatedBy: "capture_stopped_callback_return").first+ )++ XCTAssertTrue(callbackSection.contains("onCaptureStopped?()"))+ XCTAssertFalse(callbackSection.contains("await "))+ XCTAssertFalse(callbackSection.contains("Task {"))+ }++ func testNormalOutputDismissesOverlayInPasteDispatchTurn() throws {+ let repositoryRoot = URL(fileURLWithPath: #filePath)+ .deletingLastPathComponent()+ .deletingLastPathComponent()+ .deletingLastPathComponent()+ let source = try String(+ contentsOf: repositoryRoot+ .appendingPathComponent("Sources/Fluid/ContentView.swift"),+ encoding: .utf8+ )+ let normalOutputSection = try XCTUnwrap(+ source.components(separatedBy: "if spokenSendAllowed {").last?+ .components(separatedBy: "if spokenSendRequested, !spokenSendAllowed").first+ )+ let pasteIndex = try XCTUnwrap(normalOutputSection.range(of: "typeOutputPlanToActiveField("))+ let deliveryCompletionIndex = try XCTUnwrap(normalOutputSection.range(of: "completion: { outcome in"))+ let deliveryHandlerIndex = try XCTUnwrap(normalOutputSection.range(of: "self.handleTypingDelivery("))++ XCTAssertLessThan(pasteIndex.lowerBound, deliveryCompletionIndex.lowerBound)+ XCTAssertLessThan(deliveryCompletionIndex.lowerBound, deliveryHandlerIndex.lowerBound)+ let hideIndex = try XCTUnwrap(normalOutputSection.range(of: "self.hideOverlayForDispatchedPaste("))+ XCTAssertLessThan(deliveryHandlerIndex.lowerBound, hideIndex.lowerBound)+ let dispatchHideSection = try XCTUnwrap(source.components(separatedBy: "private func hideOverlayForDispatchedPaste(").last?.components(separatedBy: "private func handleTypingDelivery(").first)+ XCTAssertTrue(dispatchHideSection.contains("reason=paste_dispatched"))+ XCTAssertTrue(dispatchHideSection.contains("self.overlayLifecycleID == lifecycleID"))+ XCTAssertFalse(dispatchHideSection.contains("Task {"))+ XCTAssertFalse(normalOutputSection.contains("Task { @MainActor in"))+ XCTAssertFalse(+ normalOutputSection[pasteIndex.lowerBound..<deliveryHandlerIndex.lowerBound]+ .contains("updateTranscriptionText(\"\")")+ )++ let deliveryHandlerSection = try XCTUnwrap(+ source.components(separatedBy: "private func handleTypingDelivery(").last?+ .components(separatedBy: "private func hideOverlayAfterOutput()").first+ )+ XCTAssertTrue(deliveryHandlerSection.contains("self.overlayLifecycleID == expectedOverlayLifecycleID"))+ XCTAssertTrue(normalOutputSection.contains("shouldHideOverlay: shouldHideOverlayAfterDelivery && spokenSendRequested"))+ XCTAssertTrue(normalOutputSection.contains("shouldHide: shouldHideOverlayAfterDelivery && !spokenSendRequested"))+ XCTAssertTrue(deliveryHandlerSection.contains("guard shouldHideOverlay else { return }"))+ XCTAssertFalse(deliveryHandlerSection.contains("await self.menuBarManager.beginProcessingCompletionAndHideOverlay"))++ let menuBarSource = try String(+ contentsOf: repositoryRoot+ .appendingPathComponent("Sources/Fluid/Services/MenuBarManager.swift"),+ encoding: .utf8+ )+ let completionSection = try XCTUnwrap(+ menuBarSource.components(separatedBy: "func beginProcessingCompletionAndHideOverlay() {").last?+ .components(separatedBy: "func finishProcessingAndHideOverlay() async {").first+ )+ XCTAssertTrue(completionSection.contains("NotchOverlayManager.shared.hideImmediately()"))+ XCTAssertFalse(completionSection.contains("NotchOverlayManager.shared.hide()"))++ let postStopSection = try XCTUnwrap(+ source.components(separatedBy: "let transcribedText = await asr.stop").last?+ .components(separatedBy: "guard transcribedText.trimmingCharacters").first+ )+ XCTAssertFalse(postStopSection.contains("updateTranscriptionText(\"\")"))+ }++ func testSlowAIStatusAndPreviewAreScopedToCurrentOverlayLifecycle() throws {+ let repositoryRoot = URL(fileURLWithPath: #filePath)+ .deletingLastPathComponent()+ .deletingLastPathComponent()+ .deletingLastPathComponent()+ let source = try String(+ contentsOf: repositoryRoot+ .appendingPathComponent("Sources/Fluid/ContentView.swift"),+ encoding: .utf8+ )+ let slowStatusSection = try XCTUnwrap(+ source.components(separatedBy: "private func makeAIProcessingFeedback(").last?+ .components(separatedBy: "private func prepareOverlayForASRStop(").first+ )++ XCTAssertTrue(slowStatusSection.contains("self.overlayLifecycleID == lifecycleID"))+ XCTAssertTrue(slowStatusSection.contains("self.menuBarManager.setProcessing(true)"))+ XCTAssertTrue(slowStatusSection.contains("let streamPreview = DictationAIStreamPreviewBuffer"))++ let stopSection = try XCTUnwrap(+ source.components(separatedBy: "private func stopAndProcessTranscription(").last?+ .components(separatedBy: "private func makeAIProcessingFeedback(").first+ )+ let lifecycleSnapshotIndex = try XCTUnwrap(+ stopSection.range(of: "let expectedOverlayLifecycleID = self.overlayLifecycleID")+ )+ let ASRStopIndex = try XCTUnwrap(stopSection.range(of: "let transcribedText = await asr.stop"))+ XCTAssertLessThan(lifecycleSnapshotIndex.lowerBound, ASRStopIndex.lowerBound)+ XCTAssertEqual(+ stopSection.components(separatedBy: "let expectedOverlayLifecycleID = self.overlayLifecycleID").count,+ 2+ )+ }++ func testDictionaryTrackingStartsAfterDeliveryCallbackReturns() throws {+ let repositoryRoot = URL(fileURLWithPath: #filePath)+ .deletingLastPathComponent()+ .deletingLastPathComponent()+ .deletingLastPathComponent()+ let source = try String(+ contentsOf: repositoryRoot+ .appendingPathComponent("Sources/Fluid/Services/TypingService.swift"),+ encoding: .utf8+ )+ let completionSection = try XCTUnwrap(+ source.components(separatedBy: "let completedOutcome = outcome").last?+ .components(separatedBy: "self.log(\"[TypingService] Starting async text insertion process\")").first+ )+ let callbackIndex = try XCTUnwrap(completionSection.range(of: "completion?(completedOutcome)"))+ let trackingIndex = try XCTUnwrap(+ completionSection.range(of: "AutomaticDictionaryCorrectionTracker.shared.beginObservingInsertion")+ )++ XCTAssertLessThan(callbackIndex.lowerBound, trackingIndex.lowerBound)+ XCTAssertTrue(completionSection.contains("completedOutcome.didInsert"))+ XCTAssertTrue(completionSection.contains("dictionary_tracking_scheduled afterDeliveryCallback=true"))+ }+func testReadinessGatePreservesFirstPCMThatArrivesBeforeWait() async {let gate = AudioCaptureReadinessGate()gate.arm(sessionID: 41, attemptID: 1)@@ -61,7 +815,10 @@ final class DirectAudioReliabilityTests: XCTestCase {timeoutNanoseconds: 10_000_000_000)}- await Task.yield()+ for _ in 0..<100 where !gate.hasRegisteredWaiter(sessionID: 41, attemptID: 1) {+ await Task.yield()+ }+ XCTAssertTrue(gate.hasRegisteredWaiter(sessionID: 41, attemptID: 1))gate.arm(sessionID: 41, attemptID: 2)@@ -289,6 +1046,83 @@ final class DirectAudioReliabilityTests: XCTestCase {)}+ func testCancelledStopStillStopsHardwareAndRetainsPreparedInput() async throws {+ let fingerprint = makeFingerprint(sampleRate: 48_000, bufferFrameSize: 512)+ let recorder = DirectAudioEventRecorder(operationDelayMicroseconds: 2000)+ let factory = FakeDirectAudioInputFactory(+ fingerprints: [fingerprint],+ recorder: recorder+ )+ let controller = DirectCoreAudioLifecycleController(+ packetHandler: { _, _, _, _, _ in },+ inputFactory: { deviceID, _ in+ try factory.make(deviceID: deviceID)+ },+ fingerprintReader: { _ in fingerprint },+ installsHardwareListeners: false,+ onFormatInvalidated: { _ in }+ )+ _ = try await controller.start(+ deviceID: fingerprint.deviceID,+ deviceName: "Test microphone",+ reason: "test_start"+ )++ let stopTask = Task {+ await controller.stop(+ retainPrepared: true,+ reason: "cancelled_waiter"+ )+ }+ stopTask.cancel()+ let report = await stopTask.value++ XCTAssertEqual(report.status, noErr)+ XCTAssertTrue(report.retainedPreparedCapture)+ XCTAssertEqual(controller.snapshot.phase, .prepared)+ XCTAssertEqual(recorder.events, ["make:48000", "start:48000", "stop:48000"])+ await controller.shutdown(reason: "test_complete")+ }++ func testSequentialStopStartReusesInputOnlyAfterStopCompletes() async throws {+ let fingerprint = makeFingerprint(sampleRate: 48_000, bufferFrameSize: 512)+ let recorder = DirectAudioEventRecorder(operationDelayMicroseconds: 2000)+ let factory = FakeDirectAudioInputFactory(+ fingerprints: [fingerprint],+ recorder: recorder+ )+ let controller = DirectCoreAudioLifecycleController(+ packetHandler: { _, _, _, _, _ in },+ inputFactory: { deviceID, _ in+ try factory.make(deviceID: deviceID)+ },+ fingerprintReader: { _ in fingerprint },+ installsHardwareListeners: false,+ onFormatInvalidated: { _ in }+ )+ _ = try await controller.start(+ deviceID: fingerprint.deviceID,+ deviceName: "Test microphone",+ reason: "first_start"+ )++ _ = await controller.stop(retainPrepared: true, reason: "first_stop")+ _ = try await controller.start(+ deviceID: fingerprint.deviceID,+ deviceName: "Test microphone",+ reason: "second_start"+ )+ _ = await controller.stop(retainPrepared: true, reason: "second_stop")++ XCTAssertEqual(controller.snapshot.phase, .prepared)+ XCTAssertEqual(+ recorder.events,+ ["make:48000", "start:48000", "stop:48000", "start:48000", "stop:48000"]+ )+ XCTAssertEqual(recorder.maximumConcurrentOperations, 1)+ await controller.shutdown(reason: "test_complete")+ }+func testFailedStopPoisonsLifecycleAndPreventsReplacement() async throws {let fingerprint = makeFingerprint(sampleRate: 48_000, bufferFrameSize: 512)let recorder = DirectAudioEventRecorder()diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swiftindex baea446d..49cc61d7 100644--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift@@ -129,7 +129,12 @@ final class HotkeyShortcutTests: XCTestCase {await Task.yield()controller.show(audioPublisher: audioPublisher, mode: .dictation)controller.hide()+ XCTAssertTrue(+ NotchContentState.shared.isBottomOverlayDismissing,+ "A nonblocking hide must start the visual transition before returning"+ )controller.show(audioPublisher: audioPublisher, mode: .dictation)+ XCTAssertFalse(NotchContentState.shared.isBottomOverlayDismissing)let outcome = await controller.hideAndWait()XCTAssertEqual(outcome, .hidden)@@ -156,6 +161,25 @@ final class HotkeyShortcutTests: XCTestCase {_ = await controller.hideAndWait()}+ @MainActor+ func testBottomOverlayImmediateHideCompletesBeforeReturningAndAllowsRestart() async {+ let audioPublisher = Just(CGFloat.zero).eraseToAnyPublisher()+ let controller = BottomOverlayWindowController.shared++ controller.prepare()+ await Task.yield()+ controller.show(audioPublisher: audioPublisher, mode: .dictation)+ controller.hideImmediately()++ XCTAssertTrue(controller.isVisuallyHiddenForTests)++ controller.show(audioPublisher: audioPublisher, mode: .dictation)+ XCTAssertTrue(NotchContentState.shared.isBottomOverlayPresented)+ XCTAssertFalse(controller.isVisuallyHiddenForTests)+ XCTAssertFalse(NotchContentState.shared.isBottomOverlayDismissing)+ _ = await controller.hideAndWait()+ }+func testCoreAudioFrameCountUsesActualBufferChannelLayout() {XCTAssertEqual(fv_core_audio_buffer_frame_count(512 * 4, 4, 1), 512)XCTAssertEqual(fv_core_audio_buffer_frame_count(512 * 8, 4, 2), 512)@@ -228,7 +252,7 @@ final class HotkeyShortcutTests: XCTestCase {defer { settingsStore.skipSilentRecordingsEnabled = originalValue }settingsStore.skipSilentRecordingsEnabled = true- let document = await BackupService.shared.makeBackupDocument()+ let document = try await BackupService.shared.makeBackupDocument()XCTAssertEqual(document.settings.skipSilentRecordingsEnabled, true)let encoded = try BackupService.shared.encode(document)@@ -258,7 +282,7 @@ final class HotkeyShortcutTests: XCTestCase {XCTAssertTrue(SettingsStore.shared.experimentalParakeetUnifiedFinalEnabled)SettingsStore.shared.experimentalParakeetUnifiedFinalEnabled = false- let document = await BackupService.shared.makeBackupDocument()+ let document = try await BackupService.shared.makeBackupDocument()XCTAssertEqual(document.settings.experimentalParakeetUnifiedFinalEnabled, false)let encoded = try BackupService.shared.encode(document)@@ -288,7 +312,7 @@ final class HotkeyShortcutTests: XCTestCase {XCTAssertFalse(SettingsStore.shared.showHistoryPerformanceMetrics)SettingsStore.shared.showHistoryPerformanceMetrics = true- let document = await BackupService.shared.makeBackupDocument()+ let document = try await BackupService.shared.makeBackupDocument()XCTAssertEqual(document.settings.showHistoryPerformanceMetrics, true)let encoded = try BackupService.shared.encode(document)@@ -340,7 +364,7 @@ final class HotkeyShortcutTests: XCTestCase {@MainActorfunc testLegacySystemModeBackupQueuesMicrophonePriorityMigration() async throws {- let document = await BackupService.shared.makeBackupDocument()+ let document = try await BackupService.shared.makeBackupDocument()try self.withRestoredDefaults(keys: [self.microphoneSelectionModeKey,@@ -366,8 +390,8 @@ final class HotkeyShortcutTests: XCTestCase {}@MainActor- func testPriorityBackupKeepsCompletedMicrophoneMigration() async {- let document = await BackupService.shared.makeBackupDocument()+ func testPriorityBackupKeepsCompletedMicrophoneMigration() async throws {+ let document = try await BackupService.shared.makeBackupDocument()self.withRestoredDefaults(keys: [self.microphoneSelectionMigrationVersionKey]) {SettingsStore.shared.microphoneSelectionMigrationVersion = 4@@ -379,7 +403,7 @@ final class HotkeyShortcutTests: XCTestCase {}@MainActor- func testPriorityBackupRoundTripsRemovedConnectedMicrophones() async {+ func testPriorityBackupRoundTripsRemovedConnectedMicrophones() async throws {let originalPriority = SettingsStore.shared.microphonePrioritylet originalSuppressedUIDs = SettingsStore.shared.suppressedMicrophoneUIDsdefer {@@ -391,7 +415,7 @@ final class HotkeyShortcutTests: XCTestCase {.init(uid: "kept-mic", name: "Kept Microphone"),]SettingsStore.shared.suppressedMicrophoneUIDs = ["removed-connected-mic"]- let document = await BackupService.shared.makeBackupDocument()+ let document = try await BackupService.shared.makeBackupDocument()XCTAssertEqual(document.settings.suppressedMicrophoneUIDs, ["removed-connected-mic"])SettingsStore.shared.suppressedMicrophoneUIDs = []@@ -1953,10 +1977,10 @@ final class HotkeyShortcutTests: XCTestCase {}@MainActor- func testSelectingOrRestoringMicrophoneClearsRemovalSuppression() async {+ func testSelectingOrRestoringMicrophoneClearsRemovalSuppression() async throws {let originalSuppressedUIDs = SettingsStore.shared.suppressedMicrophoneUIDsSettingsStore.shared.suppressedMicrophoneUIDs = []- let document = await BackupService.shared.makeBackupDocument()+ let document = try await BackupService.shared.makeBackupDocument()defer { SettingsStore.shared.suppressedMicrophoneUIDs = originalSuppressedUIDs }self.withRestoredDefaults(keys: [diff --git a/Tests/FluidDictationIntegrationTests/KeychainServiceCacheTests.swift b/Tests/FluidDictationIntegrationTests/KeychainServiceCacheTests.swiftnew file mode 100644index 00000000..9c093131--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/KeychainServiceCacheTests.swift@@ -0,0 +1,190 @@+@testable import FluidVoice_Debug+import XCTest++private final class KeychainServiceBox: @unchecked Sendable {+ let service: KeychainService++ init(_ service: KeychainService) {+ self.service = service+ }+}++final class KeychainServiceCacheTests: XCTestCase {+ func testConcurrentStoresDoNotLoseUpdates() throws {+ let storageLock = NSLock()+ var storage: [String: String] = [:]+ let service = KeychainService(+ testingLoad: { storageLock.withLock { storage } },+ testingSave: { values in storageLock.withLock { storage = values } }+ )+ let box = KeychainServiceBox(service)+ let count = 200++ DispatchQueue.concurrentPerform(iterations: count) { index in+ try? box.service.storeKey("value-\(index)", for: "provider-\(index)")+ }++ XCTAssertEqual(try service.fetchAllKeys().count, count)+ }++ func testFailedLoadIsRetriedInsteadOfCached() throws {+ struct ExpectedFailure: Error {}++ var loadCount = 0+ let service = KeychainService(+ testingLoad: {+ loadCount += 1+ if loadCount == 1 { throw ExpectedFailure() }+ return ["openai": "secret"]+ },+ testingSave: { _ in }+ )++ XCTAssertThrowsError(try service.fetchAllKeys())+ XCTAssertEqual(try service.fetchAllKeys(), ["openai": "secret"])+ XCTAssertEqual(loadCount, 2)+ }++ func testFetchAllKeysLoadsOncePerProcess() throws {+ var loadCount = 0+ let service = KeychainService(+ testingLoad: {+ loadCount += 1+ return ["openai": "secret"]+ },+ testingSave: { _ in }+ )++ XCTAssertEqual(try service.fetchAllKeys(), ["openai": "secret"])+ XCTAssertEqual(try service.fetchAllKeys(), ["openai": "secret"])+ XCTAssertEqual(loadCount, 1)+ }++ func testSuccessfulStoreUpdatesCacheWithoutReloadingKeychain() throws {+ var loadCount = 0+ var stored: [String: String] = [:]+ let service = KeychainService(+ testingLoad: {+ loadCount += 1+ return ["openai": "old"]+ },+ testingSave: { stored = $0 }+ )++ try service.storeKey(" new ", for: "groq")++ XCTAssertEqual(stored, ["openai": "old", "groq": "new"])+ XCTAssertEqual(try service.fetchAllKeys(), stored)+ XCTAssertEqual(loadCount, 1)+ }++ func testFailedStoreKeepsPreviouslyLoadedCache() throws {+ struct ExpectedFailure: Error {}++ var loadCount = 0+ let service = KeychainService(+ testingLoad: {+ loadCount += 1+ return ["openai": "old"]+ },+ testingSave: { _ in throw ExpectedFailure() }+ )++ XCTAssertThrowsError(try service.storeKey("new", for: "groq"))+ XCTAssertEqual(try service.fetchAllKeys(), ["openai": "old"])+ XCTAssertEqual(loadCount, 1)+ }++ func testDeleteUpdatesCacheWithoutReloadingKeychain() throws {+ var loadCount = 0+ var stored: [String: String] = [:]+ let service = KeychainService(+ testingLoad: {+ loadCount += 1+ return ["openai": "secret", "groq": "secret"]+ },+ testingSave: { stored = $0 }+ )++ try service.deleteKey(for: "openai")++ XCTAssertEqual(stored, ["groq": "secret"])+ XCTAssertEqual(try service.fetchAllKeys(), stored)+ XCTAssertEqual(loadCount, 1)+ }++ func testStoreRefreshesBeforeMergingExternalChanges() throws {+ var storage = ["openai": "old"]+ let service = KeychainService(+ testingLoad: { storage },+ testingSave: { storage = $0 }+ )++ XCTAssertEqual(try service.fetchAllKeys(), storage)+ storage["anthropic"] = "external"++ try service.storeKey("new", for: "groq")++ XCTAssertEqual(+ storage,+ ["openai": "old", "anthropic": "external", "groq": "new"]+ )+ XCTAssertEqual(try service.fetchAllKeys(), storage)+ }++ func testExplicitRefreshObservesExternalChanges() throws {+ var loadCount = 0+ var storage = ["openai": "old"]+ let service = KeychainService(+ testingLoad: {+ loadCount += 1+ return storage+ },+ testingSave: { storage = $0 }+ )++ XCTAssertEqual(try service.fetchAllKeys(), ["openai": "old"])+ storage["openai"] = "external"++ try service.refreshCachedKeys()++ XCTAssertEqual(try service.fetchAllKeys(), ["openai": "external"])+ XCTAssertEqual(loadCount, 2)+ }++ func testCachedReadDoesNotWaitForBlockedRefresh() throws {+ let stateLock = NSLock()+ var loadCount = 0+ let refreshStarted = DispatchSemaphore(value: 0)+ let releaseRefresh = DispatchSemaphore(value: 0)+ let refreshFinished = self.expectation(description: "refresh finished")+ let service = KeychainService(+ testingLoad: {+ let currentLoad = stateLock.withLock {+ loadCount += 1+ return loadCount+ }+ if currentLoad > 1 {+ refreshStarted.signal()+ releaseRefresh.wait()+ }+ return ["openai": currentLoad == 1 ? "cached" : "refreshed"]+ },+ testingSave: { _ in }+ )+ let box = KeychainServiceBox(service)++ XCTAssertEqual(try service.fetchAllKeys(), ["openai": "cached"])+ DispatchQueue.global(qos: .utility).async {+ try? box.service.refreshCachedKeys()+ refreshFinished.fulfill()+ }+ XCTAssertEqual(refreshStarted.wait(timeout: .now() + 1), .success)++ XCTAssertEqual(try service.fetchAllKeys(), ["openai": "cached"])++ releaseRefresh.signal()+ self.wait(for: [refreshFinished], timeout: 1)+ XCTAssertEqual(try service.fetchAllKeys(), ["openai": "refreshed"])+ }+}diff --git a/Tests/FluidDictationIntegrationTests/LLMClientRequestBodyTests.swift b/Tests/FluidDictationIntegrationTests/LLMClientRequestBodyTests.swiftindex f55280e4..11495fa1 100644--- a/Tests/FluidDictationIntegrationTests/LLMClientRequestBodyTests.swift+++ b/Tests/FluidDictationIntegrationTests/LLMClientRequestBodyTests.swift@@ -8,6 +8,33 @@ import XCTest@MainActorfinal class LLMClientRequestBodyTests: XCTestCase {+ func testDictationStreamingFallbackSkipsTransportFailuresAndCancellation() {+ XCTAssertFalse(+ DictationStreamingFallbackPolicy.shouldRetryWithoutStreaming(+ after: LLMError.networkError(URLError(.notConnectedToInternet))+ )+ )+ XCTAssertFalse(+ DictationStreamingFallbackPolicy.shouldRetryWithoutStreaming(after: CancellationError())+ )+ XCTAssertFalse(+ DictationStreamingFallbackPolicy.shouldRetryWithoutStreaming(+ after: LLMError.invalidRequest("missing prompt")+ )+ )+ }++ func testDictationStreamingFallbackRetriesProtocolFailure() {+ XCTAssertTrue(+ DictationStreamingFallbackPolicy.shouldRetryWithoutStreaming(after: LLMError.invalidResponse)+ )+ XCTAssertTrue(+ DictationStreamingFallbackPolicy.shouldRetryWithoutStreaming(+ after: LLMError.httpError(400, "streaming unsupported")+ )+ )+ }+private func config(streaming: Bool) -> LLMClient.Config {LLMClient.Config(messages: [["role": "user", "content": "hello"]],@@ -272,6 +299,27 @@ final class LLMClientStreamingTests: XCTestCase {XCTAssertEqual(response.toolCalls.first?.getString("command"), "pwd")}+ func testStreamingDecodeAndCallbacksStayOffMainThread() async throws {+ let client = self.makeClient()+ let probe = LLMCallbackThreadProbe()+ var config = LLMClient.Config(+ messages: [["role": "user", "content": "Keep UI responsive"]],+ model: "qwen-thinking",+ baseURL: "https://issue-445.test/tag-parser/v1",+ apiKey: "",+ streaming: true+ )+ config.maxRetries = 1+ config.timeoutSeconds = 5+ config.onContentChunk = { _ in probe.recordCallback() }++ let response = try await client.call(config)++ XCTAssertEqual(response.content, "Ready.")+ XCTAssertGreaterThan(probe.callbackCount, 0)+ XCTAssertFalse(probe.sawMainThread)+ }+private func makeClient() -> LLMClient {let configuration = URLSessionConfiguration.ephemeralconfiguration.protocolClasses = [Issue445StreamURLProtocol.self]@@ -279,6 +327,27 @@ final class LLMClientStreamingTests: XCTestCase {}}+private final nonisolated class LLMCallbackThreadProbe: @unchecked Sendable {+ private let lock = NSLock()+ private var recordedCallbackCount = 0+ private var recordedMainThreadCallback = false++ var callbackCount: Int {+ self.lock.withLock { self.recordedCallbackCount }+ }++ var sawMainThread: Bool {+ self.lock.withLock { self.recordedMainThreadCallback }+ }++ func recordCallback() {+ self.lock.withLock {+ self.recordedCallbackCount += 1+ self.recordedMainThreadCallback = self.recordedMainThreadCallback || Thread.isMainThread+ }+ }+}+private class Issue445StreamURLProtocol: URLProtocol {// The empty-string `content` fields are load-bearing: HEAD skips tool calls only// when `delta["content"] as? String` succeeds, so replacing them with null defangs the regression.diff --git a/Tests/FluidDictationIntegrationTests/PrivateAIDictationTokenBudgetTests.swift b/Tests/FluidDictationIntegrationTests/PrivateAIDictationTokenBudgetTests.swiftindex 6a234ab1..8e9e4fd0 100644--- a/Tests/FluidDictationIntegrationTests/PrivateAIDictationTokenBudgetTests.swift+++ b/Tests/FluidDictationIntegrationTests/PrivateAIDictationTokenBudgetTests.swift@@ -1,6 +1,97 @@@testable import FluidVoice_Debugimport XCTest+private actor PrivateAIEnhancementProbe {+ struct Call: Sendable, Equatable {+ let inputText: String+ let maxOutputTokens: Int+ }++ private var activeCallCount = 0+ private var calls: [Call] = []+ private var maximumActiveCallCount = 0++ func begin(inputText: String, maxOutputTokens: Int) {+ self.activeCallCount += 1+ self.maximumActiveCallCount = max(self.maximumActiveCallCount, self.activeCallCount)+ self.calls.append(Call(inputText: inputText, maxOutputTokens: maxOutputTokens))+ }++ func end() {+ self.activeCallCount -= 1+ }++ func snapshot() -> (calls: [Call], active: Int, maximumActive: Int) {+ (self.calls, self.activeCallCount, self.maximumActiveCallCount)+ }+}++private struct PrivateAITestFailure: Error {}++private struct PrivateAITestIntegrationProvider: PrivateAIIntegrationProviding {+ let probe: PrivateAIEnhancementProbe+ let delayNanoseconds: UInt64+ let shouldFail: Bool++ var configuredModelID: String { "test-private-model" }+ var selectedModel: PrivateAIRegisteredModel { .unavailable }+ var configuredLocalModelPath: String? { nil }+ var modelDirectoryURL: URL { FileManager.default.temporaryDirectory }+ var isLocalRuntimeConfigured: Bool { true }++ func expectedLocalModelURL(for _: PrivateAIRegisteredModel) -> URL {+ self.modelDirectoryURL.appendingPathComponent("test-private-model")+ }++ func localModelPath(for _: PrivateAIRegisteredModel) -> String? { nil }+ func isModelInstalled(_: PrivateAIRegisteredModel) -> Bool { true }++ func prepareModel(+ _ model: PrivateAIRegisteredModel,+ progressHandler _: PrivateAIModelDownloadProgressHandler?+ ) async throws -> URL {+ self.expectedLocalModelURL(for: model)+ }++ func shouldHandleDictation(model _: String) -> Bool { true }++ func status(for _: PrivateAIIntegrationService.RuntimeConfiguration) async -> PrivateAIStatus {+ PrivateAIStatus(state: .ready, message: nil)+ }++ func loadedModelState() async -> PrivateAIIntegrationService.LoadedModelState? { nil }++ func loadModel(_: PrivateAIRegisteredModel) async throws -> PrivateAIStatus {+ PrivateAIStatus(state: .ready, message: nil)+ }++ func unloadCachedRuntime(reason _: String) async {}++ nonisolated func enhanceDictation(+ _ inputText: String,+ runtime _: PrivateAIIntegrationService.RuntimeConfiguration,+ context _: PrivateAIIntegrationService.AppContext,+ maxOutputTokens: Int+ ) async throws -> PrivateAIIntegrationService.EnhancementResult {+ await self.probe.begin(inputText: inputText, maxOutputTokens: maxOutputTokens)+ do {+ if self.delayNanoseconds > 0 {+ try await Task.sleep(nanoseconds: self.delayNanoseconds)+ }+ if self.shouldFail { throw PrivateAITestFailure() }+ await self.probe.end()+ return PrivateAIIntegrationService.EnhancementResult(+ outputText: "enhanced:\(inputText)",+ backendKind: "test",+ latencyMilliseconds: 1+ )+ } catch {+ await self.probe.end()+ throw error+ }+ }+}+@MainActorfinal class PrivateAIDictationTokenBudgetTests: XCTestCase {func testPrivateAIDictationTokenBudgetFallsBackBeforeLongInputCanTruncate() {@@ -41,8 +132,167 @@ final class PrivateAIDictationTokenBudgetTests: XCTestCase {)}+ func testValidatedBudgetIsPassedToProviderWithoutRecomputation() async throws {+ let probe = PrivateAIEnhancementProbe()+ let service = PrivateAIIntegrationService(testingProvider: PrivateAITestIntegrationProvider(+ probe: probe,+ delayNanoseconds: 0,+ shouldFail: false+ ))+ let inputText = "hello fluid voice"+ let runtime = self.runtimeConfiguration()++ let result = try await service.enhanceDictation(+ inputText,+ runtime: runtime,+ context: self.appContext()+ )+ let snapshot = await probe.snapshot()++ XCTAssertEqual(result.outputText, "enhanced:\(inputText)")+ XCTAssertEqual(snapshot.calls, [PrivateAIEnhancementProbe.Call(+ inputText: inputText,+ maxOutputTokens: SettingsStore.privateAIDictationTokenBudget(+ forInputText: inputText,+ contextTokenLimit: runtime.contextTokenLimit+ ).maxOutputTokens+ )])+ }++ func testValidatedBudgetIsPassedThroughStreamingOverload() async throws {+ let probe = PrivateAIEnhancementProbe()+ let service = PrivateAIIntegrationService(testingProvider: PrivateAITestIntegrationProvider(+ probe: probe,+ delayNanoseconds: 0,+ shouldFail: false+ ))+ let inputText = "streamed fluid voice"+ let runtime = self.runtimeConfiguration()++ let result = try await service.enhanceDictation(+ inputText,+ runtime: runtime,+ context: self.appContext(),+ streamHandler: { _ in }+ )+ let snapshot = await probe.snapshot()++ XCTAssertEqual(result.outputText, "enhanced:\(inputText)")+ XCTAssertEqual(snapshot.calls, [PrivateAIEnhancementProbe.Call(+ inputText: inputText,+ maxOutputTokens: SettingsStore.privateAIDictationTokenBudget(+ forInputText: inputText,+ contextTokenLimit: runtime.contextTokenLimit+ ).maxOutputTokens+ )])+ }++ func testConcurrentEnhancementsRemainIndependentAndCanOverlap() async throws {+ let probe = PrivateAIEnhancementProbe()+ let service = PrivateAIIntegrationService(testingProvider: PrivateAITestIntegrationProvider(+ probe: probe,+ delayNanoseconds: 20_000_000,+ shouldFail: false+ ))+ let runtime = self.runtimeConfiguration()+ let context = self.appContext()++ let outputs = try await withThrowingTaskGroup(of: String.self) { group in+ for index in 0..<20 {+ group.addTask {+ try await service.enhanceDictation(+ "request-\(index)",+ runtime: runtime,+ context: context+ ).outputText+ }+ }+ return try await group.reduce(into: []) { $0.append($1) }+ }+ let snapshot = await probe.snapshot()++ XCTAssertEqual(Set(outputs), Set((0..<20).map { "enhanced:request-\($0)" }))+ XCTAssertEqual(snapshot.calls.count, 20)+ XCTAssertEqual(snapshot.active, 0)+ XCTAssertGreaterThan(snapshot.maximumActive, 1)+ }++ func testCancellationPropagatesAndLeavesNoActiveProviderCall() async {+ let probe = PrivateAIEnhancementProbe()+ let service = PrivateAIIntegrationService(testingProvider: PrivateAITestIntegrationProvider(+ probe: probe,+ delayNanoseconds: 5_000_000_000,+ shouldFail: false+ ))+ let task = Task {+ try await service.enhanceDictation(+ "cancel me",+ runtime: self.runtimeConfiguration(),+ context: self.appContext()+ )+ }+ await Task.yield()+ task.cancel()++ do {+ _ = try await task.value+ XCTFail("Expected cancellation to propagate")+ } catch is CancellationError {+ // Expected.+ } catch {+ XCTFail("Unexpected error: \(error)")+ }++ let snapshot = await probe.snapshot()+ XCTAssertEqual(snapshot.active, 0)+ }++ func testProviderFailurePropagatesWithoutChangingIt() async {+ let probe = PrivateAIEnhancementProbe()+ let service = PrivateAIIntegrationService(testingProvider: PrivateAITestIntegrationProvider(+ probe: probe,+ delayNanoseconds: 0,+ shouldFail: true+ ))++ do {+ _ = try await service.enhanceDictation(+ "fail me",+ runtime: self.runtimeConfiguration(),+ context: self.appContext()+ )+ XCTFail("Expected provider failure to propagate")+ } catch is PrivateAITestFailure {+ // Expected.+ } catch {+ XCTFail("Unexpected error: \(error)")+ }++ let snapshot = await probe.snapshot()+ XCTAssertEqual(snapshot.active, 0)+ XCTAssertEqual(snapshot.calls.count, 1)+ }+private func assertRejectedBeforeProvider(_ transcript: String, failureMessage: String) async {- let runtime = PrivateAIIntegrationService.RuntimeConfiguration(+ let runtime = self.runtimeConfiguration()+ let context = self.appContext()++ do {+ _ = try await PrivateAIIntegrationService.shared.enhanceDictation(+ transcript,+ runtime: runtime,+ context: context+ )+ XCTFail(failureMessage)+ } catch AIProcessingError.dictationExceedsAIContextWindow {+ // Expected: ContentView catches this and types the complete raw transcript.+ } catch {+ XCTFail("Unexpected error: \(error)")+ }+ }++ private func runtimeConfiguration() -> PrivateAIIntegrationService.RuntimeConfiguration {+ PrivateAIIntegrationService.RuntimeConfiguration(selectedProviderID: "private",providerKey: "private",baseURL: "",@@ -53,24 +303,14 @@ final class PrivateAIDictationTokenBudgetTests: XCTestCase {usesFluid1Boost: true,contextTokenLimit: 4096)- let context = PrivateAIIntegrationService.AppContext(+ }++ private func appContext() -> PrivateAIIntegrationService.AppContext {+ PrivateAIIntegrationService.AppContext(appName: "Notes",bundleID: "com.apple.Notes",windowTitle: "",appVersion: nil)-- do {- _ = try await PrivateAIIntegrationService.shared.enhanceDictation(- transcript,- runtime: runtime,- context: context- )- XCTFail(failureMessage)- } catch AIProcessingError.dictationExceedsAIContextWindow {- // Expected: ContentView catches this and types the complete raw transcript.- } catch {- XCTFail("Unexpected error: \(error)")- }}}diff --git a/Tests/FluidDictationIntegrationTests/SpokenSendTests.swift b/Tests/FluidDictationIntegrationTests/SpokenSendTests.swiftindex fc6b3221..95b81e06 100644--- a/Tests/FluidDictationIntegrationTests/SpokenSendTests.swift+++ b/Tests/FluidDictationIntegrationTests/SpokenSendTests.swift@@ -377,7 +377,7 @@ final class SpokenSendTests: XCTestCase {}@MainActor- func testSettingsBackupIncludesSpokenSendConfiguration() async {+ func testSettingsBackupIncludesSpokenSendConfiguration() async throws {let settings = SettingsStore.sharedlet originalEnabled = settings.spokenSendEnabledlet originalImmediate = settings.spokenSendImmediatelyEnabled@@ -395,7 +395,7 @@ final class SpokenSendTests: XCTestCase {settings.spokenSendPhrase = "ship it"settings.spokenSendKey = .commandEnter- let document = await BackupService.shared.makeBackupDocument()+ let document = try await BackupService.shared.makeBackupDocument()XCTAssertEqual(document.settings.spokenSendEnabled, true)XCTAssertEqual(document.settings.spokenSendImmediatelyEnabled, false)XCTAssertEqual(document.settings.spokenSendPhrase, "ship it")diff --git a/Tests/HistoryPersistenceBoundaryTests.swift b/Tests/HistoryPersistenceBoundaryTests.swiftnew file mode 100644index 00000000..100ddc8e--- /dev/null+++ b/Tests/HistoryPersistenceBoundaryTests.swift@@ -0,0 +1,284 @@+import Combine+import Foundation+import SQLite3++// These doubles prevent the standalone test executable from touching app audio or settings.+struct DictationAudioMetadata: Codable, Equatable, Sendable {+ let fileName: String+ let durationMilliseconds: Int+ let byteCount: Int+ let sampleRate: Int+ let channels: Int+ let model: String?+}++final class DictationAudioHistoryStore {+ static let shared = DictationAudioHistoryStore()+ @discardableResult func deleteAudio(fileName: String) -> Int64 { 0 }+ func deleteAllAudioFiles() {}+ func audioUsageBytes() -> Int64 { 0 }+ func deleteUnreferencedAudioFiles(referencedFileNames: Set<String>) -> (fileCount: Int, byteCount: Int64) { (0, 0) }+}++@MainActor final class SettingsStore {+ static let shared = SettingsStore()+ var audioHistoryBudgetBytes: Int64 { 1_000_000 }+ var weekendsDontBreakStreak: Bool { false }+}++final class DebugLogger {+ static let shared = DebugLogger()+ func info(_ message: String, source: String) {}+ func debug(_ message: String, source: String) {}+}++@main struct HistoryPersistenceBoundaryTests {+ @MainActor static func main() async throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("fluid-history-tests-\(UUID())")+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let suite = "fluid-history-tests-\(UUID())"+ guard let defaults = UserDefaults(suiteName: suite) else {+ fatalError("Unable to create isolated history defaults")+ }+ defer { defaults.removePersistentDomain(forName: suite) }+ let key = "TranscriptionHistoryEntries"+ let audio = DictationAudioMetadata(+ fileName: "test.wav",+ durationMilliseconds: 1000,+ byteCount: 32_000,+ sampleRate: 16_000,+ channels: 1,+ model: "test"+ )+ let legacy = (0..<8400).map { index in+ TranscriptionHistoryEntry(+ timestamp: Date(timeIntervalSince1970: Double(index)),+ rawText: "Raw \(index)",+ processedText: String(repeating: "Test dictation \(index). ", count: 12),+ appName: "Test",+ windowTitle: "Test",+ wasAIProcessed: true,+ processingModel: "test",+ transcriptionDurationMilliseconds: 50,+ aiProcessingDurationMilliseconds: 100,+ aiTokensPerSecond: 500,+ audio: index == 0 ? audio : nil+ )+ }+ try defaults.set(JSONEncoder().encode(legacy), forKey: key)+ let url = root.appendingPathComponent("history.sqlite3")+ let writer = TranscriptionHistoryWriter(defaults: defaults, url: url)+ let store = TranscriptionHistoryStore(writer: writer)+ // No actor suspension: these mutations necessarily precede startup loading.+ let newID = UUID()+ store.addEntry(id: newID, rawText: "new", processedText: "New dictation", appName: "Test", windowTitle: "Test")+ store.attachAudio(audio, to: newID)+ store.deleteEntry(id: legacy[1].id)+ try await store.waitUntilLoaded()+ await store.waitForTodaySummary()+ precondition(store.todaySummary == .init(words: 2, transcriptions: 1), "Startup stats must include merged pending edits")+ await store.finishPendingWrites()+ precondition(defaults.data(forKey: key) == nil, "Retire legacy only after successful import")+ precondition(store.entries.count == 8400)+ precondition(store.entries.first(where: { $0.id == newID })?.audio == audio)+ precondition(!store.entries.contains(where: { $0.id == legacy[1].id }))+ let reloaded = try await TranscriptionHistoryWriter(defaults: defaults, url: url).load()+ precondition(reloaded == store.entries, "Migration, metadata and concurrent startup edits must round-trip")+ print("PASS: 8,400-entry migration, exact round-trip, startup insert/audio/delete")++ // Reject a write touching any old entry. A new dictation and its audio must only update their row.+ try self.sql(url, "CREATE TRIGGER reject_old BEFORE INSERT ON history WHEN NEW.id != '\(newID.uuidString)' BEGIN SELECT RAISE(FAIL, 'unrelated row rewritten'); END")+ let enqueueStart = ProcessInfo.processInfo.systemUptime+ store.attachAudio(audio, to: newID)+ let enqueueMs = (ProcessInfo.processInfo.systemUptime - enqueueStart) * 1000+ await store.finishPendingWrites()+ await Task.yield()+ precondition(store.persistenceError == nil, "Updating one row must not rewrite unrelated history")+ print("PASS: single-row audio update; main actor enqueue \(enqueueMs) ms")+ try self.sql(url, "DROP TRIGGER reject_old")++ try self.sql(url, "CREATE TRIGGER reject_all BEFORE INSERT ON history BEGIN SELECT RAISE(FAIL, 'test disk failure'); END")+ let failedID = UUID()+ store.addEntry(id: failedID, rawText: "pending", processedText: "Unsaved", appName: "Test", windowTitle: "Test")+ await store.finishPendingWrites()+ for _ in 0..<10 {+ await Task.yield()+ }+ precondition(store.persistenceError != nil)+ precondition(store.entries.contains(where: { $0.id == failedID }))+ await store.waitForTodaySummary()+ precondition(store.todaySummary == .init(words: 3, transcriptions: 2), "A disk error must not drop in-memory stats")+ let afterFailure = try await writer.load()+ precondition(!afterFailure.contains(where: { $0.id == failedID }))+ store.retryPersistence()+ await store.finishPendingWrites()+ let afterFailedReplacement = try await writer.load()+ precondition(afterFailedReplacement == afterFailure, "Failed replacement must roll back its initial DELETE")+ try self.sql(url, "DROP TRIGGER reject_all")+ store.retryPersistence()+ await store.finishPendingWrites()+ for _ in 0..<10 {+ await Task.yield()+ }+ precondition(store.persistenceError == nil)+ let afterRetry = try await writer.load()+ precondition(afterRetry.contains(where: { $0.id == failedID }))+ print("PASS: failed write stays in memory, surfaces error, retry restores complete snapshot")++ store.clearAllHistory()+ store.attachAudio(audio, to: newID)+ await store.finishPendingWrites()+ let afterClear = try await writer.load()+ precondition(afterClear.isEmpty, "Late audio must not resurrect deleted entries")+ try defaults.set(JSONEncoder().encode(legacy), forKey: key)+ let afterRestart = try await TranscriptionHistoryWriter(defaults: defaults, url: url).load()+ precondition(afterRestart.isEmpty, "Migration marker must prevent old history resurrection")+ print("PASS: clear, late audio, restart and stale legacy cannot resurrect history")++ let badURL = root.appendingPathComponent("bad.sqlite3")+ let badData = Data("invalid JSON".utf8)+ defaults.set(badData, forKey: key)+ let badStore = TranscriptionHistoryStore(writer: TranscriptionHistoryWriter(defaults: defaults, url: badURL))+ do {+ try await badStore.waitUntilLoaded()+ preconditionFailure("Corrupt legacy must fail visibly")+ } catch {}+ precondition(!badStore.isLoading && badStore.persistenceError != nil)+ precondition(defaults.data(forKey: key) == badData)+ try defaults.set(JSONEncoder().encode([legacy[0]]), forKey: key)+ badStore.retryPersistence()+ try await badStore.waitUntilLoaded()+ precondition(badStore.entries == [legacy[0]])+ print("PASS: corrupt migration preserves source, exits loading and supports retry")++ let restoreStore = TranscriptionHistoryStore(writer: TranscriptionHistoryWriter(defaults: defaults, url: url))+ restoreStore.restore(from: [legacy[3]])+ try await restoreStore.waitUntilLoaded()+ await restoreStore.finishPendingWrites()+ precondition(restoreStore.entries == [legacy[3]])+ let afterRestore = try await TranscriptionHistoryWriter(defaults: defaults, url: url).load()+ precondition(afterRestore == [legacy[3]])+ print("PASS: restore during loading replaces both memory and disk")+ try await self.testTodaySummary(root: root, defaults: defaults, audio: audio)+ }++ @MainActor static func testTodaySummary(root: URL, defaults: UserDefaults, audio: DictationAudioMetadata) async throws {+ let formatter = ISO8601DateFormatter()+ guard var now = formatter.date(from: "2026-03-08T18:00:00Z"),+ let losAngeles = TimeZone(identifier: "America/Los_Angeles"),+ let plusFourteen = TimeZone(secondsFromGMT: 14 * 3600)+ else { preconditionFailure("Invalid calendar fixtures") }+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = losAngeles+ var clockReads = 0+ let writer = TranscriptionHistoryWriter(defaults: defaults, url: root.appendingPathComponent("summary.sqlite3"))+ let store = TranscriptionHistoryStore(+ writer: writer,+ summaryNow: {+ clockReads += 1+ return now+ },+ summaryCalendar: { calendar }+ )+ try await store.waitUntilLoaded()+ await store.waitForTodaySummary()+ guard let day = calendar.dateInterval(of: .day, for: now) else {+ preconditionFailure("Missing fixture day")+ }+ precondition(day.duration == 23 * 3600, "Fixture must exercise a DST-shortened day")+ func entry(_ timestamp: Date, _ text: String) -> TranscriptionHistoryEntry {+ TranscriptionHistoryEntry(+ timestamp: timestamp,+ rawText: text,+ processedText: text,+ appName: "Test",+ windowTitle: "Test",+ wasAIProcessed: false+ )+ }+ let yesterday = entry(day.start.addingTimeInterval(-1), "not today")+ let first = entry(day.start, " one\t two\nthree ")+ let last = entry(day.end.addingTimeInterval(-1), "four")+ let tomorrow = entry(day.end, "next day")+ store.restore(from: [yesterday, first, last, tomorrow])+ await store.waitForTodaySummary()+ precondition(store.todaySummary == .init(words: 4, transcriptions: 2), "Preserve word splitting and half-open local-day boundaries")+ let reads = clockReads+ let unchangedEntries = store.entries+ for _ in 0..<10_000 {+ precondition(store.todaySummary.words == 4)+ }+ precondition(clockReads == reads, "Rendering must not query clock or schedule a recount")+ store.attachAudio(audio, to: first.id)+ await store.waitForTodaySummary()+ precondition(clockReads == reads, "Audio-only metadata must not invalidate text stats")+ precondition(store.entries.map(\.processedText) == unchangedEntries.map(\.processedText))+ precondition(store.selectedEntryID == unchangedEntries.first?.id, "Summary work must not change selection")+ store.deleteEntry(id: UUID())+ store.deleteEntries(ids: [])+ await store.waitForTodaySummary()+ precondition(clockReads == reads, "No-op deletions must not schedule work")+ print("PASS: constant-time stats reads, exact whitespace/DST boundaries, audio-only non-effects")++ let additionID = UUID()+ store.addEntry(id: additionID, timestamp: now, rawText: "new text", processedText: "new text", appName: "Test", windowTitle: "Test")+ store.deleteEntry(id: first.id)+ store.deleteEntries(ids: [last.id])+ await store.waitForTodaySummary()+ precondition(store.todaySummary == .init(words: 2, transcriptions: 1))+ store.addEntry(timestamp: now, rawText: "", processedText: " \n ", appName: "Test", windowTitle: "Test")+ await store.waitForTodaySummary()+ precondition(store.todaySummary == .init(words: 2, transcriptions: 1))++ // Bulk replacement followed by rapid changes must only publish the latest history.+ store.restore(from: Array(repeating: first, count: 10_000))+ await Task.yield()+ store.restore(from: [yesterday, first, last, tomorrow])+ store.deleteEntries(ids: [first.id, last.id])+ await store.waitForTodaySummary()+ precondition(store.todaySummary == .init(words: 0, transcriptions: 0), "Never apply a stale bulk-rebuild result")+ var replacedFromSubscriber = false+ let subscription = store.$todaySummary.sink { summary in+ guard summary.words == 3, !replacedFromSubscriber else { return }+ replacedFromSubscriber = true+ store.restore(from: [yesterday, tomorrow])+ }+ store.restore(from: [first])+ await store.waitForTodaySummary()+ precondition(replacedFromSubscriber && store.todaySummary == .init(words: 0, transcriptions: 0), "Reentrant changes must not be lost during publication")+ subscription.cancel()+ print("PASS: insert/delete/bulk-delete/empty input and rapid replacement converge to latest snapshot")++ now = day.end.addingTimeInterval(1)+ store.refreshTodaySummaryForCalendarChange()+ await store.waitForTodaySummary()+ precondition(store.todaySummary == .init(words: 2, transcriptions: 1), "Midnight must refresh without a dictation")+ now = day.end.addingTimeInterval(12 * 3600)+ calendar.timeZone = plusFourteen+ store.refreshTodaySummaryForCalendarChange()+ await store.waitForTodaySummary()+ precondition(store.todaySummary == .init(words: 0, transcriptions: 0), "Timezone changes must redefine today")+ now = yesterday.timestamp+ calendar.timeZone = losAngeles+ store.refreshTodaySummaryForCalendarChange()+ await store.waitForTodaySummary()+ precondition(store.todaySummary == .init(words: 2, transcriptions: 1), "Clock moving backward must refresh")+ let settledReads = clockReads+ store.refreshTodaySummaryForCalendarChange()+ await store.waitForTodaySummary()+ precondition(clockReads == settledReads + 1, "Activation within same day must not rebuild")+ store.clearAllHistory()+ await store.waitForTodaySummary()+ precondition(store.todaySummary == .init(words: 0, transcriptions: 0))+ await store.finishPendingWrites()+ print("PASS: day/timezone/backward-clock changes, unchanged-day no-op, and clear")+ }++ static func sql(_ url: URL, _ command: String) throws {+ var handle: OpaquePointer?+ precondition(sqlite3_open(url.path, &handle) == SQLITE_OK)+ defer { sqlite3_close(handle) }+ precondition(sqlite3_exec(handle, command, nil, nil, nil) == SQLITE_OK)+ }+}diff --git a/Tests/PasteKeyCodeCacheLiveLayoutTests.swift b/Tests/PasteKeyCodeCacheLiveLayoutTests.swiftnew file mode 100644index 00000000..bd8abfbe--- /dev/null+++ b/Tests/PasteKeyCodeCacheLiveLayoutTests.swift@@ -0,0 +1,71 @@+import AppKit+import Carbon.HIToolbox++// Opt-in live test. Temporarily selects Dvorak and restores the original layout.+@main+enum PasteKeyCodeCacheLiveLayoutTests {+ static func value(_ source: TISInputSource, _ property: CFString) -> String {+ guard let pointer = TISGetInputSourceProperty(source, property) else { return "" }+ return Unmanaged<CFString>.fromOpaque(pointer).takeUnretainedValue() as String+ }++ static func resolveV() -> CGKeyCode {+ PasteKeyCodeResolver.current()+ }++ static func main() throws {+ let app = NSApplication.shared+ app.setActivationPolicy(.prohibited)+ let original = TISCopyCurrentKeyboardInputSource().takeRetainedValue()+ guard let sources = TISCreateInputSourceList(nil, true).takeRetainedValue() as? [TISInputSource] else {+ throw NSError(domain: "Input source list unavailable", code: 9)+ }+ guard let dvorak = sources.first(where: { value($0, kTISPropertyInputSourceID) == "com.apple.keylayout.Dvorak" }) else {+ throw NSError(domain: "Dvorak unavailable", code: 1)+ }+ guard let enabledPointer = TISGetInputSourceProperty(dvorak, kTISPropertyInputSourceIsEnabled) else {+ throw NSError(domain: "Dvorak enabled state unavailable", code: 10)+ }+ let wasEnabled = CFBooleanGetValue(Unmanaged<CFBoolean>.fromOpaque(enabledPointer).takeUnretainedValue())+ defer {+ let restored = TISSelectInputSource(original)+ RunLoop.current.run(until: Date().addingTimeInterval(0.2))+ let disabled = wasEnabled ? noErr : TISDisableInputSource(dvorak)+ print("RESTORE selection=\(restored) removeTemporaryDvorak=\(disabled) current=\(value(TISCopyCurrentKeyboardInputSource().takeRetainedValue(), kTISPropertyInputSourceID))")+ }+ guard TISEnableInputSource(dvorak) == noErr else { throw NSError(domain: "Enable failed", code: 2) }+ var refreshes = 0+ let cache = PasteKeyCodeCache {+ refreshes += 1+ return self.resolveV()+ }+ cache.start()+ print("START key=\(cache.snapshot())")+ for source in [dvorak, original, dvorak, original] {+ let start = ProcessInfo.processInfo.systemUptime+ guard TISSelectInputSource(source) == noErr else { throw NSError(domain: "Select failed", code: 3) }+ let expected = self.resolveV()+ let immediate = cache.snapshot()+ let deadline = Date().addingTimeInterval(2)+ while cache.snapshot() != expected, Date() < deadline {+ RunLoop.current.run(until: Date().addingTimeInterval(0.001))+ }+ guard cache.snapshot() == expected else { throw NSError(domain: "Stale cache", code: 4) }+ print("SWITCH \(self.value(source, kTISPropertyInputSourceID)) expected=\(expected) immediate=\(immediate) refreshed=\(cache.snapshot()) elapsedMs=\((ProcessInfo.processInfo.systemUptime - start) * 1000)")+ }+ // Several changes without yielding the main run loop: the request must use+ // the final layout, even if notifications are still queued or coalesced.+ for source in [dvorak, original, dvorak] {+ guard TISSelectInputSource(source) == noErr else { throw NSError(domain: "Rapid select failed", code: 6) }+ }+ let expectedAfterRapidChanges = self.resolveV()+ let deadline = Date().addingTimeInterval(2)+ while cache.snapshot() != expectedAfterRapidChanges, Date() < deadline {+ RunLoop.current.run(until: Date().addingTimeInterval(0.001))+ }+ guard cache.snapshot() == expectedAfterRapidChanges else { throw NSError(domain: "Rapid refresh failed", code: 7) }+ RunLoop.current.run(until: Date().addingTimeInterval(0.2))+ guard cache.snapshot() == expectedAfterRapidChanges else { throw NSError(domain: "Late notification regressed cache", code: 8) }+ print("PASS live notifications; refreshes=\(refreshes)")+ }+}diff --git a/Tests/PasteKeyCodeCacheRegressionTests.swift b/Tests/PasteKeyCodeCacheRegressionTests.swiftnew file mode 100644index 00000000..a0638295--- /dev/null+++ b/Tests/PasteKeyCodeCacheRegressionTests.swift@@ -0,0 +1,73 @@+import AppKit+import Carbon.HIToolbox++// Standalone executable: compile with the production PasteKeyCodeCache.swift.+@main+enum PasteKeyCodeCacheRegressionTests {+ static func main() {+ precondition(Thread.isMainThread)+ let name = Notification.Name("FluidVoice.PasteKeyCacheTest.\(UUID().uuidString)")+ var selectedKey: CGKeyCode = 9+ var lookups = 0+ let cache = PasteKeyCodeCache(notificationName: name) {+ precondition(Thread.isMainThread)+ lookups += 1+ return selectedKey+ }+ cache.start()+ cache.start()+ precondition(lookups == 1, "Startup must resolve exactly once")+ for _ in 0..<10_000 {+ precondition(cache.snapshot() == 9)+ }+ precondition(lookups == 1, "Pastes must not query the layout")+ DistributedNotificationCenter.default().postNotificationName(+ Notification.Name("FluidVoice.UnrelatedTest.\(UUID().uuidString)"),+ object: nil,+ userInfo: nil,+ deliverImmediately: true+ )+ RunLoop.current.run(until: Date().addingTimeInterval(0.02))+ precondition(lookups == 1, "Unrelated notifications must not refresh the cache")++ func notifyAndWait(for key: CGKeyCode) {+ selectedKey = key+ DistributedNotificationCenter.default().postNotificationName(+ name,+ object: nil,+ userInfo: nil,+ deliverImmediately: true+ )+ let deadline = Date().addingTimeInterval(2)+ while cache.snapshot() != key, Date() < deadline {+ RunLoop.current.run(until: Date().addingTimeInterval(0.005))+ }+ precondition(cache.snapshot() == key, "Layout-change notification must update the snapshot")+ }+ notifyAndWait(for: 47) // Alternate layout, not hard-coded QWERTY.+ notifyAndWait(for: 9) // Resolver's unavailable-layout fallback replaces stale key.+ for key: CGKeyCode in [47, 12, 9, 47, 9] {+ notifyAndWait(for: key)+ }++ // Main thread is deliberately blocked: cached reads must still finish.+ let finished = DispatchSemaphore(value: 0)+ let lookupsBeforeReads = lookups+ DispatchQueue.global().async {+ DispatchQueue.concurrentPerform(iterations: 10_000) { _ in+ precondition(cache.snapshot() == 9)+ }+ finished.signal()+ }+ precondition(finished.wait(timeout: .now() + 2) == .success, "Background reads must not wait for main")+ precondition(lookups == lookupsBeforeReads)++ var released: PasteKeyCodeCache? = PasteKeyCodeCache(notificationName: name) { 9 }+ released?.start()+ weak var weakCache = released+ released = nil+ precondition(weakCache == nil, "Observer must not retain cache")+ weakCache = nil+ print("PASS: startup, cache hits, layout notifications, fallback, rapid changes, concurrent reads, observer cleanup")+ }+}diff --git a/Tests/PasteKeyCodeResolverTests.swift b/Tests/PasteKeyCodeResolverTests.swiftnew file mode 100644index 00000000..e9f1884d--- /dev/null+++ b/Tests/PasteKeyCodeResolverTests.swift@@ -0,0 +1,33 @@+import Carbon.HIToolbox+import Foundation++@main+enum PasteKeyCodeResolverTests {+ static func main() {+ // Read installed layout data without enabling or switching any user input source.+ guard let sources = TISCreateInputSourceList(nil, true).takeRetainedValue() as? [TISInputSource] else {+ fatalError("Unable to read installed keyboard layouts")+ }+ for (identifier, expected): (String, CGKeyCode) in [+ ("com.apple.keylayout.US", 9),+ ("com.apple.keylayout.Dvorak", 47),+ ("com.apple.keylayout.DVORAK-QWERTYCMD", 9),+ ("com.apple.keylayout.French", 9),+ ("com.apple.keylayout.Russian", 9),+ ] {+ guard let source = sources.first(where: { source in+ guard let pointer = TISGetInputSourceProperty(source, kTISPropertyInputSourceID) else { return false }+ return Unmanaged<CFString>.fromOpaque(pointer).takeUnretainedValue() as String == identifier+ }), let pointer = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData) else {+ fatalError("Missing test layout: \(identifier)")+ }+ let data = Unmanaged<CFData>.fromOpaque(pointer).takeUnretainedValue() as Data+ let actual = PasteKeyCodeResolver.resolve(layoutData: data, keyboardType: UInt32(LMGetKbdType()))+ precondition(actual == expected, "\(identifier): expected \(expected), got \(actual)")+ print("PASS \(identifier) Cmd+V=\(actual)")+ }+ precondition(PasteKeyCodeResolver.resolve(layoutData: nil, keyboardType: 0) == 9)+ precondition(PasteKeyCodeResolver.resolve(layoutData: Data(), keyboardType: 0) == 9)+ print("PASS unavailable layout fallback")+ }+}diff --git a/Tests/run_paste_key_cache_tests.sh b/Tests/run_paste_key_cache_tests.shnew file mode 100644index 00000000..b89f14ea--- /dev/null+++ b/Tests/run_paste_key_cache_tests.sh@@ -0,0 +1,29 @@+#!/bin/sh+set -eu++task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"+case "$task_developer_dir" in+ */Xcode*.app/Contents/Developer) ;;+ *) echo "Set DEVELOPER_DIR to an installed full Xcode before running tests." >&2; exit 1 ;;+esac+export DEVELOPER_DIR="$task_developer_dir"+task_repo_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)+task_test_dir=$(mktemp -d /tmp/fluidvoice-paste-cache-tests.XXXXXX)+xcrun swiftc -O \+ "$task_repo_dir/Sources/Fluid/Services/PasteKeyCodeCache.swift" \+ "$task_repo_dir/Tests/PasteKeyCodeCacheRegressionTests.swift" \+ -o "$task_test_dir/paste-cache-tests"+"$task_test_dir/paste-cache-tests"+xcrun swiftc -O \+ "$task_repo_dir/Sources/Fluid/Services/PasteKeyCodeResolver.swift" \+ "$task_repo_dir/Tests/PasteKeyCodeResolverTests.swift" \+ -o "$task_test_dir/paste-resolver-tests"+"$task_test_dir/paste-resolver-tests"+if [ "${1:-}" = "--live" ]; then+ xcrun swiftc -O \+ "$task_repo_dir/Sources/Fluid/Services/PasteKeyCodeCache.swift" \+ "$task_repo_dir/Sources/Fluid/Services/PasteKeyCodeResolver.swift" \+ "$task_repo_dir/Tests/PasteKeyCodeCacheLiveLayoutTests.swift" \+ -o "$task_test_dir/paste-live-tests"+ "$task_test_dir/paste-live-tests"+fidiff --git a/scripts/dictation_log_summary.py b/scripts/dictation_log_summary.pynew file mode 100644index 00000000..ae3ee2ae--- /dev/null+++ b/scripts/dictation_log_summary.py@@ -0,0 +1,464 @@+#!/usr/bin/env python3+"""Read-only, standard-library summary of recent FluidVoice dictation timings.++Usage: python3 scripts/dictation_log_summary.py --last 5 [--details] [--json]+Reads Fluid.log.1 then Fluid.log. Explicit paths are accepted with --log PATH.+No recording, playback, app activation, or file writes are performed.+"""++import argparse+import json+import math+import re+import statistics+from pathlib import Path+++MARKER = re.compile(+ r"\b(APP_BENCH|ASR_BENCH|FI_SERVICE_BENCH|FI_BRIDGE_BENCH|LLM_BENCH|OVERLAY_BENCH|TYPING_BENCH|HISTORY_BENCH|PIPELINE_SUMMARY|DICTATION_SUMMARY)\b(.*)"+)+FIELD = re.compile(r"(?:^|\s)(\w+)=([^\s]+)")+WALL = re.compile(r"^\[([\d:.]+)\]")+++def parse_logs(lines):+ """Group at recording boundaries; never reuse a previous run's timings.++ Late ID-bearing callbacks are routed back to their original pipeline.+ Unlabelled tail events after a rapid restart cannot be safely attributed;+ keep them in the timeline but exclude pre-stop events from stop metrics.+ App restarts reset correlation even when IDs/session numbers are reused.+ """+ runs, by_id, current, seen = [], {}, None, set()+ for line in lines:+ if line.startswith("[RUN]"):+ current, by_id = None, {}+ seen.clear()+ continue+ if line in seen:+ continue # overlapping rotated snapshots+ seen.add(line)+ match = MARKER.search(line)+ private_result = "Private provider post-processing complete" in line+ if not match and not private_result:+ if current and ("Cancel shortcut pressed" in line or "stopWithoutTranscription" in line):+ current["cancelled"] = True+ continue+ if private_result:+ family, body = "FI_RESULT", line.split("Private provider post-processing complete", 1)[1]+ else:+ family, body = match.groups()+ fields = dict(FIELD.findall(body))+ correlation = dict(FIELD.findall(line)).get("pipelineID")+ words = [part for part in body.split() if "=" not in part]+ name = "complete" if family == "FI_RESULT" else (+ " ".join(words) if family not in ("PIPELINE_SUMMARY", "DICTATION_SUMMARY") else "summary"+ )+ try:+ timestamp = float(fields["t"])+ except (KeyError, ValueError):+ timestamp = None+ event = {"family": family, "name": name, "t": timestamp,+ "pipeline_id": correlation,+ "fields": {k: v for k, v in fields.items() if k != "t"}}+ if family == "APP_BENCH" and name == "begin_recording":+ wall = WALL.match(line)+ current = {"id": None, "time": wall.group(1) if wall else "?",+ "events": [], "cancelled": False, "partial_start": False}+ runs.append(current)+ if family == "APP_BENCH" and name == "pipeline_begin":+ if current is None or current["id"] is not None:+ current = {"id": None, "time": WALL.match(line).group(1) if WALL.match(line) else "?",+ "events": [], "cancelled": False, "partial_start": True}+ runs.append(current)+ current["id"] = fields.get("id")+ current["correlated"] = correlation is not None+ if current["id"]:+ by_id[current["id"]] = current+ explicit_id = correlation or (fields.get("id") if family in (+ "APP_BENCH", "PIPELINE_SUMMARY", "LLM_BENCH") else None)+ if correlation and family in ("APP_BENCH", "PIPELINE_SUMMARY", "LLM_BENCH") and fields.get("id", correlation) != correlation:+ continue+ target = by_id.get(explicit_id) if explicit_id else current+ if target and target.get("correlated") and not explicit_id:+ # Unscoped work may belong to Local API or a previous recording.+ # Never use proximity as identity for modern stop-pipeline logs.+ continue+ if family == "FI_RESULT":+ # This provider log has no pipeline ID. Attach it only while the+ # current recording has an AI call that has not returned, so an+ # unrelated Local API request cannot contaminate a dictation.+ ai_names = [event["name"] for event in target["events"]] if target else []+ last_call = max((index for index, name in enumerate(ai_names) if name == "ai_process_call"), default=-1)+ last_return = max((index for index, name in enumerate(ai_names) if name == "ai_process_return"), default=-1)+ if not explicit_id and last_call <= last_return:+ continue+ # An unknown callback ID must not contaminate a newer recording.+ if fields.get("id") and family in ("APP_BENCH", "PIPELINE_SUMMARY") and name != "pipeline_begin":+ target = by_id.get(fields["id"])+ if target is not None:+ target["events"].append(event)+ return runs+++def summarize(run):+ events = run["events"]++ def find(family, names, after=None, last=False):+ matches = [e for e in events if e["family"] == family and e["name"] in names+ and not (e["name"] == "manager finish_hide_complete"+ and e["fields"].get("outcome") == "superseded")+ and e["t"] is not None and (after is None or e["t"] >= after)]+ return (matches[-1] if last else matches[0]) if matches else None++ def find_with_field(family, names, key, value, after=None):+ return next((e for e in events if e["family"] == family and e["name"] in names+ and e["fields"].get(key) == value and e["t"] is not None+ and (after is None or e["t"] >= after)), None)++ def find_untimed(family, names, after_index=0):+ return next((e for e in events[after_index:]+ if e["family"] == family and e["name"] in names), None)++ def time(event):+ return event["t"] if event else None++ def numeric_field(event, key):+ try:+ value = float(event["fields"][key]) if event else None+ return value if value is not None and math.isfinite(value) and value >= 0 else None+ except (KeyError, ValueError, TypeError):+ return None++ def delta(end, start):+ return round((end - start) * 1000, 1) if end is not None and start is not None else None++ start = time(find("APP_BENCH", {"begin_recording"}))+ stop = time(find("APP_BENCH", {"stop_path_enter"}))+ if stop is None:+ stop = time(find("APP_BENCH", {"pipeline_begin"}))+ # Do not accidentally match recording-stage events as completion events.+ after = stop if stop is not None else float("inf")+ phases = {+ "asr_stop_call": time(find("APP_BENCH", {"asr_stop_call"}, after)),+ "capture_stop_begin": time(find("ASR_BENCH", {"capture_stop_await_begin"}, after)),+ "capture_stop_return": time(find("ASR_BENCH", {"capture_stop_await_return"}, after)),+ "final_queue_ready": time(find("ASR_BENCH", {"final_queue_previous_finished"}, after)),+ "final_executor_begin": time(find("ASR_BENCH", {"final_executor_begin"}, after)),+ "final_executor_end": time(find("ASR_BENCH", {"final_executor_end"}, after)),+ "final_asr": time(find("ASR_BENCH", {"final_done"}, after)),+ "asr_return": time(find("APP_BENCH", {"asr_stop_return"}, after)),+ "refining_requested": time(find_with_field(+ "APP_BENCH", {"processing_ui_requested"}, "status", "Refining", after+ )),+ "ai_call": time(find("APP_BENCH", {"ai_process_call"}, after)),+ "ai_route_resolved": time(find("APP_BENCH", {"ai_route_resolved"}, after)),+ "ai_private_call": time(find("APP_BENCH", {"ai_private_call"}, after)),+ "ai_service_enter": time(find("FI_SERVICE_BENCH", {"enhance_enter"}, after)),+ "ai_service_call": time(find("FI_SERVICE_BENCH", {"provider_call"}, after)),+ "ai_adapter_call": time(find("FI_BRIDGE_BENCH", {"adapter_call"}, after)),+ "ai_bridge_enter": time(find("FI_BRIDGE_BENCH", {"enhance_enter"}, after)),+ "ai_bridge_validated": time(find("FI_BRIDGE_BENCH", {"validated"}, after)),+ "ai_bridge_client_ready": time(find("FI_BRIDGE_BENCH", {"client_ready"}, after)),+ "ai_model_call": time(find("FI_BRIDGE_BENCH", {"run_call"}, after)),+ "ai_model_return": time(find("FI_BRIDGE_BENCH", {"run_return"}, after)),+ "ai_bridge_return": time(find("FI_BRIDGE_BENCH", {"enhance_return"}, after)),+ "ai_adapter_return": time(find("FI_BRIDGE_BENCH", {"adapter_return"}, after)),+ "ai_service_return": time(find("FI_SERVICE_BENCH", {"provider_return"}, after)),+ "ai_private_return": time(find("APP_BENCH", {"ai_private_return"}, after)),+ "llm_call_enter": time(find("LLM_BENCH", {"call_enter"}, after)),+ "llm_request_built": time(find("LLM_BENCH", {"request_built"}, after)),+ "llm_attempt_start": time(find("LLM_BENCH", {"attempt_start"}, after)),+ "llm_response": time(find("LLM_BENCH", {"response_headers", "response_data"}, after)),+ "llm_first_content": time(find("LLM_BENCH", {"first_content"}, after)),+ "llm_response_decoded": time(find("LLM_BENCH", {"response_decoded"}, after)),+ "llm_call_return": time(find("LLM_BENCH", {"call_return"}, after)),+ "ai_return": time(find("APP_BENCH", {"ai_process_return"}, after)),+ "ai_failure": time(find("APP_BENCH", {"ai_process_fail"}, after)),+ "text_ready": time(find("APP_BENCH", {"text_ready"}, after)),+ "paste_dispatch": time(find("TYPING_BENCH", {"asr_type_dispatched"}, after)),+ "paste_done": time(find("TYPING_BENCH", {"complete"}, after)),+ "injection_return": time(find("TYPING_BENCH", {"insert_return"}, after)),+ "typing_request": time(find("TYPING_BENCH", {"request"}, after)),+ "typing_worker": time(find("TYPING_BENCH", {"worker_start"}, after)),+ "hide_request": time(find("OVERLAY_BENCH", {"manager finish_hide_request"}, after)),+ "alpha_return": time(find("OVERLAY_BENCH", {"bottom_hide_alpha_return"}, after)),+ "order_out_return": time(find("OVERLAY_BENCH", {"bottom_hide_order_out_return"}, after)),+ "hidden": time(find("OVERLAY_BENCH", {"manager finish_hide_complete"}, after)),+ "delivery_callback": time(find("TYPING_BENCH", {"delivery_main_begin"}, after)),+ "handler_return": time(find("APP_BENCH", {"pipeline_handler_return"}, after)),+ "cleanup": time(find("OVERLAY_BENCH", {"bottom_hide_immediate_cleanup_complete",+ "notch hide_immediate_cleanup_complete"}, after, last=True)),+ }+ final = find("ASR_BENCH", {"final_done"}, after)+ stop_event_index = next((index for index, event in enumerate(events)+ if event["t"] == stop and event["family"] == "APP_BENCH"), 0)+ provider_final = find_untimed("ASR_BENCH", {"provider_final_done"}, stop_event_index)+ private_results = [+ event for event in events[stop_event_index:]+ if event["family"] == "FI_RESULT" and event["name"] == "complete"+ ]+ # FI completion logs do not carry a pipeline ID. If another local request+ # finishes during this dictation, suppress the breakdown instead of+ # guessing which result belongs to the hotkey pipeline.+ private_result = private_results[0] if len(private_results) == 1 and private_results[0]["pipeline_id"] else None+ final_request = find("ASR_BENCH", {"final_executor_request"}, after)+ ai_call = find("APP_BENCH", {"ai_process_call"}, after)+ summary = find("PIPELINE_SUMMARY", {"summary"}, after)+ ready_summary = find_untimed("DICTATION_SUMMARY", {"summary"}, stop_event_index)+ if run["cancelled"]:+ outcome = "cancelled"+ elif summary:+ outcome = summary["fields"].get("outcome", "finished")+ elif ready_summary and ready_summary["fields"].get("outcome") == "asr_failed":+ outcome = "asr_failed"+ elif final and final["fields"].get("textChars") == "0" and phases["handler_return"] is not None:+ outcome = "empty"+ elif phases["paste_done"] is not None:+ outcome = "paste done; callback missing"+ else:+ outcome = "incomplete"+ tail = delta(phases["hidden"], phases["paste_done"])+ try:+ provider_final_ms = float(provider_final["fields"]["elapsedMs"]) if provider_final else None+ except (KeyError, ValueError):+ provider_final_ms = None+ fi_setup_ms = numeric_field(private_result, "setupMs")+ fi_request_ms = numeric_field(private_result, "requestMs")+ fi_model_ms = numeric_field(private_result, "totalMs")+ fi_prefill_ms = numeric_field(private_result, "prefillMs")+ fi_ttft_ms = numeric_field(private_result, "ttftMs")+ fi_decode_ms = numeric_field(private_result, "decodeMs")+ fi_return_ms = numeric_field(private_result, "returnMs")+ ai_processing_ms = delta(phases["ai_return"] if phases["ai_return"] is not None+ else phases["ai_failure"], phases["ai_call"])+ ai_route_ms = delta(phases["ai_route_resolved"], phases["ai_call"])+ fi_known_ms = [value for value in (fi_setup_ms, fi_request_ms, fi_return_ms) if value is not None]+ fi_remaining_handoff_ms = (+ round(ai_processing_ms - (ai_route_ms or 0) - sum(fi_known_ms), 1)+ if ai_processing_ms is not None and len(fi_known_ms) == 3+ else None+ )+ metrics = {+ "start_to_pcm_ms": delta(time(find("ASR_BENCH", {"first_audio"})), start),+ "start_to_overlay_ms": delta(time(find("OVERLAY_BENCH", {"bottom_visible", "bottom_order_front"})), start),+ "recording_ms": delta(stop, start),+ "hide_duration_ms": delta(phases["hidden"], phases["hide_request"]),+ "overlay_after_paste_ms": tail,+ "callback_queue_ms": delta(phases["delivery_callback"], phases["paste_done"]),+ "capture_stop_ms": delta(phases["capture_stop_return"], phases["capture_stop_begin"]),+ "final_executor_hop_ms": delta(phases["final_executor_begin"], phases["final_queue_ready"]),+ "final_executor_ms": delta(phases["final_executor_end"], phases["final_executor_begin"]),+ "asr_provider_ms": provider_final_ms,+ "asr_to_ai_call_ms": delta(phases["ai_call"], phases["asr_return"]),+ "refining_to_ai_call_ms": delta(phases["ai_call"], phases["refining_requested"]),+ "ai_route_ms": ai_route_ms,+ "ai_app_to_service_ms": delta(phases["ai_service_enter"], phases["ai_private_call"]),+ "ai_service_setup_ms": delta(phases["ai_service_call"], phases["ai_service_enter"]),+ "ai_service_to_adapter_ms": delta(phases["ai_adapter_call"], phases["ai_service_call"]),+ "ai_adapter_to_runtime_ms": delta(phases["ai_bridge_enter"], phases["ai_adapter_call"]),+ "ai_call_to_bridge_ms": delta(phases["ai_bridge_enter"], phases["ai_private_call"]),+ "ai_bridge_validate_ms": delta(phases["ai_bridge_validated"], phases["ai_bridge_enter"]),+ "ai_bridge_client_ms": delta(phases["ai_bridge_client_ready"], phases["ai_bridge_validated"]),+ "ai_bridge_request_ms": delta(phases["ai_model_call"], phases["ai_bridge_client_ready"]),+ "ai_bridge_setup_ms": delta(phases["ai_model_call"], phases["ai_bridge_enter"]),+ "ai_model_envelope_ms": delta(phases["ai_model_return"], phases["ai_model_call"]),+ "ai_bridge_tail_ms": delta(phases["ai_bridge_return"], phases["ai_model_return"]),+ "ai_runtime_to_adapter_ms": delta(phases["ai_adapter_return"], phases["ai_bridge_return"]),+ "ai_adapter_to_service_ms": delta(phases["ai_service_return"], phases["ai_adapter_return"]),+ "ai_service_to_app_ms": delta(phases["ai_private_return"], phases["ai_service_return"]),+ "ai_return_hop_ms": delta(phases["ai_private_return"], phases["ai_bridge_return"]),+ "fi_setup_ms": fi_setup_ms,+ "fi_request_ms": fi_request_ms,+ "fi_model_ms": fi_model_ms,+ "fi_prefill_ms": fi_prefill_ms,+ "fi_ttft_ms": fi_ttft_ms,+ "fi_decode_ms": fi_decode_ms,+ "fi_prompt_tokens": numeric_field(private_result, "promptTokens"),+ "fi_output_tokens": numeric_field(private_result, "outputTokens"),+ "fi_tokens_per_second": numeric_field(private_result, "tps"),+ "fi_return_ms": fi_return_ms,+ "fi_remaining_handoff_ms": fi_remaining_handoff_ms,+ "llm_setup_ms": delta(phases["llm_call_enter"], phases["ai_route_resolved"]),+ "llm_request_build_ms": delta(phases["llm_request_built"], phases["llm_call_enter"]),+ "llm_transport_to_response_ms": delta(phases["llm_response"], phases["llm_attempt_start"]),+ "llm_transport_to_first_content_ms": delta(+ phases["llm_first_content"]+ if phases["llm_first_content"] is not None+ else phases["llm_response"],+ phases["llm_attempt_start"],+ ),+ "llm_decode_tail_ms": delta(+ phases["llm_response_decoded"],+ phases["llm_first_content"]+ if phases["llm_first_content"] is not None+ else phases["llm_response"],+ ),+ "llm_return_hop_ms": delta(phases["ai_return"], phases["llm_call_return"]),+ "ai_processing_ms": ai_processing_ms,+ "ai_to_ready_ms": delta(phases["text_ready"], phases["ai_return"]),+ "internal_stop_to_ready_ms": delta(phases["text_ready"], stop),+ "typing_queue_ms": delta(phases["typing_worker"], phases["typing_request"]),+ "ready_to_injection_ms": delta(phases["injection_return"], phases["text_ready"]),+ "ready_to_delivery_ms": delta(phases["delivery_callback"], phases["text_ready"]),+ "stop_to_delivery_ms": numeric_field(summary, "totalMs"),+ "summary_asr_ms": numeric_field(ready_summary, "asrMs"),+ "summary_ai_ms": numeric_field(ready_summary, "aiMs"),+ "summary_app_overhead_ms": numeric_field(ready_summary, "appOverheadMs"),+ "summary_ready_ms": numeric_field(ready_summary, "readyMs"),+ }+ context = {+ "route": next((e["fields"].get("route") for e in events+ if e["family"] == "APP_BENCH" and e["name"] == "pipeline_begin"), None),+ "llm_attempt_count": sum(e["family"] == "LLM_BENCH" and e["name"] == "attempt_start" for e in events),+ "audio_ms": numeric_field(final, "audioMs"),+ "samples": numeric_field(final, "samples"),+ "text_chars": numeric_field(final, "textChars"),+ "asr_model": final_request["fields"].get("model") if final_request else None,+ "vocab_enabled": final_request["fields"].get("vocabEnabled") if final_request else None,+ "vocab_terms": numeric_field(final_request, "vocabTerms"),+ "ai_provider": ai_call["fields"].get("provider") if ai_call else None,+ "ai_model": ai_call["fields"].get("model") if ai_call else None,+ }+ return {"id": run["id"], "time": run["time"], "outcome": outcome,+ "ready_outcome": ready_summary["fields"].get("outcome") if ready_summary else None,+ "correlation": "request_id" if run.get("correlated") else "legacy_proximity_uncertain",+ "correctness": "not_checked_requires_expected_and_delivered_text",+ "partial_start": run["partial_start"], "stop_uptime": stop,+ "from_stop_ms": {key: delta(value, stop) for key, value in phases.items()},+ "metrics": metrics, "context": context, "events": events}+++def render(rows, details=False):+ def fmt(value):+ return "—" if value is None else f"{value:.1f}"++ lines = ["# Dictation evaluation", "",+ "Readiness is not delivery. Timing is not text-correctness proof.", "",+ "| Time / ID | Correlation | Ready result | Delivery result | ASR | AI | App overhead | Ready | Delivery |",+ "|---|---|---|---|---:|---:|---:|---:|---:|"]+ for row in rows:+ m = row["metrics"]+ values = [m["summary_asr_ms"], m["summary_ai_ms"], m["summary_app_overhead_ms"],+ m["summary_ready_ms"], m["stop_to_delivery_ms"]]+ lines.append(f"| {row['time']} / {(row['id'] or '?')[:8]} | {row['correlation']} | "+ f"{row['ready_outcome'] or 'unknown'} | {row['outcome']} | "+ + " | ".join(map(fmt, values)) + " |")+ lines += ["", "Legacy proximity metrics are exploratory, not authoritative overlap comparisons. "+ "FI breakdown requires a matching request ID. Correctness requires checking the actual delivered text.",+ "", "## Delivery and overlay", "",+ "Times in ms from stop-handler entry (not physical key-down). — = not logged / not applicable.",+ "Hidden = window API returned, not measured pixels. Paste = worker completed (including optional send-key wait), not target-app rendering.", "",+ "| Time / ID | Outcome | ASR | Ready | Paste | Hidden | Hide cost | Hidden − paste | Callback queue | Cleanup |",+ "|---|---|---:|---:|---:|---:|---:|---:|---:|---:|"]+ for row in rows:+ p, m = row["from_stop_ms"], row["metrics"]+ values = [p["asr_return"], p["text_ready"], p["paste_done"], p["hidden"],+ m["hide_duration_ms"], m["overlay_after_paste_ms"], m["callback_queue_ms"], p["cleanup"]]+ lines.append(f"| {row['time']} / {(row['id'] or '?')[:8]} | {row['outcome']} | " + " | ".join(map(fmt, values)) + " |")+ tails = [r["metrics"]["overlay_after_paste_ms"] for r in rows if r["metrics"]["overlay_after_paste_ms"] is not None]+ if tails:+ lines += ["", f"Overlay API returned after paste in {sum(t > 0 for t in tails)}/{len(tails)} measured runs. "+ f"Hidden − paste: median {statistics.median(tails):.1f} ms, worst {max(tails):.1f} ms "+ "(negative = hidden first)."]+ lines += ["", "Cleanup is the last logged overlay-cleanup marker, not proof all background work has finished.",+ "Unlabelled events are bounded by recording starts; rapid-overlap tails cannot be reliably attributed."]+ lines += ["", "## Internal model handoffs", "",+ "These exclude focus restoration, paste injection, and overlay dismissal.", "",+ "| Time / ID | Capture stop | ASR hop | ASR provider | ASR→AI | Refining→AI | AI process | AI→ready | Stop→ready |",+ "|---|---:|---:|---:|---:|---:|---:|---:|---:|"]+ for row in rows:+ m = row["metrics"]+ values = [m["capture_stop_ms"], m["final_executor_hop_ms"], m["asr_provider_ms"],+ m["asr_to_ai_call_ms"], m["refining_to_ai_call_ms"], m["ai_processing_ms"],+ m["ai_to_ready_ms"], m["internal_stop_to_ready_ms"]]+ lines.append(f"| {row['time']} / {(row['id'] or '?')[:8]} | " + " | ".join(map(fmt, values)) + " |")+ lines += ["", "ASR provider and AI process are measured model-call envelopes; all other columns are glue/handoff time."]+ if any(row["metrics"]["ai_model_envelope_ms"] is not None for row in rows):+ lines += ["", "## AI handoff detail", "",+ "| Time / ID | Route | Call→bridge | Bridge setup | FI run | Bridge tail | Return hop | AI total |",+ "|---|---:|---:|---:|---:|---:|---:|---:|"]+ for row in rows:+ m = row["metrics"]+ values = [m["ai_route_ms"], m["ai_call_to_bridge_ms"], m["ai_bridge_setup_ms"],+ m["ai_model_envelope_ms"], m["ai_bridge_tail_ms"], m["ai_return_hop_ms"],+ m["ai_processing_ms"]]+ lines.append(f"| {row['time']} / {(row['id'] or '?')[:8]} | " + " | ".join(map(fmt, values)) + " |")+ if any(row["metrics"]["ai_app_to_service_ms"] is not None for row in rows):+ lines += ["", "## FI actor and setup detail", "",+ "| Time / ID | App→service | Service setup | Service→adapter | Adapter→runtime | Validate | Cached client | Request | Runtime→adapter | Adapter→service | Service→app |",+ "|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|"]+ for row in rows:+ m = row["metrics"]+ values = [m["ai_app_to_service_ms"], m["ai_service_setup_ms"],+ m["ai_service_to_adapter_ms"], m["ai_adapter_to_runtime_ms"],+ m["ai_bridge_validate_ms"], m["ai_bridge_client_ms"],+ m["ai_bridge_request_ms"], m["ai_runtime_to_adapter_ms"],+ m["ai_adapter_to_service_ms"], m["ai_service_to_app_ms"]]+ lines.append(f"| {row['time']} / {(row['id'] or '?')[:8]} | " + " | ".join(map(fmt, values)) + " |")+ if any(row["metrics"]["fi_model_ms"] is not None for row in rows):+ lines += ["", "## Private FI handoff", "",+ "| Time / ID | Setup | Request | Model | Prefill | TTFT | Decode | Inside return | Remaining handoff | AI total |",+ "|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|"]+ for row in rows:+ m = row["metrics"]+ values = [m["fi_setup_ms"], m["fi_request_ms"], m["fi_model_ms"],+ m["fi_prefill_ms"], m["fi_ttft_ms"], m["fi_decode_ms"],+ m["fi_return_ms"], m["fi_remaining_handoff_ms"], m["ai_processing_ms"]]+ lines.append(f"| {row['time']} / {(row['id'] or '?')[:8]} | " + " | ".join(map(fmt, values)) + " |")+ if any(row["metrics"]["llm_request_build_ms"] is not None for row in rows):+ lines += ["", "## External AI handoff detail", "",+ "| Time / ID | Route→client | Request build | Transport→headers | Transport→first text | Decode tail | Return hop | AI total |",+ "|---|---:|---:|---:|---:|---:|---:|---:|"]+ for row in rows:+ m = row["metrics"]+ values = [m["llm_setup_ms"], m["llm_request_build_ms"],+ m["llm_transport_to_response_ms"], m["llm_transport_to_first_content_ms"],+ m["llm_decode_tail_ms"], m["llm_return_hop_ms"], m["ai_processing_ms"]]+ lines.append(f"| {row['time']} / {(row['id'] or '?')[:8]} | " + " | ".join(map(fmt, values)) + " |")+ if details:+ for row in rows:+ context = row["context"]+ lines += ["", f"## {row['time']} / {row['id'] or 'no pipeline ID'}", "",+ f"Start → first PCM: {fmt(row['metrics']['start_to_pcm_ms'])} ms; "+ f"start → overlay: {fmt(row['metrics']['start_to_overlay_ms'])} ms; "+ f"start → stop: {fmt(row['metrics']['recording_ms'])} ms.",+ f"Audio: {fmt(context['audio_ms'])} ms / {context['samples'] or '—'} samples; "+ f"ASR: {context['asr_model'] or '—'}; vocab: {context['vocab_enabled'] or '—'} "+ f"({context['vocab_terms'] if context['vocab_terms'] is not None else '—'} terms); "+ f"AI: {context['ai_provider'] or '—'} / {context['ai_model'] or '—'}; "+ f"text: {context['text_chars'] or '—'} chars.", "",+ "| From stop (ms) | Event | Fields |", "|---:|---|---|"]+ for e in row["events"]:+ relative = (e["t"] - row["stop_uptime"]) * 1000 if e["t"] is not None and row["stop_uptime"] is not None else None+ fields = " ".join(f"{k}={v}" for k, v in e["fields"].items()).replace("|", "\\|")+ lines.append(f"| {fmt(relative)} | {e['family']} {e['name']} | {fields} |")+ return "\n".join(lines)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--last", type=int, default=5, help="number of recent recordings (default: 5)")+ parser.add_argument("--log", type=Path, action="append", help="explicit log; repeat oldest first")+ parser.add_argument("--details", action="store_true", help="include every benchmark marker from start through tail")+ parser.add_argument("--json", action="store_true", help="machine-readable metrics and events")+ args = parser.parse_args()+ if args.last < 1:+ parser.error("--last must be positive")+ base = Path.home() / "Library/Logs/Fluid/Fluid.log"+ paths = args.log if args.log else [p for p in (base.with_name("Fluid.log.1"), base) if p.exists()]+ if not paths:+ parser.error("no FluidVoice logs found; supply --log PATH")+ try:+ # Read-only snapshots. The next invocation picks up any newly appended tail.+ lines = [line for path in paths for line in path.read_text(errors="replace").splitlines()]+ except OSError as error:+ parser.error(str(error))+ rows = [summarize(run) for run in parse_logs(lines)[-args.last:]]+ if not rows:+ parser.error("no recording/pipeline start markers found")+ print(json.dumps(rows, indent=2) if args.json else render(rows, args.details))+++if __name__ == "__main__":+ main()diff --git a/scripts/test_dictation_log_summary.py b/scripts/test_dictation_log_summary.pynew file mode 100644index 00000000..1dc88a94--- /dev/null+++ b/scripts/test_dictation_log_summary.py@@ -0,0 +1,257 @@+"""Regression fixtures; no app, microphone, or real log access."""++import unittest++from dictation_log_summary import parse_logs, render, summarize+++def row(family, t, event):+ return f"[12:00:00.000] [INFO] {family} t={t} {event}"+++class DictationLogSummaryTests(unittest.TestCase):+ def parse(self, *lines):+ return [summarize(run) for run in parse_logs(lines)]++ def test_paste_and_main_callback_are_distinct(self):+ result = self.parse(+ row("APP_BENCH", 1, "begin_recording"),+ row("ASR_BENCH", 1.1, "session=1 first_audio"),+ row("APP_BENCH", 2, "pipeline_begin id=A"),+ row("TYPING_BENCH", 2.2, "complete totalMs=16"),+ row("OVERLAY_BENCH", 2.18, "manager finish_hide_request"),+ row("OVERLAY_BENCH", 2.24, "manager finish_hide_complete"),+ row("TYPING_BENCH", 2.4, "delivery_main_begin"),+ row("PIPELINE_SUMMARY", 2.4, "id=A outcome=inserted"),+ )[0]+ self.assertEqual(result["from_stop_ms"]["paste_done"], 200)+ self.assertEqual(result["metrics"]["overlay_after_paste_ms"], 40)+ self.assertEqual(result["metrics"]["callback_queue_ms"], 200)+ self.assertEqual(result["metrics"]["hide_duration_ms"], 60)+ self.assertEqual(result["metrics"]["start_to_pcm_ms"], 100)++ def test_empty_run_never_inherits_paste(self):+ results = self.parse(+ row("APP_BENCH", 1, "begin_recording"),+ row("APP_BENCH", 2, "pipeline_begin id=A"),+ row("TYPING_BENCH", 2.1, "complete"),+ row("APP_BENCH", 3, "begin_recording"),+ row("APP_BENCH", 4, "pipeline_begin id=B"),+ row("ASR_BENCH", 4.1, "session=2 final_done textChars=0"),+ row("APP_BENCH", 4.2, "pipeline_handler_return id=B"),+ )+ self.assertEqual(results[1]["outcome"], "empty")+ self.assertIsNone(results[1]["from_stop_ms"]["paste_done"])++ def test_late_id_callback_routes_to_old_run(self):+ results = self.parse(+ row("APP_BENCH", 1, "begin_recording"),+ row("APP_BENCH", 2, "pipeline_begin id=A"),+ row("APP_BENCH", 3, "begin_recording"),+ row("PIPELINE_SUMMARY", 3.1, "id=A outcome=inserted"),+ row("OVERLAY_BENCH", 3.2, "manager finish_hide_complete"),+ row("APP_BENCH", 4, "pipeline_begin id=B"),+ )+ self.assertEqual(results[0]["outcome"], "inserted")+ self.assertEqual(results[1]["outcome"], "incomplete")+ self.assertIsNone(results[1]["from_stop_ms"]["hidden"])++ def test_rotation_duplicates_and_restart_are_isolated(self):+ begin = row("APP_BENCH", 1, "begin_recording")+ results = self.parse(begin, begin, row("APP_BENCH", 2, "pipeline_begin id=A"),+ "[RUN] PID=2", row("PIPELINE_SUMMARY", 3, "id=A outcome=inserted"),+ row("APP_BENCH", 4, "pipeline_begin id=B"))+ self.assertEqual(len(results), 2)+ self.assertEqual(results[0]["outcome"], "incomplete")+ self.assertTrue(results[1]["partial_start"])++ def test_incomplete_cancelled_and_untimed_markers(self):+ result = self.parse(row("APP_BENCH", 1, "begin_recording"),+ "ASR_BENCH provider_streaming_done elapsedMs=4",+ "Cancel shortcut pressed")[0]+ self.assertEqual(result["outcome"], "cancelled")+ self.assertIsNone(result["from_stop_ms"]["hidden"])+ self.assertIn("provider_streaming_done", render([result], details=True))++ def test_superseded_hide_is_not_reported_as_hidden(self):+ result = self.parse(row("APP_BENCH", 1, "begin_recording"),+ row("APP_BENCH", 2, "pipeline_begin id=A"),+ row("OVERLAY_BENCH", 2.1, "manager finish_hide_complete outcome=superseded"))[0]+ self.assertIsNone(result["from_stop_ms"]["hidden"])++ def test_internal_model_handoffs_and_context_are_separate(self):+ result = self.parse(+ row("APP_BENCH", 1, "begin_recording"),+ row("APP_BENCH", 2, "pipeline_begin id=A"),+ row("ASR_BENCH", 2.01, "session=4 capture_stop_await_begin"),+ row("ASR_BENCH", 2.05, "session=4 capture_stop_await_return"),+ row("ASR_BENCH", 2.06, "session=4 final_executor_request model=parakeet-v3 "+ "samples=80000 vocabEnabled=true vocabTerms=8"),+ row("ASR_BENCH", 2.061, "session=4 final_queue_previous_finished mainThread=false"),+ row("ASR_BENCH", 2.064, "final_executor_begin mainThread=true"),+ "ASR_BENCH provider_final_done samples=80000 audioMs=5000 elapsedMs=91 textChars=40",+ row("ASR_BENCH", 2.155, "final_executor_end"),+ row("ASR_BENCH", 2.16, "session=4 final_done samples=80000 audioMs=5000 textChars=40"),+ row("APP_BENCH", 2.162, "asr_stop_return elapsedMs=162"),+ row("APP_BENCH", 2.164, "processing_ui_requested status=Refining"),+ row("APP_BENCH", 2.165, "ai_process_call id=A provider=FluidIntelligence "+ "model=fluid-1 inputChars=40"),+ row("APP_BENCH", 2.365, "ai_process_return id=A"),+ row("APP_BENCH", 2.367, "text_ready chars=41"),+ )[0]++ self.assertEqual(result["metrics"]["capture_stop_ms"], 40)+ self.assertEqual(result["metrics"]["final_executor_hop_ms"], 3)+ self.assertEqual(result["metrics"]["asr_provider_ms"], 91)+ self.assertEqual(result["metrics"]["asr_to_ai_call_ms"], 3)+ self.assertEqual(result["metrics"]["refining_to_ai_call_ms"], 1)+ self.assertEqual(result["metrics"]["ai_processing_ms"], 200)+ self.assertEqual(result["metrics"]["ai_to_ready_ms"], 2)+ self.assertEqual(result["metrics"]["internal_stop_to_ready_ms"], 367)+ self.assertEqual(result["context"]["audio_ms"], 5000)+ self.assertEqual(result["context"]["samples"], 80000)+ self.assertEqual(result["context"]["asr_model"], "parakeet-v3")+ self.assertEqual(result["context"]["vocab_enabled"], "true")+ self.assertEqual(result["context"]["vocab_terms"], 8)+ self.assertEqual(result["context"]["ai_provider"], "FluidIntelligence")+ self.assertEqual(result["context"]["ai_model"], "fluid-1")++ def test_external_llm_handoff_breakdown(self):+ result = self.parse(+ row("APP_BENCH", 1, "begin_recording"),+ row("APP_BENCH", 2, "pipeline_begin id=A"),+ row("APP_BENCH", 2.100, "ai_process_call id=A provider=OpenAI model=gpt-5 inputChars=40"),+ row("APP_BENCH", 2.102, "ai_route_resolved elapsedMs=2"),+ row("LLM_BENCH", 2.105, "id=A call_enter"),+ row("LLM_BENCH", 2.106, "id=A request_built bodyBytes=900"),+ row("LLM_BENCH", 2.107, "id=A attempt_start attempt=1"),+ row("LLM_BENCH", 2.120, "id=A response_headers"),+ row("LLM_BENCH", 2.150, "id=A first_content"),+ row("LLM_BENCH", 2.170, "id=A response_decoded"),+ row("LLM_BENCH", 2.171, "id=A call_return"),+ row("APP_BENCH", 2.172, "ai_process_return id=A"),+ )[0]++ self.assertEqual(result["metrics"]["llm_setup_ms"], 3)+ self.assertEqual(result["metrics"]["llm_request_build_ms"], 1)+ self.assertEqual(result["metrics"]["llm_transport_to_response_ms"], 13)+ self.assertEqual(result["metrics"]["llm_transport_to_first_content_ms"], 43)+ self.assertEqual(result["metrics"]["llm_decode_tail_ms"], 20)+ self.assertEqual(result["metrics"]["llm_return_hop_ms"], 1)+ self.assertIn("External AI handoff detail", render([result]))++ def test_private_fi_summary_uses_low_overhead_completion_log(self):+ result = self.parse(+ row("APP_BENCH", 1, "begin_recording"),+ row("APP_BENCH", 2, "pipeline_begin id=A"),+ row("APP_BENCH", 2.100, "ai_process_call id=A provider=fluid-1 model=fluid-1 inputChars=40"),+ "[12:00:00.000] [INFO] [PrivateAIProvider] pipelineID=A Private provider post-processing complete "+ "backend=FluidDecode model=fluid-1 setupMs=1 requestMs=31 returnMs=0 totalMs=30 "+ "prefillMs=8 ttftMs=9 decodeMs=21",+ row("APP_BENCH", 2.140, "ai_process_return id=A"),+ )[0]++ self.assertEqual(result["metrics"]["fi_setup_ms"], 1)+ self.assertEqual(result["metrics"]["fi_request_ms"], 31)+ self.assertEqual(result["metrics"]["fi_model_ms"], 30)+ self.assertEqual(result["metrics"]["fi_prefill_ms"], 8)+ self.assertEqual(result["metrics"]["fi_ttft_ms"], 9)+ self.assertEqual(result["metrics"]["fi_decode_ms"], 21)+ self.assertEqual(result["metrics"]["fi_return_ms"], 0)+ self.assertEqual(result["metrics"]["fi_remaining_handoff_ms"], 8)+ rendered = render([result])+ self.assertIn("Private FI handoff", rendered)+ self.assertIn("| 1.0 | 31.0 | 30.0 | 8.0 | 9.0 | 21.0 |", rendered)++ def test_unrelated_private_api_result_does_not_attach_after_dictation_return(self):+ result = self.parse(+ row("APP_BENCH", 1, "begin_recording"),+ row("APP_BENCH", 2, "pipeline_begin id=A"),+ row("APP_BENCH", 2.100, "ai_process_call id=A provider=fluid-1 model=fluid-1 inputChars=40"),+ row("APP_BENCH", 2.140, "ai_process_return id=A"),+ "[12:00:01.000] [INFO] [PrivateAIProvider] Private provider post-processing complete "+ "backend=FluidDecode model=fluid-1 setupMs=1 requestMs=31 returnMs=0 totalMs=30",+ )[0]++ self.assertIsNone(result["metrics"]["fi_request_ms"])++ def test_request_ids_route_every_family_and_reject_unknown_requests(self):+ results = self.parse(+ row("APP_BENCH", 1, "pipeline_begin id=A pipelineID=A"),+ row("APP_BENCH", 2, "pipeline_begin id=B pipelineID=B"),+ "pipelineID=A TYPING_BENCH t=2.1 complete",+ "pipelineID=unknown LLM_BENCH t=2.2 call_enter",+ "TYPING_BENCH t=2.3 complete",+ "pipelineID=A DICTATION_SUMMARY asrMs=30 aiMs=-1 readyMs=50 appOverheadMs=20 outcome=success",+ )+ self.assertEqual(results[0]["from_stop_ms"]["paste_done"], 1100)+ self.assertIsNone(results[1]["from_stop_ms"]["paste_done"])+ self.assertIsNone(results[1]["from_stop_ms"]["llm_call_enter"])+ self.assertEqual(results[0]["ready_outcome"], "success")+ self.assertEqual(results[0]["outcome"], "paste done; callback missing")+ self.assertEqual(results[0]["metrics"]["summary_asr_ms"], 30)+ self.assertIsNone(results[0]["metrics"]["summary_ai_ms"])++ def test_single_unlabelled_fi_result_is_not_authoritative(self):+ result = self.parse(+ row("APP_BENCH", 1, "pipeline_begin id=A"),+ row("APP_BENCH", 1.1, "ai_process_call id=A"),+ "Private provider post-processing complete requestMs=30",+ row("APP_BENCH", 1.2, "ai_process_fail id=A"),+ )[0]+ self.assertIsNone(result["metrics"]["fi_request_ms"])+ self.assertEqual(result["metrics"]["ai_processing_ms"], 100)+ self.assertEqual(result["correlation"], "legacy_proximity_uncertain")++ def test_malformed_numbers_are_missing_not_zero_or_crashes(self):+ result = self.parse(+ row("APP_BENCH", 1, "pipeline_begin id=A"),+ row("ASR_BENCH", 1.1, "final_done samples=no audioMs=nan textChars=inf"),+ )[0]+ self.assertIsNone(result["context"]["samples"])+ self.assertIsNone(result["context"]["audio_ms"])+ self.assertIsNone(result["context"]["text_chars"])++ def test_terminal_outcomes_are_not_relabelled_as_external_insertion(self):+ for outcome in ("sandbox", "internal_editor", "insertedAndActionDispatched",+ "insertedActionSuppressed", "actionSuppressed", "rejected", "insertionFailed"):+ with self.subTest(outcome=outcome):+ result = self.parse(+ row("APP_BENCH", 1, "pipeline_begin id=A pipelineID=A"),+ f"pipelineID=A PIPELINE_SUMMARY t=1.1 id=A outcome={outcome} totalMs=100",+ )[0]+ self.assertEqual(result["outcome"], outcome)+ self.assertEqual(result["metrics"]["stop_to_delivery_ms"], 100)++ def test_asr_timeout_failure_is_not_empty_or_success(self):+ result = self.parse(+ row("APP_BENCH", 1, "pipeline_begin id=A pipelineID=A"),+ "pipelineID=A DICTATION_SUMMARY asrMs=-1 aiMs=-1 readyMs=30000 outcome=asr_failed",+ "pipelineID=A APP_BENCH t=31 pipeline_handler_return id=A",+ )[0]+ self.assertEqual(result["outcome"], "asr_failed")+ self.assertIsNone(result["metrics"]["summary_asr_ms"])+ self.assertIsNone(result["metrics"]["stop_to_delivery_ms"])++ def test_restart_does_not_deduplicate_a_new_recording_with_reused_values(self):+ begin = row("APP_BENCH", 1, "begin_recording")+ results = self.parse(begin, "[RUN] new process", begin)+ self.assertEqual(len(results), 2)++ def test_concurrent_private_results_are_not_misattributed_to_dictation(self):+ result = self.parse(+ row("APP_BENCH", 1, "begin_recording"),+ row("APP_BENCH", 2, "pipeline_begin id=A"),+ row("APP_BENCH", 2.100, "ai_process_call id=A provider=fluid-1 model=fluid-1 inputChars=40"),+ "[12:00:00.000] [INFO] [PrivateAIProvider] Private provider post-processing complete "+ "backend=FluidDecode model=fluid-1 setupMs=1 requestMs=31 returnMs=0 totalMs=30",+ "[12:00:00.010] [INFO] [PrivateAIProvider] Private provider post-processing complete "+ "backend=FluidDecode model=fluid-1 setupMs=1 requestMs=41 returnMs=0 totalMs=40",+ row("APP_BENCH", 2.150, "ai_process_return id=A"),+ )[0]++ self.assertIsNone(result["metrics"]["fi_request_ms"])+++if __name__ == "__main__":+ unittest.main()