Skip to content

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

feat(paste): add PasteDeliveryCoordinator and insertion analytics

altic-dev91b56a85e186
diff --cc Fluid.xcodeproj/project.pbxproj
index ac45b54b,88d9b881..c894752b
--- a/Fluid.xcodeproj/project.pbxproj
+++ b/Fluid.xcodeproj/project.pbxproj
@@@ -32,8 -29,7 +32,9 @@@
803000000000000000000003 /* MediaRemoteAdapter in Frameworks */ = {isa = PBXBuildFile; productRef = 803000000000000000000004 /* MediaRemoteAdapter */; };
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 */; };
+ FEED67600000000000000002 /* PasteDeliveryCoordinatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEED67600000000000000001 /* PasteDeliveryCoordinatorTests.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 */; };
@@@ -75,12 -71,9 +76,13 @@@
DA7100010000000000000001 /* DirectAudioReliabilityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectAudioReliabilityTests.swift; sourceTree = "<group>"; };
B51800000000000000000001 /* SpokenSendTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpokenSendTests.swift; sourceTree = "<group>"; };
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>"; };
+ FEED67600000000000000001 /* PasteDeliveryCoordinatorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PasteDeliveryCoordinatorTests.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>"; };
7CDB0A202F3C4D5600FB7CAD /* FluidDictationIntegrationTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = FluidDictationIntegrationTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
7CDB0A292F3C4D5600FB7CAD /* DictationE2ETests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DictationE2ETests.swift; sourceTree = "<group>"; };
CD1C7A0000000000000000B1 /* CustomDictionaryManualEntryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomDictionaryManualEntryTests.swift; sourceTree = "<group>"; };
@@@ -172,10 -163,7 +174,11 @@@
803000000000000000000001 /* MediaPlaybackServiceTests.swift */,
B51800000000000000000001 /* SpokenSendTests.swift */,
B51900000000000000000001 /* PrivateAIProviderPromptFormatTests.swift */,
+ B52000000000000000000001 /* PrivateAIDictationTokenBudgetTests.swift */,
+ C0DE63700000000000000001 /* WhisperLanguageSelectionTests.swift */,
+ CACEC0010000000000000001 /* KeychainServiceCacheTests.swift */,
+ 0B05F11E000000000000A001 /* SupportedFileExtensionsTests.swift */,
+ FEED67600000000000000001 /* PasteDeliveryCoordinatorTests.swift */,
);
path = FluidDictationIntegrationTests;
sourceTree = "<group>";
@@@ -349,9 -335,7 +352,10 @@@
803000000000000000000002 /* MediaPlaybackServiceTests.swift in Sources */,
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 */,
+ FEED67600000000000000002 /* PasteDeliveryCoordinatorTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
diff --cc Sources/Fluid/Analytics/AnalyticsDatabase.swift
index fe17f133,74240368..c8f50e86
--- a/Sources/Fluid/Analytics/AnalyticsDatabase.swift
+++ b/Sources/Fluid/Analytics/AnalyticsDatabase.swift
@@@ -124,35 -111,72 +124,101 @@@ 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 recordInsertionLatency(
+ path: AnalyticsInsertionPath,
+ outcome: AnalyticsInsertionOutcome,
+ requestMilliseconds: Int,
+ readyMilliseconds: Int?,
+ toggleStopMilliseconds: Int? = nil,
+ at date: Date
+ ) throws {
+ try self.finalizeDays(before: date)
+ let requestMilliseconds = max(0, requestMilliseconds)
+ let readyMilliseconds = readyMilliseconds.map { max(0, $0) }
+ let readyCount = readyMilliseconds == nil ? 0 : 1
+ let readyValue = readyMilliseconds ?? 0
+ let day = self.dayString(date)
+
+ try self.transaction {
+ try self.run(
+ "INSERT INTO daily_insertion_latency (" +
+ "day, delivery_path, outcome, request_count, request_total_ms, request_min_ms, request_max_ms, " +
+ "ready_count, ready_total_ms, ready_min_ms, ready_max_ms" +
+ ") VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?) " +
+ "ON CONFLICT(day, delivery_path, outcome) DO UPDATE SET " +
+ "request_count = request_count + 1, " +
+ "request_total_ms = request_total_ms + excluded.request_total_ms, " +
+ "request_min_ms = MIN(request_min_ms, excluded.request_min_ms), " +
+ "request_max_ms = MAX(request_max_ms, excluded.request_max_ms), " +
+ "ready_count = ready_count + excluded.ready_count, " +
+ "ready_total_ms = ready_total_ms + excluded.ready_total_ms, " +
+ "ready_min_ms = CASE " +
+ "WHEN excluded.ready_count = 0 THEN ready_min_ms " +
+ "WHEN ready_count = 0 THEN excluded.ready_min_ms " +
+ "ELSE MIN(ready_min_ms, excluded.ready_min_ms) END, " +
+ "ready_max_ms = CASE " +
+ "WHEN excluded.ready_count = 0 THEN ready_max_ms " +
+ "WHEN ready_count = 0 THEN excluded.ready_max_ms " +
+ "ELSE MAX(ready_max_ms, excluded.ready_max_ms) END",
+ bindings: [
+ .text(day), .text(path.rawValue), .text(outcome.rawValue),
+ .integer(requestMilliseconds), .integer(requestMilliseconds), .integer(requestMilliseconds),
+ .integer(readyCount), .integer(readyValue), .integer(readyValue), .integer(readyValue),
+ ]
+ )
+
+ if let toggleStopMilliseconds,
+ outcome == .dispatched,
+ path == .clipboard || path == .clipboardFallback
+ {
+ let milliseconds = max(0, toggleStopMilliseconds)
+ try self.run(
+ "INSERT INTO daily_clipboard_toggle_latency " +
+ "(day, delivery_path, sample_count, total_ms, min_ms, max_ms) " +
+ "VALUES (?, ?, 1, ?, ?, ?) " +
+ "ON CONFLICT(day, delivery_path) DO UPDATE SET " +
+ "sample_count = sample_count + 1, " +
+ "total_ms = total_ms + excluded.total_ms, " +
+ "min_ms = MIN(min_ms, excluded.min_ms), " +
+ "max_ms = MAX(max_ms, excluded.max_ms)",
+ bindings: [
+ .text(day), .text(path.rawValue),
+ .integer(milliseconds), .integer(milliseconds), .integer(milliseconds),
+ ]
+ )
+ }
+ }
+ }
+
func recordOnboardingStarted(origin: AnalyticsOnboardingOrigin, at date: Date) throws {
try self.finalizeDays(before: date)
try self.transaction {
@@@ -404,14 -339,20 +470,28 @@@
"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 || !performanceRows.isEmpty else { return }
+ let insertionRows = try self.query(
+ "SELECT day, delivery_path, outcome, request_count, request_total_ms, request_min_ms, " +
+ "request_max_ms, ready_count, ready_total_ms, ready_min_ms, ready_max_ms " +
+ "FROM daily_insertion_latency WHERE day < ? ORDER BY day, delivery_path, outcome",
+ bindings: [.text(today)]
+ )
+ let clipboardToggleRows = try self.query(
+ "SELECT day, delivery_path, sample_count, total_ms, min_ms, max_ms " +
+ "FROM daily_clipboard_toggle_latency WHERE day < ? ORDER BY day, delivery_path",
+ bindings: [.text(today)]
+ )
+
- guard !usageRows.isEmpty || !modelRows.isEmpty || !insertionRows.isEmpty || !clipboardToggleRows.isEmpty
++ guard !usageRows.isEmpty || !modelRows.isEmpty || !performanceRows.isEmpty ||
++ !insertionRows.isEmpty || !clipboardToggleRows.isEmpty
+ else { return }
try self.transaction {
for row in usageRows where row.count == 5 {
try self.enqueue(.usageDailySummary, at: date, properties: [
@@@ -432,12 -373,49 +512,53 @@@
"use_count": Int(row[5]) ?? 0,
])
}
+ for summary in self.performanceSummaries(from: performanceRows) {
+ try self.enqueue(.dictationPerformanceDailySummary, at: date, properties: summary.properties)
+ }
+ for row in insertionRows where row.count == 11 {
+ let requestCount = Int(row[3]) ?? 0
+ let requestTotal = Int(row[4]) ?? 0
+ let readyCount = Int(row[7]) ?? 0
+ let readyTotal = Int(row[8]) ?? 0
+ let toggleRow = clipboardToggleRows.first {
+ $0.count == 6 &&
+ row[2] == AnalyticsInsertionOutcome.dispatched.rawValue &&
+ $0[0] == row[0] &&
+ $0[1] == row[1]
+ }
+ var properties: [String: Any] = [
+ "latency_date": row[0],
+ "delivery_path": row[1],
+ "outcome": row[2],
+ "request_count": requestCount,
+ "request_total_ms": requestTotal,
+ "request_average_ms": Self.average(total: requestTotal, count: requestCount),
+ "request_min_ms": Int(row[5]) ?? 0,
+ "request_max_ms": Int(row[6]) ?? 0,
+ "ready_count": readyCount,
+ ]
+ if readyCount > 0 {
+ properties["ready_total_ms"] = readyTotal
+ properties["ready_average_ms"] = Self.average(total: readyTotal, count: readyCount)
+ properties["ready_min_ms"] = Int(row[9]) ?? 0
+ properties["ready_max_ms"] = Int(row[10]) ?? 0
+ }
+ if let toggleRow {
+ let count = Int(toggleRow[2]) ?? 0
+ let total = Int(toggleRow[3]) ?? 0
+ properties["toggle_stop_to_dispatch_count"] = count
+ properties["toggle_stop_to_dispatch_total_ms"] = total
+ properties["toggle_stop_to_dispatch_average_ms"] = Self.average(total: total, count: count)
+ properties["toggle_stop_to_dispatch_min_ms"] = Int(toggleRow[4]) ?? 0
+ properties["toggle_stop_to_dispatch_max_ms"] = Int(toggleRow[5]) ?? 0
+ }
+ try self.enqueue(.insertionLatencyDailySummary, at: date, properties: properties)
+ }
try self.run("DELETE FROM daily_usage WHERE day < ?", bindings: [.text(today)])
try self.run("DELETE FROM daily_model_usage WHERE day < ?", bindings: [.text(today)])
+ try self.run("DELETE FROM daily_insertion_latency WHERE day < ?", bindings: [.text(today)])
+ try self.run("DELETE FROM daily_clipboard_toggle_latency WHERE day < ?", bindings: [.text(today)])
+ try self.run("DELETE FROM daily_dictation_performance WHERE day < ?", bindings: [.text(today)])
}
}
@@@ -517,32 -483,10 +638,36 @@@
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 daily_insertion_latency")
+ try self.execute("DELETE FROM daily_clipboard_toggle_latency")
try self.execute("DELETE FROM event_dedupe")
try self.execute("DELETE FROM onboarding_flows")
+ try self.execute("DELETE FROM onboarding_tryout_state")
+ try self.execute("DELETE FROM model_download_attempts")
+ }
+ try self.purgeDeletedPages()
+ }
+
+ /// Removes detailed analytics while preserving the daily active-user signal and its dedupe key.
+ func purgeDetailedAnalytics() throws {
+ try self.transaction {
+ try self.run(
+ "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")
++ try self.execute("DELETE FROM daily_insertion_latency")
++ try self.execute("DELETE FROM daily_clipboard_toggle_latency")
+ try self.run(
+ "DELETE FROM event_dedupe WHERE dedupe_key NOT LIKE ?",
+ bindings: [.text("activity:%")]
+ )
+ try self.execute("DELETE FROM onboarding_flows")
try self.execute("DELETE FROM model_download_attempts")
}
try self.purgeDeletedPages()
@@@ -575,15 -519,29 +700,38 @@@
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 daily_insertion_latency (
+ day TEXT NOT NULL,
+ delivery_path TEXT NOT NULL,
+ outcome TEXT NOT NULL,
+ request_count INTEGER NOT NULL DEFAULT 0,
+ request_total_ms INTEGER NOT NULL DEFAULT 0,
+ request_min_ms INTEGER NOT NULL DEFAULT 0,
+ request_max_ms INTEGER NOT NULL DEFAULT 0,
+ ready_count INTEGER NOT NULL DEFAULT 0,
+ ready_total_ms INTEGER NOT NULL DEFAULT 0,
+ ready_min_ms INTEGER NOT NULL DEFAULT 0,
+ ready_max_ms INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY(day, delivery_path, outcome)
+ );
+ CREATE TABLE IF NOT EXISTS daily_clipboard_toggle_latency (
+ day TEXT NOT NULL,
+ delivery_path TEXT NOT NULL,
+ sample_count INTEGER NOT NULL DEFAULT 0,
+ total_ms INTEGER NOT NULL DEFAULT 0,
+ min_ms INTEGER NOT NULL DEFAULT 0,
+ max_ms INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY(day, delivery_path)
+ );
CREATE TABLE IF NOT EXISTS event_dedupe (
dedupe_key TEXT PRIMARY KEY,
created_at REAL NOT NULL
diff --cc Sources/Fluid/Analytics/AnalyticsService.swift
index 1656f3eb,dfaa28f2..718d1dc2
--- a/Sources/Fluid/Analytics/AnalyticsService.swift
+++ b/Sources/Fluid/Analytics/AnalyticsService.swift
@@@ -63,20 -60,25 +63,39 @@@ 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 recordInsertionLatency(
+ path: AnalyticsInsertionPath,
+ outcome: AnalyticsInsertionOutcome,
+ requestMilliseconds: Int,
+ readyMilliseconds: Int?,
+ toggleStopMilliseconds: Int?
+ ) {
+ self.submit { core, context in
+ await core.recordInsertionLatency(
+ path: path,
+ outcome: outcome,
+ requestMilliseconds: requestMilliseconds,
+ readyMilliseconds: readyMilliseconds,
+ toggleStopMilliseconds: toggleStopMilliseconds,
+ context: context
+ )
+ }
+ }
+
func recordOnboardingStarted(origin: AnalyticsOnboardingOrigin) {
self.submit { core, context in
await core.recordOnboardingStarted(origin: origin, context: context)
@@@ -318,30 -270,28 +337,50 @@@ 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 recordInsertionLatency(
+ path: AnalyticsInsertionPath,
+ outcome: AnalyticsInsertionOutcome,
+ requestMilliseconds: Int,
+ readyMilliseconds: Int?,
+ toggleStopMilliseconds: Int?,
+ context: AnalyticsContext
+ ) async {
- await self.write(context: context) { database, date in
++ await self.writeDetailed(context: context) { database, date in
+ try database.recordInsertionLatency(
+ path: path,
+ outcome: outcome,
+ requestMilliseconds: requestMilliseconds,
+ readyMilliseconds: readyMilliseconds,
+ toggleStopMilliseconds: toggleStopMilliseconds,
+ at: date
+ )
+ }
+ }
+
func recordOnboardingStarted(origin: AnalyticsOnboardingOrigin, context: AnalyticsContext) async {
- await self.write(context: context) { database, date in
+ await self.writeDetailed(context: context, fallbackActivity: .app) { database, date in
try database.recordOnboardingStarted(origin: origin, at: date)
}
}
diff --cc Sources/Fluid/ContentView.swift
index d1cd30a8,b9c88319..96d487f1
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@@ -2551,23 -2092,13 +2557,23 @@@ struct ContentView: View
// MARK: - Stop and Process Transcription
- private func stopAndProcessTranscription(route: DictationOutputRoute = .normal) async {
- private func stopAndProcessTranscription(
- route: DictationOutputRoute = .normal,
- toggleStopRequestedAt: TimeInterval? = nil
- ) async {
- DebugLogger.shared.debug("stopAndProcessTranscription called", source: "ContentView")
++ private func stopAndProcessTranscription(route: DictationOutputRoute = .normal, toggleStopRequestedAt: TimeInterval? = nil) async {
+ let pipelineID = UUID().uuidString
+ await DebugLogger.$pipelineID.withValue(pipelineID) {
- await self.processStoppedTranscription(route: route, pipelineID: pipelineID)
++ await self.processStoppedTranscription(route: route, pipelineID: pipelineID, toggleStopRequestedAt: toggleStopRequestedAt)
+ }
+ }
+
- private func processStoppedTranscription(route: DictationOutputRoute, pipelineID: String) async {
++ private func processStoppedTranscription(route: DictationOutputRoute, pipelineID: String, toggleStopRequestedAt: TimeInterval?) 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
// Check if we're in rewrite or command mode
let modeAtStop = self.activeRecordingMode
@@@ -2875,14 -2421,13 +2880,10 @@@
!sendsExistingDraft &&
SettingsStore.shared.copyTranscriptionToClipboard &&
!isFluidFrontmost
-
- if shouldCopyToClipboard {
- ClipboardService.copyToClipboard(finalText)
- }
+ let shouldTypeExternally = shouldPersistOutputs && !isFluidFrontmost
- if shouldCopyToClipboard, !shouldTypeExternally {
- ClipboardService.copyToClipboard(finalText)
- }
var didTypeExternally = false
- var didScheduleOverlayHideAfterDelivery = false
- let shouldTypeExternally = shouldPersistOutputs && !isFluidFrontmost
+ var didFailTextDelivery = false
DebugLogger.shared.debug(
"Typing decision → frontmost: \(frontmostName), fluidFrontmost: \(isFluidFrontmost), editorFocused: \(self.isTranscriptionFocused), willTypeExternally: \(shouldTypeExternally)",
@@@ -2916,38 -2468,29 +2924,47 @@@
let deliveryOutcome = await self.deliverSpokenSend(
finalOutputPlan,
targetPID: typingTarget.pid,
- textReadyAt: finalTextReadyAt
+ textReadyAt: finalTextReadyAt,
+ toggleStopRequestedAt: toggleStopRequestedAt,
+ preserveTranscriptOnClipboard: shouldCopyToClipboard
)
+ self.logPipelineCompletion(
+ outcome: String(describing: deliveryOutcome),
+ pipelineID: pipelineID,
+ pipelineStartedAt: pipelineStartedAt,
+ textReadyAt: finalTextReadyAt
+ )
didTypeExternally = deliveryOutcome.didInsert
+ deliveryResult = deliveryOutcome.didInsert || deliveryOutcome.didDispatchAction
+ ? .commandPosted
+ : .recoverableFailure(.pasteCommandFailed)
} else {
- let shouldHideOverlayAfterDelivery = !shouldShowAIProcessingFailure
- && !stopOverlay.didRequestHide
- self.asr.typeOutputPlanToActiveField(
+ self.appBench(
+ "text_ready_to_type_request elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - finalTextReadyAt) * 1000).rounded()))"
+ )
+ deliveryResult = await self.asr.typeOutputPlanToActiveField(
finalOutputPlan,
preferredTargetPID: typingTarget.pid,
textReadyAt: finalTextReadyAt,
+ toggleStopRequestedAt: toggleStopRequestedAt,
tracksDictionaryCorrections: true,
- completion: { outcome in
- self.handleTypingDelivery(
- outcome,
- pipelineID: pipelineID,
- pipelineStartedAt: pipelineStartedAt,
- textReadyAt: finalTextReadyAt,
- shouldHideOverlay: shouldHideOverlayAfterDelivery && spokenSendRequested,
- expectedOverlayLifecycleID: expectedOverlayLifecycleID
- )
- }
+ preserveTranscriptOnClipboard: shouldCopyToClipboard
+ )
+ didTypeExternally = deliveryResult.wasDispatched
++ self.handleTypingDelivery(
++ deliveryResult.wasDispatched ? .inserted : .insertionFailed,
++ pipelineID: pipelineID,
++ pipelineStartedAt: pipelineStartedAt,
++ textReadyAt: finalTextReadyAt,
++ shouldHideOverlay: deliveryResult.wasDispatched && !shouldShowAIProcessingFailure && !stopOverlay.didRequestHide && !spokenSendRequested,
++ expectedOverlayLifecycleID: expectedOverlayLifecycleID
+ )
- self.hideOverlayForDispatchedPaste(shouldHide: shouldHideOverlayAfterDelivery && !spokenSendRequested, lifecycleID: expectedOverlayLifecycleID)
- didScheduleOverlayHideAfterDelivery = shouldHideOverlayAfterDelivery
- didTypeExternally = true
+ }
+
++ guard self.overlayLifecycleID == expectedOverlayLifecycleID else {
++ self.appBench("delivery_ui_skipped reason=stale_recording")
++ return
+ }
if spokenSendRequested, !spokenSendAllowed {
NotchContentState.shared.setSpokenSendIndicatorState(.failed)
DebugLogger.shared.warning(
@@@ -2959,234 -2502,24 +2976,243 @@@
try? await Task.sleep(nanoseconds: 650_000_000)
}
}
- NotchOverlayManager.shared.updateTranscriptionText("")
++ guard self.overlayLifecycleID == expectedOverlayLifecycleID else { return }
NotchContentState.shared.setSpokenSendIndicatorState(.hidden)
- if !shouldShowAIProcessingFailure,
- !stopOverlay.didRequestHide,
- !didScheduleOverlayHideAfterDelivery
- {
- NotchOverlayManager.shared.updateTranscriptionText("")
+
+ if case let .recoverableFailure(failure) = deliveryResult {
+ didFailTextDelivery = true
+ self.showTextDeliveryFailure(failure, transcript: finalText)
- } else if !shouldShowAIProcessingFailure, !didRequestOverlayHideOnStop {
++ } else if !shouldShowAIProcessingFailure, !stopOverlay.didRequestHide {
self.hideOverlayAfterOutput()
}
++ // Delivery UI must complete before correction tracking queries Accessibility.
++ if didTypeExternally, !spokenSendAllowed {
++ AutomaticDictionaryCorrectionTracker.shared.beginObservingInsertion(
++ finalOutputPlan.plainText,
++ targetPID: typingTarget.pid
++ )
++ self.appBench("dictionary_tracking_scheduled afterDeliveryUI=true")
++ }
}
- if !didTypeExternally,
- !shouldShowAIProcessingFailure,
- !didFailTextDelivery,
- !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 {
++ if !didTypeExternally, !shouldShowAIProcessingFailure, !didFailTextDelivery, !stopOverlay.didRequestHide {
self.hideOverlayAfterOutput()
}
+ if !shouldTypeExternally {
+ self.logPipelineCompletion(
+ outcome: shouldPersistOutputs ? "internal_editor" : "sandbox",
+ pipelineID: pipelineID,
+ pipelineStartedAt: pipelineStartedAt,
+ textReadyAt: finalTextReadyAt
+ )
+ }
+ }
+
+ private func processDictationPromptTest(_ transcribedText: String, lifecycleID: UInt64) 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."
+ if self.overlayLifecycleID == lifecycleID {
+ self.menuBarManager.setProcessing(false)
+ }
+ return
+ }
+ promptTest.isProcessing = true
+ let refiningStatusTask = self.makeAIProcessingFeedback(lifecycleID: lifecycleID).statusTask
+ defer {
+ refiningStatusTask.cancel()
+ if self.overlayLifecycleID == lifecycleID {
+ 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() {
@@@ -3200,6 -2533,62 +3226,54 @@@
NotchContentState.shared.setSpokenSendIndicatorState(shouldSend ? .detected : .hidden)
}
+ private func showTextDeliveryFailure(_ failure: TextDeliveryFailure, transcript: String) {
- let message = switch failure {
- case .emptyText:
- "There was no text to insert"
- case .accessibilityNotTrusted:
- "Enable Accessibility to insert text"
- case .targetUnavailable, .targetRestoreFailed:
- "Could not restore the target text field"
- case .clipboardSnapshotFailed:
- "Clipboard contents could not be preserved exactly"
- case .clipboardWriteFailed:
- "Could not prepare the clipboard"
- case .pasteCommandFailed:
- "Could not send the paste command"
- }
- NotchContentState.shared.showTextDeliveryFailure(message: message, transcript: transcript)
++ let failure = failure != .emptyText && !AXIsProcessTrusted() ? TextDeliveryFailure.accessibilityNotTrusted : failure
++ DebugLogger.shared.warning("Text delivery failed: \(failure.rawValue)", source: "ContentView")
++ NotchContentState.shared.recordTextDeliveryFailure(failure, transcript: transcript)
++ guard failure.userFacingMessage != nil else {
++ self.hideOverlayAfterOutput()
++ return
++ }
+ self.menuBarManager.finishProcessingKeepingOverlayVisible()
+ }
+
+ private func showPrivateAIEditModeUnavailableIfNeeded() -> Bool {
+ let settings = SettingsStore.shared
+ let providerID = settings.rewriteModeLinkedToGlobal
+ ? settings.selectedProviderID
+ : settings.rewriteModeSelectedProviderID
+ guard PrivateFeatures.privateAIProvider,
+ providerID.trimmingCharacters(in: .whitespacesAndNewlines) ==
+ PrivateAIProviderFeature.shared.providerID
+ else {
+ return false
+ }
+
+ guard !self.asr.isRunningOrStarting,
+ !NotchContentState.shared.isProcessing
+ else {
+ return true
+ }
+
+ self.menuBarManager.setOverlayMode(.edit)
+ self.advanceOverlayLifecycle()
+ let expectedOverlayLifecycleID = self.overlayLifecycleID
+ self.menuBarManager.showRecordingOverlayImmediately()
+ NotchContentState.shared.showAIProcessingFailure(
+ message: "Edit Mode cannot be used with Fluid-1",
+ canRetry: false
+ )
+ self.menuBarManager.finishProcessingKeepingOverlayVisible()
+
+ Task { @MainActor in
+ try? await Task.sleep(nanoseconds: 6_000_000_000)
+ guard self.overlayLifecycleID == expectedOverlayLifecycleID else { return }
+ NotchContentState.shared.clearAIProcessingFailure()
+ await self.menuBarManager.finishProcessingAndHideOverlay()
+ }
+ return true
+ }
+
private func advanceOverlayLifecycle() {
self.spokenSendAutoStopTask?.cancel()
self.spokenSendAutoStopTask = nil
@@@ -3749,23 -3160,25 +3861,33 @@@
if shouldTypeExternally {
let typingTarget = self.resolveTypingTargetPID()
if typingTarget.shouldRestoreOriginalFocus {
- await self.restoreFocusToRecordingTarget()
+ guard await self.restoreFocusToRecordingTarget() else {
+ self.showTextDeliveryFailure(.targetRestoreFailed, transcript: finalText)
+ return
+ }
}
- self.asr.typeOutputPlanToActiveField(
+ let result = await self.asr.typeOutputPlanToActiveField(
outputPlan,
- preferredTargetPID: typingTarget.pid
+ preferredTargetPID: typingTarget.pid,
+ preserveTranscriptOnClipboard: SettingsStore.shared.copyTranscriptionToClipboard
)
+ if case let .recoverableFailure(failure) = result {
+ self.showTextDeliveryFailure(failure, transcript: finalText)
+ return
+ }
+ } else if SettingsStore.shared.copyTranscriptionToClipboard {
+ ClipboardService.copyToClipboard(finalText)
}
- 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()
}
diff --cc Sources/Fluid/Services/PasteDeliveryCoordinator.swift
index 00000000,6974955d..15ca8918
mode 000000,100644..100644
--- a/Sources/Fluid/Services/PasteDeliveryCoordinator.swift
+++ b/Sources/Fluid/Services/PasteDeliveryCoordinator.swift
@@@ -1,0 -1,712 +1,689 @@@
+ import AppKit
+ import Carbon
+ import Foundation
+ import UniformTypeIdentifiers
+
+ enum TextDeliveryFailure: String, Equatable {
+ case emptyText = "empty_text"
+ case accessibilityNotTrusted = "accessibility_not_trusted"
+ case clipboardSnapshotFailed = "clipboard_snapshot_failed"
+ case clipboardWriteFailed = "clipboard_write_failed"
+ case pasteCommandFailed = "paste_command_failed"
+ case targetUnavailable = "target_unavailable"
+ case targetRestoreFailed = "target_restore_failed"
++
++ var userFacingMessage: String? {
++ switch self {
++ case .accessibilityNotTrusted:
++ "Enable Accessibility to insert text"
++ case .emptyText, .clipboardSnapshotFailed, .clipboardWriteFailed,
++ .pasteCommandFailed, .targetUnavailable, .targetRestoreFailed:
++ nil
++ }
++ }
+ }
+
+ enum TextDeliveryResult: Equatable {
+ case commandPosted
+ case recoverableFailure(TextDeliveryFailure)
+
+ var wasDispatched: Bool {
+ self == .commandPosted
+ }
+ }
+
+ struct PasteboardSnapshot: Equatable {
+ struct Item: Equatable {
+ struct Representation: Equatable {
+ let type: NSPasteboard.PasteboardType
+ let data: Data
+ }
+
+ /// AppKit uses source order as representation preference, so this must remain ordered.
+ let representations: [Representation]
+ /// Materialized while the original owner still provides file access or promised image data.
+ let portableImage: Representation?
+
+ init(representations: [Representation], portableImage: Representation? = nil) {
+ self.representations = representations
+ self.portableImage = portableImage
+ }
+ }
+
+ let items: [Item]
+ }
+
+ @MainActor
+ protocol PasteboardManaging: AnyObject {
+ func captureSnapshot() -> PasteboardSnapshot?
+ func writeTemporaryText(_ text: String, sessionID: String) -> Bool
+ func writeIntentionalText(_ text: String) -> Bool
+ func isOwned(sessionID: String, expectedText: String) -> Bool
+ func restore(_ snapshot: PasteboardSnapshot) -> Bool
++ func restoreTemporarySnapshot(_ snapshot: PasteboardSnapshot, sessionID: String, expectedText: String) -> Bool
+ }
+
+ @MainActor
+ protocol PasteCommandPosting: AnyObject {
+ func postGlobalPasteCommand() async -> Bool
+ }
+
+ @MainActor
+ final class SystemPasteboardManager: PasteboardManaging {
+ private static let sourceType = NSPasteboard.PasteboardType("org.nspasteboard.source")
+ private static let transientType = NSPasteboard.PasteboardType("org.nspasteboard.TransientType")
+ private static let autoGeneratedType = NSPasteboard.PasteboardType("org.nspasteboard.AutoGeneratedType")
+ private static let sessionType = NSPasteboard.PasteboardType(
+ "\(Bundle.main.bundleIdentifier ?? "com.FluidApp.Fluid").PasteSession"
+ )
+ private static let fileSemanticTypes: Set<NSPasteboard.PasteboardType> = [
+ .fileURL,
+ NSPasteboard.PasteboardType("NSFilenamesPboardType"),
+ NSPasteboard.PasteboardType("com.apple.pasteboard.promised-file-url"),
+ NSPasteboard.PasteboardType("com.apple.pasteboard.promised-file-content-type"),
+ NSPasteboard.PasteboardType("com.apple.filepromise"),
+ ]
+
+ private let pasteboard: NSPasteboard
++ private var temporaryWrite: (sessionID: String, changeCount: Int)?
+
+ init(pasteboard: NSPasteboard = .general) {
+ self.pasteboard = pasteboard
+ }
+
+ func captureSnapshot() -> PasteboardSnapshot? {
+ let startedAt = ProcessInfo.processInfo.systemUptime
+ for attempt in 1...2 {
+ let startingChangeCount = self.pasteboard.changeCount
+ guard let sourceItems = self.pasteboard.pasteboardItems else {
+ let endingChangeCount = self.pasteboard.changeCount
+ if endingChangeCount != startingChangeCount {
+ self.logSnapshotRetry(
+ attempt: attempt,
+ startingChangeCount: startingChangeCount,
+ endingChangeCount: endingChangeCount
+ )
+ continue
+ }
+ self.logSnapshotFailure(
+ reason: "pasteboard_items_unavailable",
+ itemCount: 0,
+ itemIndex: -1,
+ totalBytes: 0
+ )
+ return nil
+ }
+ var items: [PasteboardSnapshot.Item] = []
+ var totalBytes = 0
+ var totalPortableImageBytes = 0
+ var totalRepresentations = 0
+ var failure: (reason: String, itemIndex: Int, type: NSPasteboard.PasteboardType?)?
+
+ itemLoop: for (itemIndex, sourceItem) in sourceItems.enumerated() {
+ let sourceTypes = sourceItem.types
+ guard !sourceTypes.isEmpty else {
+ failure = ("empty_item", itemIndex, nil)
+ break
+ }
+
+ var representations: [PasteboardSnapshot.Item.Representation] = []
+ representations.reserveCapacity(sourceTypes.count)
+ for type in sourceTypes {
+ guard let data = sourceItem.data(forType: type) else {
+ failure = ("unavailable_representation", itemIndex, type)
+ break itemLoop
+ }
+ representations.append(.init(type: type, data: data))
+ totalBytes += data.count
+ totalRepresentations += 1
+ }
+ let item = PasteboardSnapshot.Item(representations: representations)
+ let portableImage = Self.portableImageRepresentation(for: item)
+ totalPortableImageBytes += portableImage?.data.count ?? 0
+ items.append(
+ .init(
+ representations: representations,
+ portableImage: portableImage
+ )
+ )
+ }
+
+ let endingChangeCount = self.pasteboard.changeCount
+ guard endingChangeCount == startingChangeCount else {
+ self.logSnapshotRetry(
+ attempt: attempt,
+ startingChangeCount: startingChangeCount,
+ endingChangeCount: endingChangeCount
+ )
+ continue
+ }
+
+ if let failure {
+ self.logSnapshotFailure(
+ reason: failure.reason,
+ itemCount: sourceItems.count,
+ itemIndex: failure.itemIndex,
+ totalBytes: totalBytes,
+ type: failure.type
+ )
+ return nil
+ }
+
+ self.log(
+ "clipboard_snapshot_complete items=\(items.count) representations=\(totalRepresentations) " +
+ "bytes=\(totalBytes) portableImageBytes=\(totalPortableImageBytes) " +
+ "elapsedMs=\(Self.elapsedMs(since: startedAt)) firstItem=\(Self.representationSummary(items.first))"
+ )
+ return PasteboardSnapshot(items: items)
+ }
+
+ self.log("clipboard_snapshot_failed reason=clipboard_changed_during_snapshot")
+ return nil
+ }
+
+ func writeTemporaryText(_ text: String, sessionID: String) -> Bool {
+ let item = NSPasteboardItem()
+ guard item.setString(text, forType: .string),
+ item.setString(Bundle.main.bundleIdentifier ?? "com.FluidApp.Fluid", forType: Self.sourceType),
+ item.setData(Data(), forType: Self.transientType),
+ item.setData(Data(), forType: Self.autoGeneratedType),
+ item.setString(sessionID, forType: Self.sessionType)
+ else {
+ return false
+ }
+
- self.pasteboard.clearContents()
- return self.pasteboard.writeObjects([item]) && self.isOwned(sessionID: sessionID, expectedText: text)
++ let clearedChangeCount = self.pasteboard.clearContents()
++ self.temporaryWrite = (sessionID, clearedChangeCount)
++ let didWrite = self.pasteboard.writeObjects([item])
++ if self.hasTemporaryText(sessionID: sessionID, expectedText: text) {
++ self.temporaryWrite = (sessionID, self.pasteboard.changeCount)
++ return didWrite
++ }
++ return false
+ }
+
+ func writeIntentionalText(_ text: String) -> Bool {
+ let item = NSPasteboardItem()
+ guard item.setString(text, forType: .string) else { return false }
+
+ self.pasteboard.clearContents()
+ return self.pasteboard.writeObjects([item]) && self.pasteboard.string(forType: .string) == text
+ }
+
+ func isOwned(sessionID: String, expectedText: String) -> Bool {
++ guard let temporaryWrite,
++ temporaryWrite.sessionID == sessionID,
++ temporaryWrite.changeCount == self.pasteboard.changeCount
++ else { return false }
++ return self.hasTemporaryText(sessionID: sessionID, expectedText: expectedText)
++ }
++
++ private func hasTemporaryText(sessionID: String, expectedText: String) -> Bool {
+ self.pasteboard.string(forType: .string) == expectedText &&
+ self.pasteboard.string(forType: Self.sessionType) == sessionID
+ }
+
++ func restoreTemporarySnapshot(_ snapshot: PasteboardSnapshot, sessionID: String, expectedText _: String) -> Bool {
++ guard let temporaryWrite, temporaryWrite.sessionID == sessionID else { return false }
++ return self.restore(snapshot, ifUnchangedSince: temporaryWrite.changeCount)
++ }
++
+ func restore(_ snapshot: PasteboardSnapshot) -> Bool {
++ self.restore(snapshot, ifUnchangedSince: nil)
++ }
++
++ private func restore(_ snapshot: PasteboardSnapshot, ifUnchangedSince changeCount: Int?) -> Bool {
+ var items: [NSPasteboardItem] = []
+ for snapshotItem in snapshot.items {
+ let item = NSPasteboardItem()
+ let portableImage = snapshotItem.portableImage
+ let hasFileURL = snapshotItem.representations.contains { $0.type == .fileURL }
+
+ if !hasFileURL,
+ let portableImage,
+ !item.setData(portableImage.data, forType: portableImage.type)
+ {
+ self.log("clipboard_restore_failed reason=portable_image_write_failed type=\(portableImage.type.rawValue)")
+ return false
+ }
+ for representation in snapshotItem.representations {
+ guard Self.writeRestoredRepresentation(representation, to: item) else {
+ self.log("clipboard_restore_failed reason=representation_write_failed type=\(representation.type.rawValue)")
+ return false
+ }
+ if representation.type == .fileURL,
+ let portableImage,
+ !item.setData(portableImage.data, forType: portableImage.type)
+ {
+ self.log("clipboard_restore_failed reason=portable_image_write_failed type=\(portableImage.type.rawValue)")
+ return false
+ }
+ }
+ guard Self.addRestorationMarkers(to: item) else {
+ self.log("clipboard_restore_failed reason=marker_write_failed")
+ return false
+ }
+ items.append(item)
+ }
+
++ // Recheck after preparing representations; a newer external copy wins.
++ if let changeCount, self.pasteboard.changeCount != changeCount { return false }
+ self.pasteboard.clearContents()
+ guard items.isEmpty || self.pasteboard.writeObjects(items) else {
+ self.log("clipboard_restore_failed reason=pasteboard_write_failed")
+ return false
+ }
+ guard self.containsRestoredSnapshot(snapshot) else {
+ self.log("clipboard_restore_failed reason=post_write_verification_failed")
+ return false
+ }
+
+ let fileURLFallbacks = zip(self.pasteboard.pasteboardItems ?? [], snapshot.items).reduce(into: 0) { count, pair in
+ let (restoredItem, snapshotItem) = pair
+ if snapshotItem.representations.contains(where: { $0.type == .fileURL }),
+ restoredItem.data(forType: .fileURL) == nil,
+ snapshotItem.portableImage != nil
+ {
+ count += 1
+ }
+ }
+ self.log(
+ "clipboard_restore_verified items=\(snapshot.items.count) changeCount=\(self.pasteboard.changeCount) fileURLFallbacks=\(fileURLFallbacks) firstItem=\(Self.representationSummary(snapshot.items.first))"
+ )
+ if let portableImage = snapshot.items.first?.portableImage {
+ self.log("clipboard_restore_portable_image type=\(portableImage.type.rawValue) bytes=\(portableImage.data.count)")
+ }
+ return true
+ }
+
+ private func containsRestoredSnapshot(_ snapshot: PasteboardSnapshot) -> Bool {
+ let restoredItems = self.pasteboard.pasteboardItems ?? []
+ guard restoredItems.count == snapshot.items.count else { return false }
+
+ for (restoredItem, snapshotItem) in zip(restoredItems, snapshot.items) {
+ for representation in snapshotItem.representations {
+ if representation.type == .fileURL,
+ restoredItem.data(forType: .fileURL) == nil,
+ snapshotItem.portableImage != nil
+ {
+ continue
+ }
+ guard Self.restoredData(restoredItem, matches: representation) else {
+ return false
+ }
+ }
+ if let portableImage = snapshotItem.portableImage,
+ restoredItem.data(forType: portableImage.type) != portableImage.data
+ {
+ return false
+ }
+ guard restoredItem.types.contains(Self.transientType),
+ restoredItem.types.contains(Self.autoGeneratedType)
+ else {
+ return false
+ }
+ }
+ return true
+ }
+
+ private static func restoredData(
+ _ restoredItem: NSPasteboardItem,
+ matches representation: PasteboardSnapshot.Item.Representation
+ ) -> Bool {
+ if representation.type == .fileURL,
+ let expectedURL = URL(dataRepresentation: representation.data, relativeTo: nil, isAbsolute: true),
+ let restoredURL = restoredItem.string(forType: .fileURL).flatMap(URL.init(string:))
+ {
+ return restoredURL == expectedURL
+ }
+ return restoredItem.data(forType: representation.type) == representation.data
+ }
+
+ private static func portableImageRepresentation(
+ for item: PasteboardSnapshot.Item
+ ) -> PasteboardSnapshot.Item.Representation? {
+ let sourceTypes = Set(item.representations.map(\.type))
+ guard !sourceTypes.contains(.png),
+ !sourceTypes.contains(.tiff)
+ else {
+ return nil
+ }
+
+ if !sourceTypes.isDisjoint(with: Self.fileSemanticTypes) {
+ guard Self.fileItemContainsImage(item) else { return nil }
+
+ // Preserve an image file's encoded bytes directly. Decoding and re-encoding it
+ // here would put work proportional to its pixel count on the paste critical path.
+ if let fileURL = Self.fileURL(in: item),
+ let fileType = UTType(filenameExtension: fileURL.pathExtension),
+ fileType.conforms(to: .image),
+ let imageData = try? Data(contentsOf: fileURL, options: .mappedIfSafe)
+ {
+ return .init(
+ type: NSPasteboard.PasteboardType(fileType.identifier),
+ data: imageData
+ )
+ }
+ }
+
+ for representation in item.representations {
+ guard UTType(representation.type.rawValue)?.conforms(to: .image) == true,
+ let pngData = Self.pngData(from: representation.data)
+ else {
+ continue
+ }
+ return .init(type: .png, data: pngData)
+ }
+ return nil
+ }
+
+ private static func fileItemContainsImage(_ item: PasteboardSnapshot.Item) -> Bool {
+ if let fileURL = fileURL(in: item),
+ isImageFilename(fileURL.lastPathComponent)
+ {
+ return true
+ }
+
+ guard let textRepresentation = item.representations.first(where: { $0.type == .string }),
+ let filename = String(data: textRepresentation.data, encoding: .utf8)
+ else {
+ return false
+ }
+ return Self.isImageFilename(filename)
+ }
+
+ private static func fileURL(in item: PasteboardSnapshot.Item) -> URL? {
+ guard let representation = item.representations.first(where: { $0.type == .fileURL }) else {
+ return nil
+ }
+ return URL(dataRepresentation: representation.data, relativeTo: nil, isAbsolute: true)
+ }
+
+ private static func isImageFilename(_ filename: String) -> Bool {
+ let pathExtension = (filename as NSString).pathExtension
+ return !pathExtension.isEmpty && UTType(filenameExtension: pathExtension)?.conforms(to: .image) == true
+ }
+
+ private static func writeRestoredRepresentation(
+ _ representation: PasteboardSnapshot.Item.Representation,
+ to item: NSPasteboardItem
+ ) -> Bool {
+ if representation.type == .fileURL,
+ let fileURL = URL(dataRepresentation: representation.data, relativeTo: nil, isAbsolute: true)
+ {
+ // A file URL is a semantic pasteboard property-list value. Re-emitting its
+ // opaque bytes can appear valid to this process while disappearing for readers.
+ return item.setString(fileURL.absoluteString, forType: .fileURL)
+ }
+ return item.setData(representation.data, forType: representation.type)
+ }
+
+ private static func pngData(from sourceData: Data) -> Data? {
+ if let bitmap = NSBitmapImageRep(data: sourceData) {
+ return bitmap.representation(using: .png, properties: [:])
+ }
+
+ guard let image = NSImage(data: sourceData) else { return nil }
+ return Self.pngData(from: image)
+ }
+
+ private static func pngData(from image: NSImage) -> Data? {
+ var proposedRect = NSRect(origin: .zero, size: image.size)
+ guard let cgImage = image.cgImage(
+ forProposedRect: &proposedRect,
+ context: nil,
+ hints: nil
+ ) else {
+ return nil
+ }
+ return NSBitmapImageRep(cgImage: cgImage).representation(using: .png, properties: [:])
+ }
+
+ private static func addRestorationMarkers(to item: NSPasteboardItem) -> Bool {
+ let transientWasWritten = item.types.contains(Self.transientType) ||
+ item.setData(Data(), forType: Self.transientType)
+ let autoGeneratedWasWritten = item.types.contains(Self.autoGeneratedType) ||
+ item.setData(Data(), forType: Self.autoGeneratedType)
+ return transientWasWritten && autoGeneratedWasWritten
+ }
+
+ private static func representationSummary(_ item: PasteboardSnapshot.Item?) -> String {
+ guard let item else { return "none" }
+ return item.representations
+ .map { "\($0.type.rawValue):\($0.data.count)" }
+ .joined(separator: ",")
+ }
+
+ private func logSnapshotFailure(
+ reason: String,
+ itemCount: Int,
+ itemIndex: Int,
+ totalBytes: Int,
+ type: NSPasteboard.PasteboardType? = nil
+ ) {
+ self.log(
+ "clipboard_snapshot_failed reason=\(reason) items=\(itemCount) itemIndex=\(itemIndex) bytes=\(totalBytes) type=\(type?.rawValue ?? "nil")"
+ )
+ }
+
+ private func logSnapshotRetry(
+ attempt: Int,
+ startingChangeCount: Int,
+ endingChangeCount: Int
+ ) {
+ self.log(
+ "clipboard_snapshot_retry attempt=\(attempt) startChangeCount=\(startingChangeCount) endChangeCount=\(endingChangeCount)"
+ )
+ }
+
+ private func log(_ message: String) {
+ DebugLogger.shared.benchmark("TYPING_BENCH", message: message, source: "TypingBenchmark")
+ }
+
+ private static func elapsedMs(since start: TimeInterval) -> Int {
+ Int(((ProcessInfo.processInfo.systemUptime - start) * 1000).rounded())
+ }
+ }
+
-@MainActor
-enum KeyboardLayoutKeyCodeResolver {
- static func keyCode(for character: Character, qwertyFallback: CGKeyCode) -> CGKeyCode {
- guard let source = TISCopyCurrentKeyboardLayoutInputSource()?.takeRetainedValue(),
- let rawLayoutData = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData)
- else {
- return qwertyFallback
- }
-
- let layoutData = Unmanaged<CFData>.fromOpaque(rawLayoutData).takeUnretainedValue() as Data
- return layoutData.withUnsafeBytes { buffer in
- guard let layout = buffer.baseAddress?.assumingMemoryBound(to: UCKeyboardLayout.self) else {
- return qwertyFallback
- }
- return self.keyCode(for: character, qwertyFallback: qwertyFallback) { keyCode in
- self.unmodifiedScalar(for: keyCode, layout: layout)
- }
- }
- }
-
- static func keyCode(
- for character: Character,
- qwertyFallback: CGKeyCode,
- translatedScalar: (CGKeyCode) -> Unicode.Scalar?
- ) -> CGKeyCode {
- guard let targetScalar = character.unicodeScalars.first else { return qwertyFallback }
-
- for keyCode: CGKeyCode in 0..<128 where translatedScalar(keyCode) == targetScalar {
- return keyCode
- }
- return qwertyFallback
- }
-
- private static func unmodifiedScalar(
- for keyCode: CGKeyCode,
- layout: UnsafePointer<UCKeyboardLayout>
- ) -> Unicode.Scalar? {
- var deadKeyState: UInt32 = 0
- var characters = [UniChar](repeating: 0, count: 4)
- var length = 0
- let status = UCKeyTranslate(
- layout,
- keyCode,
- UInt16(kUCKeyActionDisplay),
- 0,
- UInt32(LMGetKbdType()),
- UInt32(kUCKeyTranslateNoDeadKeysMask),
- &deadKeyState,
- characters.count,
- &length,
- &characters
- )
- guard status == noErr, length > 0 else { return nil }
- return Unicode.Scalar(characters[0])
- }
-}
-
+ @MainActor
+ final class SystemPasteCommandPoster: PasteCommandPosting {
+ func postGlobalPasteCommand() async -> Bool {
+ guard AXIsProcessTrusted() else { return false }
+
- let pasteKeyCode = KeyboardLayoutKeyCodeResolver.keyCode(for: "v", qwertyFallback: 0x09)
++ let pasteKeyCode = TypingService.pasteVirtualKeyCode
+ let source = CGEventSource(stateID: .combinedSessionState)
+ guard let vDown = CGEvent(
+ keyboardEventSource: source,
+ virtualKey: pasteKeyCode,
+ keyDown: true
+ ), let vUp = CGEvent(
+ keyboardEventSource: source,
+ virtualKey: pasteKeyCode,
+ keyDown: false
+ ) else {
+ return false
+ }
+
+ vDown.flags = .maskCommand
+ vUp.flags = .maskCommand
+
+ // The coordinator verifies pasteboard ownership before reaching this point,
+ // so the temporary item is ready to consume without an additional delay.
+ vDown.post(tap: .cghidEventTap)
+ vUp.post(tap: .cghidEventTap)
+ return true
+ }
+ }
+
+ @MainActor
+ final class PasteDeliveryCoordinator {
+ static let shared = PasteDeliveryCoordinator()
+ nonisolated static let defaultSettlementDelayNanoseconds: UInt64 = 500_000_000
+
+ private struct ClipboardLease {
+ let originalSnapshot: PasteboardSnapshot
+ let sessionID: String
+ let text: String
+ let generation: UInt64
+ let shouldKeepTranscript: Bool
+ var settlementTask: Task<Void, Never>?
+ }
+
+ private let pasteboard: PasteboardManaging
+ private let commandPoster: PasteCommandPosting
+ private let settlementDelayNanoseconds: UInt64
+ private var generation: UInt64 = 0
+ private var lease: ClipboardLease?
+ private var isDelivering = false
+ private var deliveryWaiters: [CheckedContinuation<Void, Never>] = []
+
+ init(
+ pasteboard: PasteboardManaging? = nil,
+ commandPoster: PasteCommandPosting? = nil,
+ settlementDelayNanoseconds: UInt64 = PasteDeliveryCoordinator.defaultSettlementDelayNanoseconds
+ ) {
+ self.pasteboard = pasteboard ?? SystemPasteboardManager()
+ self.commandPoster = commandPoster ?? SystemPasteCommandPoster()
+ self.settlementDelayNanoseconds = settlementDelayNanoseconds
+ }
+
+ func deliver(
+ _ text: String,
+ preserveTranscriptOnClipboard: Bool,
+ onCommandPosted: ((TimeInterval) -> Void)? = nil
+ ) async -> TextDeliveryResult {
+ await self.acquireDeliverySlot()
- defer { self.releaseDeliverySlot() }
++ var settlementOwnsSlot = false
++ defer {
++ if !settlementOwnsSlot { self.releaseDeliverySlot() }
++ }
+
+ let startedAt = ProcessInfo.processInfo.systemUptime
+ self.generation &+= 1
+ let generation = self.generation
- self.lease?.settlementTask?.cancel()
-
- let originalSnapshot = self.captureOriginalSnapshotForNextDelivery()
- self.lease = nil
++ let originalSnapshot = self.pasteboard.captureSnapshot()
+
+ guard let originalSnapshot else {
+ self.log("delivery_failed generation=\(generation) reason=clipboard_snapshot_failed")
+ return .recoverableFailure(.clipboardSnapshotFailed)
+ }
+
+ let sessionID = UUID().uuidString
+ let writeStartedAt = ProcessInfo.processInfo.systemUptime
+ guard self.pasteboard.writeTemporaryText(text, sessionID: sessionID) else {
- self.restoreAfterFailure(originalSnapshot, generation: generation, reason: "clipboard_write_failed")
++ self.restoreAfterFailure(originalSnapshot, sessionID: sessionID, expectedText: text, generation: generation, reason: "clipboard_write_failed")
+ self.log("delivery_failed generation=\(generation) reason=clipboard_write_failed")
+ return .recoverableFailure(.clipboardWriteFailed)
+ }
+ self.log(
+ "clipboard_write generation=\(generation) elapsedMs=\(Self.elapsedMs(since: writeStartedAt))"
+ )
+
+ guard await self.commandPoster.postGlobalPasteCommand() else {
- self.restoreAfterFailure(originalSnapshot, generation: generation, reason: "paste_command_failed")
++ self.restoreAfterFailure(originalSnapshot, sessionID: sessionID, expectedText: text, generation: generation, reason: "paste_command_failed")
+ self.log("delivery_failed generation=\(generation) reason=paste_command_failed")
+ return .recoverableFailure(.pasteCommandFailed)
+ }
+ let commandPostedAt = ProcessInfo.processInfo.systemUptime
+ onCommandPosted?(commandPostedAt)
+
+ self.log(
+ "command_posted generation=\(generation) totalMs=\(Self.elapsedMs(since: startedAt))"
+ )
+
+ self.lease = ClipboardLease(
+ originalSnapshot: originalSnapshot,
+ sessionID: sessionID,
+ text: text,
+ generation: generation,
+ shouldKeepTranscript: preserveTranscriptOnClipboard,
+ settlementTask: nil
+ )
++ // Return immediately to finish delivery UI, but retain exclusive clipboard use
++ // until the existing consumption window ends.
++ settlementOwnsSlot = true
+ self.scheduleSettlement(sessionID: sessionID, generation: generation)
+ return .commandPosted
+ }
+
+ private func acquireDeliverySlot() async {
+ guard self.isDelivering else {
+ self.isDelivering = true
+ return
+ }
+
+ await withCheckedContinuation { continuation in
+ self.deliveryWaiters.append(continuation)
+ }
+ }
+
+ private func releaseDeliverySlot() {
+ guard !self.deliveryWaiters.isEmpty else {
+ self.isDelivering = false
+ return
+ }
+
+ self.deliveryWaiters.removeFirst().resume()
+ }
+
+ func runPendingSettlementForTesting() {
+ guard let lease = self.lease else { return }
+ lease.settlementTask?.cancel()
+ self.settleIfCurrent(sessionID: lease.sessionID, generation: lease.generation)
+ }
+
+ private func scheduleSettlement(sessionID: String, generation: UInt64) {
+ let settlementDelayNanoseconds = self.settlementDelayNanoseconds
+ let task = Task { @MainActor [weak self] in
+ try? await Task.sleep(nanoseconds: settlementDelayNanoseconds)
+ guard !Task.isCancelled else { return }
+ self?.settleIfCurrent(sessionID: sessionID, generation: generation)
+ }
+ self.lease?.settlementTask = task
+ self.log("settlement_scheduled generation=\(generation) delayMs=\(settlementDelayNanoseconds / 1_000_000)")
+ }
+
+ private func settleIfCurrent(sessionID: String, generation: UInt64) {
+ guard let lease = self.lease,
+ lease.generation == generation,
+ lease.sessionID == sessionID
+ else {
+ self.log("settlement_skipped generation=\(generation) reason=stale_generation")
+ return
+ }
+
+ self.lease = nil
++ defer { self.releaseDeliverySlot() }
+ guard self.pasteboard.isOwned(sessionID: sessionID, expectedText: lease.text) else {
+ self.log("settlement_skipped generation=\(generation) reason=clipboard_changed")
+ return
+ }
+
+ if lease.shouldKeepTranscript {
+ let didWrite = self.pasteboard.writeIntentionalText(lease.text)
+ self.log("intentional_copy_settled generation=\(generation) success=\(didWrite)")
+ } else {
- let didRestore = self.pasteboard.restore(lease.originalSnapshot)
++ let didRestore = self.pasteboard.restoreTemporarySnapshot(lease.originalSnapshot, sessionID: sessionID, expectedText: lease.text)
+ self.log("restore_completed generation=\(generation) success=\(didRestore)")
+ }
+ }
+
- private func captureOriginalSnapshotForNextDelivery() -> PasteboardSnapshot? {
- if let lease = self.lease,
- self.pasteboard.isOwned(sessionID: lease.sessionID, expectedText: lease.text)
- {
- return lease.originalSnapshot
- }
- return self.pasteboard.captureSnapshot()
- }
-
+ private func restoreAfterFailure(
+ _ snapshot: PasteboardSnapshot,
++ sessionID: String,
++ expectedText: String,
+ generation: UInt64,
+ reason: String
+ ) {
- let didRestore = self.pasteboard.restore(snapshot)
++ let didRestore = self.pasteboard.restoreTemporarySnapshot(snapshot, sessionID: sessionID, expectedText: expectedText)
+ self.log("failure_restore generation=\(generation) reason=\(reason) success=\(didRestore)")
+ }
+
+ private func log(_ message: String) {
+ DebugLogger.shared.benchmark("TYPING_BENCH", message: message, source: "TypingBenchmark")
+ }
+
+ private static func elapsedMs(since start: TimeInterval) -> Int {
+ Int(((ProcessInfo.processInfo.systemUptime - start) * 1000).rounded())
+ }
+ }
diff --cc Sources/Fluid/Services/TypingService.swift
index 28478c7e,e0383b5a..1113023c
--- a/Sources/Fluid/Services/TypingService.swift
+++ b/Sources/Fluid/Services/TypingService.swift
@@@ -112,32 -124,6 +124,32 @@@ final class TypingService
SettingsStore.shared.textInsertionMode
}
+ // MARK: - Layout-aware key code lookup
+
+ 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
+ }
+
+ /// 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).
+ /// Refreshed by the input-source notification, never by a background paste request.
- private static var pasteVirtualKeyCode: CGKeyCode {
++ static var pasteVirtualKeyCode: CGKeyCode {
+ 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)
/// Best-effort: returns the PID owning the currently focused accessibility element.
@@@ -403,117 -465,144 +491,146 @@@
self.bench("request_return reason=accessibility_not_trusted")
self.log("[TypingService] ERROR: Accessibility permissions required for text injection")
self.log("[TypingService] Current accessibility status: \(AXIsProcessTrusted())")
- completion?(.rejected)
- return
+ let result = TextDeliveryResult.recoverableFailure(.accessibilityNotTrusted)
+ self.recordInsertionLatency(
+ path: .notAttempted,
+ result: result,
+ requestedAt: requestedAt,
+ textReadyAt: textReadyAt,
+ toggleStopRequestedAt: toggleStopRequestedAt
+ )
+ return result
+ }
+
+ let usesClipboard = mode == .reliablePaste ||
+ self.ghosttyTargetPID(preferredTargetPID: preferredTargetPID) != nil
+ let result: TextDeliveryResult
+ let deliveryPath: AnalyticsInsertionPath
+ var dispatchedAt: TimeInterval?
+ if usesClipboard {
+ deliveryPath = .clipboard
+ result = await PasteDeliveryCoordinator.shared.deliver(
+ text,
+ preserveTranscriptOnClipboard: preserveTranscriptOnClipboard,
+ onCommandPosted: { dispatchedAt = $0 }
+ )
+ } else if await self.insertTextDirectlyOffMain(text, preferredTargetPID: preferredTargetPID) {
+ deliveryPath = .direct
+ if preserveTranscriptOnClipboard {
+ _ = ClipboardService.copyToClipboard(text)
+ }
+ result = .commandPosted
+ } else {
+ deliveryPath = .clipboardFallback
+ self.log("[TypingService] Direct insertion failed; using non-blocking clipboard fallback")
+ result = await PasteDeliveryCoordinator.shared.deliver(
+ text,
+ preserveTranscriptOnClipboard: preserveTranscriptOnClipboard,
+ onCommandPosted: { dispatchedAt = $0 }
+ )
}
- self.log("[TypingService] Accessibility check passed, proceeding with text injection")
- self.isCurrentlyTyping = true
+ let completedAt = dispatchedAt ?? ProcessInfo.processInfo.systemUptime
+ self.bench(
+ "complete result=\(String(describing: result)) totalMs=\(Self.elapsedMs(from: requestedAt, to: completedAt)) textReadyToCompleteMs=\(textReadyAt.map { String(Self.elapsedMs(from: $0, to: completedAt)) } ?? "nil")"
+ )
+ self.recordInsertionLatency(
+ path: deliveryPath,
+ result: result,
+ requestedAt: requestedAt,
+ textReadyAt: textReadyAt,
+ toggleStopRequestedAt: toggleStopRequestedAt,
+ completedAt: completedAt
+ )
- if result.wasDispatched, tracksDictionaryCorrections {
- AutomaticDictionaryCorrectionTracker.shared.beginObservingInsertion(
- text,
- targetPID: preferredTargetPID
- )
- }
++ // The caller starts correction tracking after completing delivery UI.
+ return result
+ }
- let pipelineID = DebugLogger.pipelineID
- DispatchQueue.global(qos: .userInitiated).async {
- DebugLogger.$pipelineID.withValue(pipelineID) {
- var outcome: DeliveryOutcome = .insertionFailed
- let workerStartedAt = ProcessInfo.processInfo.systemUptime
- self.bench("worker_start queueDelayMs=\(Self.elapsedMs(from: requestedAt, to: workerStartedAt))")
+ func typeOutputPlanInstantly(
+ _ plan: DictationLiteralOutputPlan,
+ preferredTargetPID: pid_t?,
+ textReadyAt: TimeInterval?,
+ toggleStopRequestedAt: TimeInterval? = nil,
+ tracksDictionaryCorrections: Bool = false,
+ postInsertionKey: SettingsStore.SpokenSendKey? = nil,
+ requiredFocusTarget: CapturedFocusTarget? = nil,
+ preserveTranscriptOnClipboard: Bool = false,
- completion: ((DeliveryOutcome) -> Void)? = nil
++ completion: (@MainActor (DeliveryOutcome) -> Void)? = nil
+ ) {
+ Task { @MainActor in
+ let hasTextToInsert = !plan.plainText.isEmpty
+ guard hasTextToInsert || postInsertionKey != nil else {
+ completion?(.rejected)
+ return
+ }
- 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")
- }
- }
+ if postInsertionKey != nil {
+ guard let preferredTargetPID, let requiredFocusTarget,
+ Self.canInsertBeforePostInsertionAction(
+ preferredTargetPID: preferredTargetPID,
+ requiredTargetPID: requiredFocusTarget.pid,
+ isSecureTextField: requiredFocusTarget.isSecureTextField,
+ exactFocusIsActive: Self.isExactFocusTargetActive(requiredFocusTarget)
+ )
+ else {
+ completion?(.actionSuppressed)
+ return
}
+ }
- 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
- }
+ var outcome: DeliveryOutcome = .actionSuppressed
+ if hasTextToInsert {
+ let result = await self.typeOutputPlanInstantly(
+ plan,
+ preferredTargetPID: preferredTargetPID,
+ textReadyAt: textReadyAt,
+ toggleStopRequestedAt: toggleStopRequestedAt,
+ tracksDictionaryCorrections: tracksDictionaryCorrections,
+ preserveTranscriptOnClipboard: preserveTranscriptOnClipboard
+ )
+ guard result.wasDispatched else {
+ completion?(.insertionFailed)
+ return
}
+ outcome = .inserted
+ }
- 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 let postInsertionKey else {
+ completion?(outcome)
++ if tracksDictionaryCorrections, outcome.didInsert {
++ AutomaticDictionaryCorrectionTracker.shared.beginObservingInsertion(
++ plan.plainText,
++ targetPID: preferredTargetPID
+ )
- guard inserted else {
- outcome = .insertionFailed
- return
- }
-
- outcome = .inserted
++ self.bench("dictionary_tracking_scheduled afterDeliveryCallback=true")
+ }
+ return
+ }
+ guard let preferredTargetPID, let requiredFocusTarget else {
+ completion?(hasTextToInsert ? .insertedActionSuppressed : .actionSuppressed)
+ return
+ }
- 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
- }
+ let modifiersReleased = await self.waitForPhysicalModifiersToRelease(timeout: 2)
+ guard Self.canDispatchPostInsertionAction(
+ preferredTargetPID: preferredTargetPID,
+ requiredTargetPID: requiredFocusTarget.pid,
+ isSecureTextField: requiredFocusTarget.isSecureTextField,
+ modifiersReleased: modifiersReleased,
+ exactFocusIsActive: Self.isExactFocusTargetActive(requiredFocusTarget)
+ ) else {
+ completion?(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
+ try? await Task.sleep(nanoseconds: 50_000_000)
+ guard Self.isExactFocusTargetActive(requiredFocusTarget),
+ await self.postReturnKey(postInsertionKey, targetPID: preferredTargetPID)
+ else {
+ completion?(hasTextToInsert ? .insertedActionSuppressed : .actionSuppressed)
+ return
}
+ completion?(hasTextToInsert ? .insertedAndActionDispatched : .actionDispatched)
}
}
@@@ -737,16 -808,24 +836,37 @@@
return "focusedPID=\(pid) role=\(role) subrole=\(subrole) title=\(title) description=\(description)"
}
- private static func logFocusState(_ prefix: String) {
+ private nonisolated static func logFocusState(_ prefix: String) {
guard self.isLoggingEnabled else { return }
- self.emitDebugLog("\(prefix) | \(self.currentFocusDebugDescription())")
+ 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")
++ let description = self.currentFocusDebugDescription()
++ let finishedAt = ProcessInfo.processInfo.systemUptime
++ let elapsedMs = Int(((finishedAt - startedAt) * 1000).rounded())
++ self.emitDebugLog(
++ "\(prefix) | \(description)",
++ focusTiming: "TYPING_BENCH t=\(finishedAt) focus_debug_query elapsedMs=\(elapsedMs)"
++ )
+ }
+
- private nonisolated static func emitDebugLog(_ message: String) {
++ private nonisolated static func emitDebugLog(_ message: String, focusTiming: String? = nil) {
+ if Thread.isMainThread {
+ MainActor.assumeIsolated {
+ DebugLogger.shared.debug(message, source: "TypingService")
++ if let focusTiming {
++ DebugLogger.shared.info(focusTiming, source: "TypingBenchmark")
++ }
+ }
+ } else {
+ DispatchQueue.main.async {
+ DebugLogger.shared.debug(message, source: "TypingService")
++ if let focusTiming {
++ DebugLogger.shared.info(focusTiming, source: "TypingBenchmark")
++ }
+ }
}
- DebugLogger.shared.debug("\(prefix) | \(self.currentFocusDebugDescription())", source: "TypingService")
}
- private static func isCurrentlyFocusedElement(_ expectedElement: AXUIElement, expectedPID: pid_t) -> Bool {
+ private nonisolated static func isCurrentlyFocusedElement(_ expectedElement: AXUIElement, expectedPID: pid_t) -> Bool {
let systemWideElement = AXUIElementCreateSystemWide()
var focusedElementRef: CFTypeRef?
let result = AXUIElementCopyAttributeValue(
diff --cc Sources/Fluid/UI/AnalyticsPrivacyView.swift
index 47ecc1bb,6414983c..f9ecb0ff
--- a/Sources/Fluid/UI/AnalyticsPrivacyView.swift
+++ b/Sources/Fluid/UI/AnalyticsPrivacyView.swift
@@@ -45,16 -43,14 +46,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, other unique device identifiers, or individual transcription events.")
- self.bullet("Hardware identifiers, CPU/chip details, target-app identity, or individual insertion timings/events.")
++ self.bullet("Hardware serial numbers, other unique device identifiers, target-app identity, or individual transcription and insertion timings/events.")
self.sectionTitle("How it’s used")
- self.bullet("To understand feature adoption, insertion performance, onboarding completion, model usage, active installations, and retention without requiring accounts.")
+ 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("Optional detailed analytics helps us understand feature adoption, insertion performance, 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 analytics anytime in Settings → Share Anonymous Analytics.")
- self.bullet("Disabling analytics securely removes all queued and aggregated analytics stored on this Mac.")
+ 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. Daily activity and beta timing summaries remain enabled.")
}
.padding(.vertical, 6)
}
diff --cc Sources/Fluid/UI/SettingsView.swift
index 49ccd857,45535153..d4bbe3e2
--- a/Sources/Fluid/UI/SettingsView.swift
+++ b/Sources/Fluid/UI/SettingsView.swift
@@@ -782,7 -774,7 +782,7 @@@ struct SettingsView: View
icon: "arrow.down.doc",
iconColor: .secondary,
title: "Paste Last Transcription",
-- description: "Re-insert your most recent transcription without using the clipboard"
++ description: "Re-insert your most recent transcription using your selected insertion method"
),
shortcut: self.pasteLastTranscriptionShortcut,
isRecording: self.isRecording(.pasteLast),
@@@ -964,13 -942,10 +964,13 @@@
Divider().opacity(0.2)
self.optionToggleRow(
- title: "Share Anonymous Analytics",
- description: "Send lean, anonymous daily usage, insertion performance, onboarding, retention, and model metrics. Never includes transcription text or prompts.",
- isOn: self.analyticsToggleBinding
+ title: "Share Detailed Anonymous Analytics",
- description: "Share anonymous daily feature, onboarding, and model metrics. " +
++ description: "Share anonymous daily feature, insertion performance, onboarding, and model metrics. " +
+ "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
)
+ .settingsSearchTarget(.analyticsPrivacy)
HStack {
Button("What we collect") {
diff --cc Sources/Fluid/Views/BottomOverlayView.swift
index f7463aa4,eb494426..909cfd2e
--- a/Sources/Fluid/Views/BottomOverlayView.swift
+++ b/Sources/Fluid/Views/BottomOverlayView.swift
@@@ -3065,51 -2825,32 +3074,77 @@@ struct BottomOverlayView: View
.frame(maxWidth: self.previewMaxWidth, alignment: .leading)
}
+ private var targetAppIconView: some View {
+ let appIcon = self.displayedAppIcon
+ let showModelLoading = self.layout.showsModeLabel && !self.appServices.asr.isAsrReady &&
+ (self.appServices.asr.isLoadingModel || self.appServices.asr.isDownloadingModel)
+ return VStack(spacing: 2) {
+ if showModelLoading {
+ ProgressView()
+ .controlSize(.mini)
+ }
+ if let appIcon = appIcon {
+ Image(nsImage: appIcon)
+ .resizable()
+ .aspectRatio(contentMode: .fit)
+ .frame(width: self.layout.iconSize, height: self.layout.iconSize)
+ .clipShape(RoundedRectangle(cornerRadius: self.layout.iconSize / 4))
+ } else if !self.layout.showsModeLabel {
+ Circle()
+ .fill(self.modeColor.opacity(0.9))
+ .frame(width: max(self.layout.iconSize * 0.45, 7), height: max(self.layout.iconSize * 0.45, 7))
+ }
+ }
+ .frame(width: self.layout.iconSize, height: self.layout.iconSize)
+ .opacity((appIcon != nil || showModelLoading || !self.layout.showsModeLabel) ? 1 : 0)
+ }
+
+ private var leadingAppContextView: some View {
+ HStack(spacing: self.isPillSize ? 4 : 8) {
+ if self.showsSpokenSendIndicator {
+ SpokenSendIndicatorView(
+ state: self.contentState.spokenSendIndicatorState,
+ color: self.modeColor,
+ size: self.isPillSize ? 14 : self.spokenSendIndicatorSize
+ )
+ .id(self.contentState.spokenSendCountdownID)
+ .transition(.scale(scale: 0.8).combined(with: .opacity))
+ }
+
+ self.targetAppIconView
+ }
+ .animation(
+ self.reduceMotion ? nil : .easeOut(duration: 0.14),
+ value: self.contentState.spokenSendIndicatorState
+ )
+ }
+
+ private var textDeliveryFailureView: some View {
+ HStack(spacing: 8) {
+ Text(self.contentState.textDeliveryFailureMessage)
+ .font(.system(size: self.layout.transFontSize, weight: .semibold))
+ .foregroundStyle(Color.orange.opacity(0.9))
+ .lineLimit(1)
+ .truncationMode(.tail)
+
+ Spacer(minLength: 4)
+
+ self.failureIconButton(systemName: "doc.on.doc", help: "Copy transcript") {
+ _ = ClipboardService.copyToClipboard(self.contentState.textDeliveryFailureTranscript)
+ }
+ self.failureIconButton(systemName: "arrow.down.doc", help: "Paste last transcript") {
+ let transcript = self.contentState.textDeliveryFailureTranscript
+ self.contentState.clearTextDeliveryFailure()
+ self.contentState.onRetryTextDeliveryRequested?(transcript)
+ }
+ self.failureIconButton(systemName: "xmark", help: "Dismiss") {
+ self.contentState.clearTextDeliveryFailure()
+ NotchOverlayManager.shared.hide()
+ }
+ }
+ .frame(maxWidth: self.previewMaxWidth, alignment: .leading)
+ }
+
private func scrollablePreviewText(_ previewText: String) -> some View {
ScrollViewReader { proxy in
ScrollView(.vertical, showsIndicators: false) {
diff --cc Sources/Fluid/Views/NotchContentViews.swift
index 1fd4cc50,a2c28101..ba2e66a4
--- a/Sources/Fluid/Views/NotchContentViews.swift
+++ b/Sources/Fluid/Views/NotchContentViews.swift
@@@ -204,6 -209,16 +209,16 @@@ class NotchContentState: ObservableObje
return self.spokenSendCountdownID
}
- func showTextDeliveryFailure(message: String, transcript: String) {
- self.textDeliveryFailureMessage = message
++ func recordTextDeliveryFailure(_ failure: TextDeliveryFailure, transcript: String) {
+ self.textDeliveryFailureTranscript = transcript
- self.isTextDeliveryFailureVisible = true
++ self.textDeliveryFailureMessage = failure.userFacingMessage ?? ""
++ self.isTextDeliveryFailureVisible = failure.userFacingMessage != nil
+ }
+
+ func clearTextDeliveryFailure() {
+ self.isTextDeliveryFailureVisible = false
+ }
+
/// Update transcription and recompute cached lines
func updateTranscription(_ text: String) {
let boundedText = Self.tailCharacters(in: text, maxCharacters: Self.maxStoredTranscriptionCharacters)
diff --cc Tests/FluidDictationIntegrationTests/AnalyticsDatabaseTests.swift
index 151acb4c,fd04fbf2..14b85d44
--- a/Tests/FluidDictationIntegrationTests/AnalyticsDatabaseTests.swift
+++ b/Tests/FluidDictationIntegrationTests/AnalyticsDatabaseTests.swift
@@@ -15,133 -15,6 +15,185 @@@ final class AnalyticsDatabaseTests: XCT
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 testDetailedOptOutClearsInsertionAggregatesWithoutRemovingBetaPerformance() throws {
++ let database = try self.makeDatabase()
++ let firstDay = Date(timeIntervalSince1970: 1_735_689_600)
++ let secondDay = firstDay.addingTimeInterval(24 * 60 * 60)
++
++ // Keep both an already queued summary and an unfinished day's aggregates.
++ for day in [firstDay, secondDay] {
++ try database.recordDictationPerformance(
++ asrMilliseconds: 75,
++ fluidIntelligenceMilliseconds: 200,
++ measuredAppVersion: "1.6.10-beta.1",
++ at: day
++ )
++ try database.recordInsertionLatency(
++ path: .clipboard,
++ outcome: .dispatched,
++ requestMilliseconds: 80,
++ readyMilliseconds: 90,
++ toggleStopMilliseconds: 100,
++ at: day
++ )
++ }
++
++ try database.purgeDetailedAnalytics()
++
++ let remainingNames = try self.events(in: database).map(\.name)
++ XCTAssertEqual(remainingNames, [AnalyticsEvent.dictationPerformanceDailySummary.rawValue])
++
++ // A same-day opt-in must not resurrect either insertion or toggle-stop samples.
++ try database.recordInsertionLatency(
++ path: .clipboard,
++ outcome: .dispatched,
++ requestMilliseconds: 5,
++ readyMilliseconds: nil,
++ at: secondDay.addingTimeInterval(60)
++ )
++ try database.finalizeDays(before: secondDay.addingTimeInterval(24 * 60 * 60))
++
++ let events = try self.events(in: database)
++ let betaSummaries = events.filter { $0.name == AnalyticsEvent.dictationPerformanceDailySummary.rawValue }
++ XCTAssertEqual(betaSummaries.count, 2)
++ XCTAssertTrue(betaSummaries.allSatisfy { $0.properties["asr_sample_count"] as? Int == 1 })
++ let insertionSummaries = events.filter { $0.name == AnalyticsEvent.insertionLatencyDailySummary.rawValue }
++ XCTAssertEqual(insertionSummaries.count, 1)
++ let insertion = try XCTUnwrap(insertionSummaries.first)
++ XCTAssertEqual(insertion.properties["request_count"] as? Int, 1)
++ XCTAssertEqual(insertion.properties["request_total_ms"] as? Int, 5)
++ XCTAssertEqual(insertion.properties["ready_count"] as? Int, 0)
++ XCTAssertNil(insertion.properties["toggle_stop_to_dispatch_count"])
++ XCTAssertNil(insertion.properties["toggle_stop_to_dispatch_total_ms"])
++ }
++
+ 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
diff --cc Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift
index 00000000,53479c86..438290aa
mode 000000,100644..100644
--- a/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift
+++ b/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift
@@@ -1,0 -1,428 +1,573 @@@
+ import AppKit
+ @testable import FluidVoice_Debug
+ import Foundation
+ import XCTest
+
+ @MainActor
+ final class PasteDeliveryCoordinatorTests: XCTestCase {
+ func testDeliveryPostsImmediatelyAndRestoresOriginalClipboard() async {
+ let pasteboard = FakePasteboardManager(text: "before")
+ let commandPoster = FakePasteCommandPoster()
+ let coordinator = PasteDeliveryCoordinator(
+ pasteboard: pasteboard,
+ commandPoster: commandPoster,
+ settlementDelayNanoseconds: .max
+ )
+
+ let result = await coordinator.deliver("dictated text", preserveTranscriptOnClipboard: false)
+
+ XCTAssertEqual(result, .commandPosted)
+ XCTAssertEqual(commandPoster.postCount, 1)
+ XCTAssertEqual(pasteboard.text, "dictated text")
+
+ coordinator.runPendingSettlementForTesting()
+
+ XCTAssertEqual(pasteboard.text, "before")
+ XCTAssertEqual(pasteboard.restoreCount, 1)
+ }
+
- func testOverlappingDeliveriesRestoreThePreBurstClipboardOnce() async {
++ func testQueuedDeliveryKeepsFirstPayloadUntilConsumptionWindowEnds() async {
+ let pasteboard = FakePasteboardManager(text: "before")
+ let commandPoster = FakePasteCommandPoster()
+ let coordinator = PasteDeliveryCoordinator(
+ pasteboard: pasteboard,
+ commandPoster: commandPoster,
+ settlementDelayNanoseconds: .max
+ )
+
+ let firstResult = await coordinator.deliver("first", preserveTranscriptOnClipboard: false)
- let secondResult = await coordinator.deliver("second", preserveTranscriptOnClipboard: false)
++ var secondStarted = false
++ let secondDelivery = Task { @MainActor in
++ secondStarted = true
++ return await coordinator.deliver("second", preserveTranscriptOnClipboard: false)
++ }
++ await self.waitUntil { secondStarted }
+
+ XCTAssertEqual(firstResult, .commandPosted)
++ XCTAssertEqual(commandPoster.postCount, 1)
++ XCTAssertEqual(pasteboard.text, "first")
++ var consumedTexts = [pasteboard.text]
++ coordinator.runPendingSettlementForTesting()
++
++ let secondResult = await secondDelivery.value
+ XCTAssertEqual(secondResult, .commandPosted)
++ consumedTexts.append(pasteboard.text)
+ coordinator.runPendingSettlementForTesting()
+
++ XCTAssertEqual(consumedTexts, ["first", "second"])
+ XCTAssertEqual(commandPoster.postCount, 2)
+ XCTAssertEqual(pasteboard.text, "before")
- XCTAssertEqual(pasteboard.restoreCount, 1)
++ XCTAssertEqual(pasteboard.restoreCount, 2)
+ }
+
+ func testOverlappingDeliveriesDoNotReplaceClipboardDuringActivePasteCommand() async {
+ let pasteboard = FakePasteboardManager(text: "before")
+ let commandPoster = SuspendingFakePasteCommandPoster()
+ let coordinator = PasteDeliveryCoordinator(
+ pasteboard: pasteboard,
+ commandPoster: commandPoster,
+ settlementDelayNanoseconds: .max
+ )
+
+ let firstDelivery = Task { @MainActor in
+ await coordinator.deliver("first", preserveTranscriptOnClipboard: false)
+ }
+ await self.waitUntil { commandPoster.firstPostIsSuspended }
+
+ let secondDelivery = Task { @MainActor in
+ await coordinator.deliver("second", preserveTranscriptOnClipboard: false)
+ }
+ await Task.yield()
+
+ XCTAssertEqual(pasteboard.text, "first")
+ XCTAssertEqual(pasteboard.temporaryWriteCount, 1)
+ XCTAssertEqual(commandPoster.postCount, 1)
+
+ commandPoster.resumeFirstPost()
+ let firstResult = await firstDelivery.value
++ XCTAssertEqual(pasteboard.text, "first")
++ XCTAssertEqual(commandPoster.postCount, 1)
++ coordinator.runPendingSettlementForTesting()
+ let secondResult = await secondDelivery.value
+
+ XCTAssertEqual(firstResult, .commandPosted)
+ XCTAssertEqual(secondResult, .commandPosted)
+ XCTAssertEqual(pasteboard.temporaryWriteCount, 2)
+ XCTAssertEqual(commandPoster.postCount, 2)
++ coordinator.runPendingSettlementForTesting()
+ }
+
+ func testExternalClipboardChangeIsNeverOverwritten() async {
+ let pasteboard = FakePasteboardManager(text: "before")
+ let coordinator = PasteDeliveryCoordinator(
+ pasteboard: pasteboard,
+ commandPoster: FakePasteCommandPoster(),
+ settlementDelayNanoseconds: .max
+ )
+
+ let result = await coordinator.deliver("dictated text", preserveTranscriptOnClipboard: false)
+
+ XCTAssertEqual(result, .commandPosted)
+ pasteboard.simulateExternalCopy("user copy")
+ coordinator.runPendingSettlementForTesting()
+
+ XCTAssertEqual(pasteboard.text, "user copy")
+ XCTAssertEqual(pasteboard.restoreCount, 0)
+ }
+
+ func testCopyTranscriptPreferenceKeepsTranscriptOnClipboard() async {
+ let pasteboard = FakePasteboardManager(text: "before")
+ let coordinator = PasteDeliveryCoordinator(
+ pasteboard: pasteboard,
+ commandPoster: FakePasteCommandPoster(),
+ settlementDelayNanoseconds: .max
+ )
+
+ let result = await coordinator.deliver("dictated text", preserveTranscriptOnClipboard: true)
+
+ XCTAssertEqual(result, .commandPosted)
+ XCTAssertTrue(pasteboard.isTemporary)
+
+ coordinator.runPendingSettlementForTesting()
+
+ XCTAssertEqual(pasteboard.text, "dictated text")
+ XCTAssertEqual(pasteboard.restoreCount, 0)
+ XCTAssertEqual(pasteboard.intentionalWriteCount, 1)
+ XCTAssertFalse(pasteboard.isTemporary)
+ }
+
+ func testExternalClipboardChangeWinsOverCopyTranscriptPreference() async {
+ let pasteboard = FakePasteboardManager(text: "before")
+ let coordinator = PasteDeliveryCoordinator(
+ pasteboard: pasteboard,
+ commandPoster: FakePasteCommandPoster(),
+ settlementDelayNanoseconds: .max
+ )
+
+ let result = await coordinator.deliver("dictated text", preserveTranscriptOnClipboard: true)
+
+ XCTAssertEqual(result, .commandPosted)
+ pasteboard.simulateExternalCopy("user copy")
+ coordinator.runPendingSettlementForTesting()
+
+ XCTAssertEqual(pasteboard.text, "user copy")
+ XCTAssertEqual(pasteboard.intentionalWriteCount, 0)
+ }
+
+ func testPasteCommandFailureRestoresOriginalClipboardForRecovery() async {
+ let pasteboard = FakePasteboardManager(text: "before")
+ let commandPoster = FakePasteCommandPoster(succeeds: false)
+ let coordinator = PasteDeliveryCoordinator(
+ pasteboard: pasteboard,
+ commandPoster: commandPoster,
+ settlementDelayNanoseconds: .max
+ )
+
+ let result = await coordinator.deliver("dictated text", preserveTranscriptOnClipboard: false)
+ coordinator.runPendingSettlementForTesting()
+
+ XCTAssertEqual(result, .recoverableFailure(.pasteCommandFailed))
+ XCTAssertEqual(pasteboard.text, "before")
+ XCTAssertEqual(pasteboard.restoreCount, 1)
+ XCTAssertFalse(pasteboard.isTemporary)
+ }
+
+ func testPasteCommandFailureRestoresOriginalClipboardWhenCopyPreferenceIsEnabled() async {
+ let pasteboard = FakePasteboardManager(text: "before")
+ let coordinator = PasteDeliveryCoordinator(
+ pasteboard: pasteboard,
+ commandPoster: FakePasteCommandPoster(succeeds: false),
+ settlementDelayNanoseconds: .max
+ )
+
+ let result = await coordinator.deliver("dictated text", preserveTranscriptOnClipboard: true)
+
+ XCTAssertEqual(result, .recoverableFailure(.pasteCommandFailed))
+ XCTAssertEqual(pasteboard.text, "before")
+ XCTAssertEqual(pasteboard.restoreCount, 1)
+ XCTAssertEqual(pasteboard.intentionalWriteCount, 0)
+ }
+
+ func testIncompleteSnapshotDoesNotTouchClipboardOrPostPasteCommand() async {
+ let pasteboard = FakePasteboardManager(text: "before", snapshotSucceeds: false)
+ let commandPoster = FakePasteCommandPoster()
+ let coordinator = PasteDeliveryCoordinator(
+ pasteboard: pasteboard,
+ commandPoster: commandPoster,
+ settlementDelayNanoseconds: .max
+ )
+
+ let result = await coordinator.deliver("dictated text", preserveTranscriptOnClipboard: false)
+
+ XCTAssertEqual(result, .recoverableFailure(.clipboardSnapshotFailed))
+ XCTAssertEqual(pasteboard.text, "before")
+ XCTAssertEqual(pasteboard.temporaryWriteCount, 0)
+ XCTAssertEqual(commandPoster.postCount, 0)
+ }
+
+ func testTemporaryWriteFailureRestoresOriginalClipboard() async {
+ let pasteboard = FakePasteboardManager(text: "before", temporaryWriteSucceeds: false)
+ let commandPoster = FakePasteCommandPoster()
+ let coordinator = PasteDeliveryCoordinator(
+ pasteboard: pasteboard,
+ commandPoster: commandPoster,
+ settlementDelayNanoseconds: .max
+ )
+
+ let result = await coordinator.deliver("dictated text", preserveTranscriptOnClipboard: false)
+
+ XCTAssertEqual(result, .recoverableFailure(.clipboardWriteFailed))
+ XCTAssertEqual(pasteboard.text, "before")
+ XCTAssertEqual(pasteboard.restoreCount, 1)
+ XCTAssertEqual(commandPoster.postCount, 0)
+ }
+
- func testHundredRapidDeliveriesDoNotDropCommands() async {
++ func testExternalCopyDuringFailedWriteIsPreserved() async {
++ let pasteboard = FakePasteboardManager(text: "before", temporaryWriteSucceeds: false)
++ pasteboard.onTemporaryWrite = { pasteboard.simulateExternalCopy("new user copy") }
++ let commandPoster = FakePasteCommandPoster()
++ let coordinator = PasteDeliveryCoordinator(
++ pasteboard: pasteboard,
++ commandPoster: commandPoster,
++ settlementDelayNanoseconds: .max
++ )
++
++ let result = await coordinator.deliver("dictated text", preserveTranscriptOnClipboard: false)
++
++ XCTAssertEqual(result, .recoverableFailure(.clipboardWriteFailed))
++ XCTAssertEqual(pasteboard.text, "new user copy")
++ XCTAssertEqual(pasteboard.restoreCount, 0)
++ XCTAssertEqual(commandPoster.postCount, 0)
++ pasteboard.onTemporaryWrite = nil
++ }
++
++ func testExternalCopyDuringFailedPostIsPreserved() async {
++ let pasteboard = FakePasteboardManager(text: "before")
++ let commandPoster = FakePasteCommandPoster(succeeds: false)
++ commandPoster.onPost = { pasteboard.simulateExternalCopy("new user copy") }
++ let coordinator = PasteDeliveryCoordinator(
++ pasteboard: pasteboard,
++ commandPoster: commandPoster,
++ settlementDelayNanoseconds: .max
++ )
++
++ let result = await coordinator.deliver("dictated text", preserveTranscriptOnClipboard: false)
++
++ XCTAssertEqual(result, .recoverableFailure(.pasteCommandFailed))
++ XCTAssertEqual(pasteboard.text, "new user copy")
++ XCTAssertEqual(pasteboard.restoreCount, 0)
++ }
++
++ func testSnapshotFailureReleasesSlotForNextDelivery() async {
++ let pasteboard = FakePasteboardManager(text: "before", snapshotSucceeds: false)
++ let coordinator = PasteDeliveryCoordinator(
++ pasteboard: pasteboard,
++ commandPoster: FakePasteCommandPoster(),
++ settlementDelayNanoseconds: .max
++ )
++ let firstResult = await coordinator.deliver("first", preserveTranscriptOnClipboard: false)
++ XCTAssertEqual(firstResult, .recoverableFailure(.clipboardSnapshotFailed))
++ pasteboard.snapshotSucceeds = true
++ var nextResult: TextDeliveryResult?
++ let nextDelivery = Task { @MainActor in
++ nextResult = await coordinator.deliver("second", preserveTranscriptOnClipboard: false)
++ }
++ await self.waitUntil { nextResult != nil }
++ XCTAssertEqual(nextResult, .commandPosted)
++ XCTAssertEqual(pasteboard.text, "second")
++ coordinator.runPendingSettlementForTesting()
++ nextDelivery.cancel()
++ }
++
++ func testSettlementAfterExternalCopyReleasesQueuedDelivery() async {
++ let pasteboard = FakePasteboardManager(text: "before")
++ let coordinator = PasteDeliveryCoordinator(
++ pasteboard: pasteboard,
++ commandPoster: FakePasteCommandPoster(),
++ settlementDelayNanoseconds: .max
++ )
++ let firstResult = await coordinator.deliver("first", preserveTranscriptOnClipboard: false)
++ XCTAssertEqual(firstResult, .commandPosted)
++ var nextResult: TextDeliveryResult?
++ var nextStarted = false
++ let nextDelivery = Task { @MainActor in
++ nextStarted = true
++ nextResult = await coordinator.deliver("second", preserveTranscriptOnClipboard: false)
++ }
++ await self.waitUntil { nextStarted }
++ pasteboard.simulateExternalCopy("new user copy")
++ coordinator.runPendingSettlementForTesting()
++ XCTAssertEqual(pasteboard.text, "new user copy")
++ XCTAssertEqual(pasteboard.restoreCount, 0)
++ await self.waitUntil { nextResult != nil }
++ XCTAssertEqual(nextResult, .commandPosted)
++ XCTAssertEqual(pasteboard.text, "second")
++ coordinator.runPendingSettlementForTesting()
++ XCTAssertEqual(pasteboard.text, "new user copy")
++ nextDelivery.cancel()
++ }
++
++ func testHundredDeliveriesPreserveEveryPayloadThroughConsumptionWindow() async {
+ let pasteboard = FakePasteboardManager(text: "before")
+ let commandPoster = FakePasteCommandPoster()
+ let coordinator = PasteDeliveryCoordinator(
+ pasteboard: pasteboard,
+ commandPoster: commandPoster,
+ settlementDelayNanoseconds: .max
+ )
+
++ var consumedTexts: [String] = []
+ for index in 0..<100 {
+ let result = await coordinator.deliver("dictation \(index)", preserveTranscriptOnClipboard: false)
+ XCTAssertEqual(result, .commandPosted)
++ consumedTexts.append(pasteboard.text)
++ coordinator.runPendingSettlementForTesting()
+ }
- coordinator.runPendingSettlementForTesting()
+
++ XCTAssertEqual(consumedTexts, (0..<100).map { "dictation \($0)" })
+ XCTAssertEqual(commandPoster.postCount, 100)
+ XCTAssertEqual(pasteboard.text, "before")
- XCTAssertEqual(pasteboard.restoreCount, 1)
++ XCTAssertEqual(pasteboard.restoreCount, 100)
++ }
++
++ func testProductionSettlementTimerReleasesQueuedDelivery() async {
++ let pasteboard = FakePasteboardManager(text: "before")
++ let coordinator = PasteDeliveryCoordinator(
++ pasteboard: pasteboard,
++ commandPoster: FakePasteCommandPoster()
++ )
++ let firstResult = await coordinator.deliver("first", preserveTranscriptOnClipboard: false)
++ XCTAssertEqual(firstResult, .commandPosted)
++ let firstPostedAt = ProcessInfo.processInfo.systemUptime
++ var secondPostedAt: TimeInterval?
++ let secondDelivery = Task { @MainActor in
++ _ = await coordinator.deliver("second", preserveTranscriptOnClipboard: false)
++ secondPostedAt = ProcessInfo.processInfo.systemUptime
++ }
++ // Bounded wait also catches a slot that never releases after settlement.
++ for _ in 0..<200 where secondPostedAt == nil {
++ try? await Task.sleep(nanoseconds: 10_000_000)
++ }
++ XCTAssertNotNil(secondPostedAt)
++ if let secondPostedAt {
++ XCTAssertGreaterThanOrEqual(secondPostedAt - firstPostedAt, 0.45)
++ XCTAssertEqual(pasteboard.text, "second")
++ }
++ coordinator.runPendingSettlementForTesting()
++ secondDelivery.cancel()
+ }
+
+ func testClipboardRestorationUsesHalfSecondDelay() {
+ XCTAssertEqual(PasteDeliveryCoordinator.defaultSettlementDelayNanoseconds, 500_000_000)
+ }
+
- func testPasteKeyResolverUsesTheKeyThatProducesVInTheActiveLayout() {
- let resolvedKeyCode = KeyboardLayoutKeyCodeResolver.keyCode(
- for: "v",
- qwertyFallback: 0x09
- ) { keyCode in
- keyCode == 0x2a ? "v" : nil
++ func testOnlyAccessibilityFailureHasUserFacingMessage() {
++ XCTAssertEqual(TextDeliveryFailure.accessibilityNotTrusted.userFacingMessage, "Enable Accessibility to insert text")
++ let silentFailures: [TextDeliveryFailure] = [
++ .emptyText, .clipboardSnapshotFailed, .clipboardWriteFailed,
++ .pasteCommandFailed, .targetUnavailable, .targetRestoreFailed,
++ ]
++ for failure in silentFailures {
++ XCTAssertNil(failure.userFacingMessage, "Unexpected visible failure: \(failure)")
+ }
-
- XCTAssertEqual(resolvedKeyCode, 0x2a)
+ }
+
- func testPasteKeyResolverFallsBackWhenTheLayoutDoesNotExposeV() {
- let resolvedKeyCode = KeyboardLayoutKeyCodeResolver.keyCode(
- for: "v",
- qwertyFallback: 0x09,
- translatedScalar: { _ in nil }
- )
-
- XCTAssertEqual(resolvedKeyCode, 0x09)
++ func testSilentFailureClearsPriorErrorAndRetainsTranscript() {
++ let state = NotchContentState.shared
++ defer { state.clearTextDeliveryFailure() }
++ state.recordTextDeliveryFailure(.accessibilityNotTrusted, transcript: "earlier")
++ state.recordTextDeliveryFailure(.clipboardSnapshotFailed, transcript: "retained output")
++ XCTAssertFalse(state.isTextDeliveryFailureVisible)
++ XCTAssertEqual(state.textDeliveryFailureMessage, "")
++ XCTAssertEqual(state.textDeliveryFailureTranscript, "retained output")
+ }
+
+ func testRecoveryActivationNeverRequestsAllWindows() {
+ XCTAssertTrue(TypingService.recoveryActivationOptions.contains(.activateIgnoringOtherApps))
+ XCTAssertFalse(TypingService.recoveryActivationOptions.contains(.activateAllWindows))
+ }
+
+ func testDeliveryFailureStateKeepsTheExactTranscriptForRecovery() {
+ let state = NotchContentState.shared
+ defer { state.clearTextDeliveryFailure() }
+
- state.showTextDeliveryFailure(message: "Could not insert", transcript: "exact failed output")
++ state.recordTextDeliveryFailure(.accessibilityNotTrusted, transcript: "exact failed output")
+
+ XCTAssertTrue(state.isTextDeliveryFailureVisible)
- XCTAssertEqual(state.textDeliveryFailureMessage, "Could not insert")
++ XCTAssertEqual(state.textDeliveryFailureMessage, "Enable Accessibility to insert text")
+ XCTAssertEqual(state.textDeliveryFailureTranscript, "exact failed output")
+ }
+
+ private func waitUntil(_ condition: @MainActor () -> Bool) async {
+ for _ in 0..<100 where !condition() {
+ await Task.yield()
+ }
+ XCTAssertTrue(condition())
+ }
+ }
+
+ final class TextInsertionModeMigrationTests: XCTestCase {
+ private let modeKey = "TextInsertionMode"
+ private let migrationKey = "TextInsertionModeMigratedToReliablePasteV1"
+
+ func testMigrationOverridesExistingDirectModeOnce() throws {
+ let defaults = try self.makeDefaults()
+ defer { defaults.removePersistentDomain(forName: self.name) }
+ defaults.set(SettingsStore.TextInsertionMode.standard.rawValue, forKey: self.modeKey)
+
+ SettingsStore.migrateTextInsertionModeToReliablePasteIfNeeded(defaults: defaults)
+
+ XCTAssertEqual(defaults.string(forKey: self.modeKey), SettingsStore.TextInsertionMode.reliablePaste.rawValue)
+ XCTAssertTrue(defaults.bool(forKey: self.migrationKey))
+
+ defaults.set(SettingsStore.TextInsertionMode.standard.rawValue, forKey: self.modeKey)
+ SettingsStore.migrateTextInsertionModeToReliablePasteIfNeeded(defaults: defaults)
+
+ XCTAssertEqual(defaults.string(forKey: self.modeKey), SettingsStore.TextInsertionMode.standard.rawValue)
+ }
+
+ func testMigrationDefaultsUnsetModeToReliablePaste() throws {
+ let defaults = try self.makeDefaults()
+ defer { defaults.removePersistentDomain(forName: self.name) }
+
+ SettingsStore.migrateTextInsertionModeToReliablePasteIfNeeded(defaults: defaults)
+
+ XCTAssertEqual(defaults.string(forKey: self.modeKey), SettingsStore.TextInsertionMode.reliablePaste.rawValue)
+ XCTAssertTrue(defaults.bool(forKey: self.migrationKey))
+ }
+
+ func testRecommendedModeAppearsFirst() {
+ XCTAssertEqual(SettingsStore.TextInsertionMode.allCases.first, .reliablePaste)
+ XCTAssertEqual(SettingsStore.TextInsertionMode.reliablePaste.displayName, "Clipboard Paste (Recommended)")
+ XCTAssertEqual(SettingsStore.TextInsertionMode.standard.displayName, "Direct Paste")
+ }
+
+ private func makeDefaults() throws -> UserDefaults {
+ let defaults = try XCTUnwrap(UserDefaults(suiteName: self.name))
+ defaults.removePersistentDomain(forName: self.name)
+ return defaults
+ }
+ }
+
+ @MainActor
+ private final class FakePasteboardManager: PasteboardManaging {
+ private(set) var text: String
+ private(set) var restoreCount = 0
+ private(set) var intentionalWriteCount = 0
+ private(set) var temporaryWriteCount = 0
+ private(set) var isTemporary = false
- private let snapshotSucceeds: Bool
++ var snapshotSucceeds: Bool
++ var onTemporaryWrite: (() -> Void)?
+ private let temporaryWriteSucceeds: Bool
+ private var sessionID: String?
+
+ init(
+ text: String,
+ snapshotSucceeds: Bool = true,
+ temporaryWriteSucceeds: Bool = true
+ ) {
+ self.text = text
+ self.snapshotSucceeds = snapshotSucceeds
+ self.temporaryWriteSucceeds = temporaryWriteSucceeds
+ }
+
+ func captureSnapshot() -> PasteboardSnapshot? {
+ guard self.snapshotSucceeds else { return nil }
+ return PasteboardSnapshot(items: [
+ .init(representations: [
+ .init(type: .string, data: Data(self.text.utf8)),
+ ]),
+ ])
+ }
+
+ func writeTemporaryText(_ text: String, sessionID: String) -> Bool {
+ self.temporaryWriteCount += 1
+ self.text = text
+ self.sessionID = sessionID
+ self.isTemporary = true
++ self.onTemporaryWrite?()
+ return self.temporaryWriteSucceeds
+ }
+
+ func writeIntentionalText(_ text: String) -> Bool {
+ self.intentionalWriteCount += 1
+ self.text = text
+ self.sessionID = nil
+ self.isTemporary = false
+ return true
+ }
+
+ func isOwned(sessionID: String, expectedText: String) -> Bool {
+ self.sessionID == sessionID && self.text == expectedText
+ }
+
+ func restore(_ snapshot: PasteboardSnapshot) -> Bool {
+ self.restoreCount += 1
+ self.sessionID = nil
+ self.isTemporary = false
+ guard let data = snapshot.items.first?.representations.first(where: { $0.type == .string })?.data,
+ let restoredText = String(data: data, encoding: .utf8)
+ else {
+ self.text = ""
+ return snapshot.items.isEmpty
+ }
+ self.text = restoredText
+ return true
+ }
+
++ func restoreTemporarySnapshot(
++ _ snapshot: PasteboardSnapshot,
++ sessionID: String,
++ expectedText: String
++ ) -> Bool {
++ guard self.isOwned(sessionID: sessionID, expectedText: expectedText) else { return false }
++ return self.restore(snapshot)
++ }
++
+ func simulateExternalCopy(_ text: String) {
+ self.text = text
+ self.sessionID = nil
+ self.isTemporary = false
+ }
+ }
+
+ @MainActor
+ private final class FakePasteCommandPoster: PasteCommandPosting {
+ private let succeeds: Bool
+ private(set) var postCount = 0
++ var onPost: (() -> Void)?
+
+ init(succeeds: Bool = true) {
+ self.succeeds = succeeds
+ }
+
+ func postGlobalPasteCommand() async -> Bool {
+ self.postCount += 1
++ self.onPost?()
+ return self.succeeds
+ }
+ }
+
+ @MainActor
+ private final class SuspendingFakePasteCommandPoster: PasteCommandPosting {
+ private(set) var postCount = 0
+ private(set) var firstPostIsSuspended = false
+ private var firstPostContinuation: CheckedContinuation<Void, Never>?
+
+ func postGlobalPasteCommand() async -> Bool {
+ self.postCount += 1
+ guard self.postCount == 1 else { return true }
+
+ self.firstPostIsSuspended = true
+ await withCheckedContinuation { continuation in
+ self.firstPostContinuation = continuation
+ }
+ return true
+ }
+
+ func resumeFirstPost() {
+ let continuation = self.firstPostContinuation
+ self.firstPostContinuation = nil
+ continuation?.resume()
+ }
+ }
diff --cc Tests/FluidDictationIntegrationTests/TypingServiceTransientPasteboardTests.swift
index aeedc61e,36b479fa..f77a0d1b
--- a/Tests/FluidDictationIntegrationTests/TypingServiceTransientPasteboardTests.swift
+++ b/Tests/FluidDictationIntegrationTests/TypingServiceTransientPasteboardTests.swift
@@@ -76,7 -90,336 +90,382 @@@ final class TypingServiceTransientPaste
)
XCTAssertFalse(
options.contains(.activateAllWindows),
- "Restoring focus must not raise every window of the target app (issue #748)"
+ "Recovery must not raise every window of the target app (issue #748)"
+ )
+ }
+
+ func testIntentionalClipboardWriteIsHistoryVisible() throws {
+ let pasteboard = self.makePasteboard()
+ defer { pasteboard.releaseGlobally() }
+
+ XCTAssertTrue(SystemPasteboardManager(pasteboard: pasteboard).writeIntentionalText("keep me"))
+
+ let item = try XCTUnwrap(pasteboard.pasteboardItems?.first)
+ let types = item.types.map(\.rawValue)
+ XCTAssertEqual(item.string(forType: .string), "keep me")
+ XCTAssertFalse(types.contains("org.nspasteboard.TransientType"))
+ XCTAssertFalse(types.contains("org.nspasteboard.AutoGeneratedType"))
+ XCTAssertFalse(types.contains("org.nspasteboard.ConcealedType"))
+ XCTAssertFalse(types.contains { $0.hasSuffix(".PasteSession") })
+ }
+
+ func testSnapshotRestoresEveryRepresentation() throws {
+ let pasteboard = self.makePasteboard()
+ defer { pasteboard.releaseGlobally() }
+ let customType = NSPasteboard.PasteboardType("com.fluidvoice.tests.custom")
+ let customData = Data([0x01, 0x02, 0x03])
+ let originalItem = NSPasteboardItem()
+ XCTAssertTrue(originalItem.setString("original", forType: .string))
+ XCTAssertTrue(originalItem.setData(customData, forType: customType))
+ let secondItem = NSPasteboardItem()
+ XCTAssertTrue(secondItem.setString("second", forType: .string))
+ XCTAssertTrue(pasteboard.writeObjects([originalItem, secondItem]))
+ let originalItems = try XCTUnwrap(pasteboard.pasteboardItems)
+ let originalTypes = originalItems.map(\.types)
+ let originalRepresentations = originalItems.map { item in
+ item.types.map { type in item.data(forType: type) }
+ }
+
+ let manager = SystemPasteboardManager(pasteboard: pasteboard)
+ let snapshot = try XCTUnwrap(manager.captureSnapshot())
+ XCTAssertTrue(manager.writeTemporaryText("temporary", sessionID: "session"))
+ XCTAssertTrue(manager.restore(snapshot))
+
+ let restoredItems = try XCTUnwrap(pasteboard.pasteboardItems)
+ XCTAssertEqual(restoredItems.count, 2)
+ for (restoredItem, sourceTypes) in zip(restoredItems, originalTypes) {
+ XCTAssertEqual(Array(restoredItem.types.prefix(sourceTypes.count)), sourceTypes)
+ XCTAssertTrue(restoredItem.types.contains(Self.transientType))
+ XCTAssertTrue(restoredItem.types.contains(Self.autoGeneratedType))
+ }
+ XCTAssertEqual(
+ zip(restoredItems, originalTypes).map { item, types in
+ types.map { type in item.data(forType: type) }
+ },
+ originalRepresentations
+ )
+ let restoredItem = restoredItems[0]
+ XCTAssertEqual(restoredItem.string(forType: .string), "original")
+ XCTAssertEqual(restoredItem.data(forType: customType), customData)
+ XCTAssertEqual(restoredItems[1].string(forType: .string), "second")
+ }
+
+ func testSnapshotRestoresImageBeforeTextInOriginalPreferenceOrder() throws {
+ let pasteboard = self.makePasteboard()
+ defer { pasteboard.releaseGlobally() }
+
+ let bitmap = try XCTUnwrap(
+ NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: 2,
+ pixelsHigh: 2,
+ bitsPerSample: 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .deviceRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0
+ )
+ )
+ bitmap.setColor(NSColor(deviceRed: 0, green: 0, blue: 1, alpha: 1), atX: 0, y: 0)
+ bitmap.setColor(NSColor(deviceRed: 1, green: 0, blue: 0, alpha: 1), atX: 1, y: 0)
+ bitmap.setColor(NSColor(deviceRed: 0, green: 1, blue: 0, alpha: 1), atX: 0, y: 1)
+ bitmap.setColor(NSColor(deviceRed: 1, green: 1, blue: 1, alpha: 1), atX: 1, y: 1)
+ let imageData = try XCTUnwrap(bitmap.representation(using: .tiff, properties: [:]))
+ let originalItem = NSPasteboardItem()
+ XCTAssertTrue(originalItem.setData(imageData, forType: .tiff))
+ XCTAssertTrue(originalItem.setString("image text fallback", forType: .string))
+ XCTAssertTrue(pasteboard.writeObjects([originalItem]))
+ let originalTypes = try XCTUnwrap(pasteboard.pasteboardItems?.first?.types)
+ XCTAssertEqual(originalTypes.first, .tiff)
+
+ let manager = SystemPasteboardManager(pasteboard: pasteboard)
+ let snapshot = try XCTUnwrap(manager.captureSnapshot())
+ XCTAssertEqual(snapshot.items.first?.representations.map(\.type), originalTypes)
+ XCTAssertTrue(manager.writeTemporaryText("temporary", sessionID: "session"))
+ XCTAssertTrue(manager.restore(snapshot))
+
+ let restoredItem = try XCTUnwrap(pasteboard.pasteboardItems?.first)
+ XCTAssertEqual(Array(restoredItem.types.prefix(originalTypes.count)), originalTypes)
+ XCTAssertEqual(restoredItem.data(forType: .tiff), imageData)
+ XCTAssertEqual(restoredItem.string(forType: .string), "image text fallback")
+ let restoredImageData = try XCTUnwrap(restoredItem.data(forType: .tiff))
+ XCTAssertNotNil(NSImage(data: restoredImageData))
+ }
+
+ func testSnapshotAddsPortableImageBeforeFilenameForICNSOnlyClipboard() throws {
+ let pasteboard = self.makePasteboard()
+ defer { pasteboard.releaseGlobally() }
+
+ let bitmap = try XCTUnwrap(
+ NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: 2,
+ pixelsHigh: 2,
+ bitsPerSample: 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .deviceRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0
+ )
+ )
+ bitmap.setColor(NSColor(deviceRed: 0, green: 0, blue: 1, alpha: 1), atX: 0, y: 0)
+ let sourceImageData = try XCTUnwrap(bitmap.representation(using: .png, properties: [:]))
+ let icnsType = NSPasteboard.PasteboardType("com.apple.icns")
+ let originalItem = NSPasteboardItem()
+ XCTAssertTrue(originalItem.setString("Example.icns", forType: .string))
+ XCTAssertTrue(originalItem.setData(sourceImageData, forType: icnsType))
+ XCTAssertTrue(pasteboard.writeObjects([originalItem]))
+
+ let manager = SystemPasteboardManager(pasteboard: pasteboard)
+ let snapshot = try XCTUnwrap(manager.captureSnapshot())
+ XCTAssertNotNil(snapshot.items.first?.portableImage)
+ XCTAssertTrue(manager.writeTemporaryText("temporary", sessionID: "session"))
+ XCTAssertTrue(manager.restore(snapshot))
+
+ let externalReader = NSPasteboard(name: pasteboard.name)
+ let restoredItem = try XCTUnwrap(externalReader.pasteboardItems?.first)
+ XCTAssertEqual(restoredItem.types.first, .png)
+ XCTAssertEqual(restoredItem.string(forType: .string), "Example.icns")
+ XCTAssertEqual(restoredItem.data(forType: icnsType), sourceImageData)
+ XCTAssertNotNil(restoredItem.data(forType: .png).flatMap(NSImage.init(data:)))
+ XCTAssertTrue(restoredItem.types.contains(Self.transientType))
+ XCTAssertTrue(restoredItem.types.contains(Self.autoGeneratedType))
+ }
+
+ func testSnapshotAddsPortableImageForImageFileURL() throws {
+ let pasteboard = self.makePasteboard()
+ defer { pasteboard.releaseGlobally() }
+
+ let temporaryDirectory = FileManager.default.temporaryDirectory
+ .appendingPathComponent("fluidvoice-image-pasteboard-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: temporaryDirectory, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: temporaryDirectory) }
+
+ let bitmap = try XCTUnwrap(
+ NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: 1,
+ pixelsHigh: 1,
+ bitsPerSample: 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .deviceRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0
+ )
)
+ bitmap.setColor(NSColor(deviceRed: 1, green: 0, blue: 0, alpha: 1), atX: 0, y: 0)
+ let sourceImageData = try XCTUnwrap(bitmap.representation(using: .png, properties: [:]))
+ let imageURL = temporaryDirectory.appendingPathComponent("Example.png")
+ try sourceImageData.write(to: imageURL)
+
+ bitmap.setColor(NSColor(deviceRed: 0, green: 0, blue: 1, alpha: 1), atX: 0, y: 0)
+ let iconData = try XCTUnwrap(bitmap.representation(using: .png, properties: [:]))
+ let icnsType = NSPasteboard.PasteboardType("com.apple.icns")
+ let originalItem = NSPasteboardItem()
+ XCTAssertTrue(originalItem.setString(imageURL.absoluteString, forType: .fileURL))
+ XCTAssertTrue(originalItem.setString("Example.png", forType: .string))
+ XCTAssertTrue(originalItem.setData(iconData, forType: icnsType))
+ XCTAssertTrue(pasteboard.writeObjects([originalItem]))
+
+ let manager = SystemPasteboardManager(pasteboard: pasteboard)
+ let snapshot = try XCTUnwrap(manager.captureSnapshot())
+ XCTAssertNotNil(snapshot.items.first?.portableImage)
+ XCTAssertTrue(manager.writeTemporaryText("temporary", sessionID: "session"))
+ XCTAssertTrue(manager.restore(snapshot))
+
+ let restoredItem = try XCTUnwrap(pasteboard.pasteboardItems?.first)
+ XCTAssertEqual(Array(restoredItem.types.prefix(2)), [.fileURL, .png])
+ XCTAssertEqual(restoredItem.string(forType: .fileURL), imageURL.absoluteString)
+ XCTAssertEqual(restoredItem.data(forType: icnsType), iconData)
+ XCTAssertNotEqual(restoredItem.data(forType: .png), iconData)
+ XCTAssertEqual(restoredItem.data(forType: .png), sourceImageData)
+
+ let restoredPNG = try XCTUnwrap(restoredItem.data(forType: .png))
+ let restoredBitmap = try XCTUnwrap(NSBitmapImageRep(data: restoredPNG))
+ let restoredColor = try XCTUnwrap(restoredBitmap.colorAt(x: 0, y: 0)?.usingColorSpace(.deviceRGB))
+ XCTAssertGreaterThan(restoredColor.redComponent, 0.8)
+ XCTAssertGreaterThan(restoredColor.redComponent, restoredColor.greenComponent + 0.5)
+ XCTAssertGreaterThan(restoredColor.redComponent, restoredColor.blueComponent + 0.5)
+ }
+
+ func testSnapshotUsesEmbeddedImageWhenImageFileURLCannotBeRead() throws {
+ let pasteboard = self.makePasteboard()
+ defer { pasteboard.releaseGlobally() }
+
+ let bitmap = try XCTUnwrap(
+ NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: 1,
+ pixelsHigh: 1,
+ bitsPerSample: 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .deviceRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0
+ )
+ )
+ let iconData = try XCTUnwrap(bitmap.representation(using: .png, properties: [:]))
+ let icnsType = NSPasteboard.PasteboardType("com.apple.icns")
+ let originalItem = NSPasteboardItem()
+ XCTAssertTrue(originalItem.setString("file:///.file/id=123456.789", forType: .fileURL))
+ XCTAssertTrue(originalItem.setString("Example.png", forType: .string))
+ XCTAssertTrue(originalItem.setData(iconData, forType: icnsType))
+ XCTAssertTrue(pasteboard.writeObjects([originalItem]))
+
+ let manager = SystemPasteboardManager(pasteboard: pasteboard)
+ let snapshot = try XCTUnwrap(manager.captureSnapshot())
+ XCTAssertNotNil(snapshot.items.first?.portableImage)
+ XCTAssertTrue(manager.writeTemporaryText("temporary", sessionID: "session"))
+ XCTAssertTrue(manager.restore(snapshot))
+
+ let externalReader = NSPasteboard(name: pasteboard.name)
+ let restoredItem = try XCTUnwrap(externalReader.pasteboardItems?.first)
+ XCTAssertTrue(restoredItem.types.contains(.png))
+ XCTAssertLessThan(
+ try XCTUnwrap(restoredItem.types.firstIndex(of: .png)),
+ try XCTUnwrap(restoredItem.types.firstIndex(of: .string))
+ )
+ XCTAssertNotNil(restoredItem.data(forType: .png).flatMap(NSImage.init(data:)))
+ }
+
+ func testSnapshotDoesNotTurnNonImageFileIconIntoImage() throws {
+ let pasteboard = self.makePasteboard()
+ defer { pasteboard.releaseGlobally() }
+
+ let bitmap = try XCTUnwrap(
+ NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: 1,
+ pixelsHigh: 1,
+ bitsPerSample: 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .deviceRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0
+ )
+ )
+ let iconData = try XCTUnwrap(bitmap.representation(using: .png, properties: [:]))
+ let icnsType = NSPasteboard.PasteboardType("com.apple.icns")
+ let originalItem = NSPasteboardItem()
+ XCTAssertTrue(originalItem.setString("file:///tmp/Example.txt", forType: .fileURL))
+ XCTAssertTrue(originalItem.setString("Example.txt", forType: .string))
+ XCTAssertTrue(originalItem.setData(iconData, forType: icnsType))
+ XCTAssertTrue(pasteboard.writeObjects([originalItem]))
+
+ let manager = SystemPasteboardManager(pasteboard: pasteboard)
+ let snapshot = try XCTUnwrap(manager.captureSnapshot())
+ XCTAssertTrue(manager.writeTemporaryText("temporary", sessionID: "session"))
+ XCTAssertTrue(manager.restore(snapshot))
+
+ let restoredItem = try XCTUnwrap(pasteboard.pasteboardItems?.first)
+ XCTAssertFalse(restoredItem.types.contains(.png))
+ XCTAssertEqual(restoredItem.string(forType: .fileURL), "file:///tmp/Example.txt")
+ XCTAssertEqual(restoredItem.data(forType: icnsType), iconData)
+ }
+
+ func testLargeRepresentationIsSnapshottedAndRestoredWithoutSizeLimit() throws {
+ let pasteboard = self.makePasteboard()
+ defer { pasteboard.releaseGlobally() }
+ let customType = NSPasteboard.PasteboardType("com.fluidvoice.tests.large")
+ let originalData = Data(repeating: 0xab, count: 20 * 1024 * 1024)
+ let originalItem = NSPasteboardItem()
+ XCTAssertTrue(originalItem.setData(originalData, forType: customType))
+ XCTAssertTrue(pasteboard.writeObjects([originalItem]))
+
+ let manager = SystemPasteboardManager(pasteboard: pasteboard)
+ let snapshot = try XCTUnwrap(manager.captureSnapshot())
+ XCTAssertEqual(snapshot.items.first?.representations.first?.data, originalData)
+ XCTAssertTrue(manager.writeTemporaryText("temporary", sessionID: "session"))
+ XCTAssertTrue(manager.restore(snapshot))
+
+ XCTAssertEqual(pasteboard.data(forType: customType), originalData)
+ }
+
+ func testMoreThanOneHundredItemsAreSnapshottedAndRestored() throws {
+ let pasteboard = self.makePasteboard()
+ defer { pasteboard.releaseGlobally() }
+ let originalItems = (0..<101).map { index in
+ let item = NSPasteboardItem()
+ XCTAssertTrue(item.setString("item \(index)", forType: .string))
+ return item
+ }
+ XCTAssertTrue(pasteboard.writeObjects(originalItems))
+
+ let manager = SystemPasteboardManager(pasteboard: pasteboard)
+ let snapshot = try XCTUnwrap(manager.captureSnapshot())
+ XCTAssertEqual(snapshot.items.count, 101)
+ XCTAssertTrue(manager.writeTemporaryText("temporary", sessionID: "session"))
+ XCTAssertTrue(manager.restore(snapshot))
+
+ let restoredItems = try XCTUnwrap(pasteboard.pasteboardItems)
+ XCTAssertEqual(restoredItems.count, 101)
+ XCTAssertEqual(restoredItems.first?.string(forType: .string), "item 0")
+ XCTAssertEqual(restoredItems.last?.string(forType: .string), "item 100")
+ }
+
+ private func makePasteboard() -> NSPasteboard {
+ let name = NSPasteboard.Name("com.fluidvoice.tests.transient.\(UUID().uuidString)")
+ let pasteboard = NSPasteboard(name: name)
+ pasteboard.clearContents()
+ return pasteboard
+ }
+
+ private static let transientType = NSPasteboard.PasteboardType("org.nspasteboard.TransientType")
+ private static let autoGeneratedType = NSPasteboard.PasteboardType("org.nspasteboard.AutoGeneratedType")
+ }
++
++@MainActor
++final class PasteboardOwnershipRegressionTests: XCTestCase {
++ func testFailureRestorationPreservesNewerCopy() throws {
++ let pasteboard = NSPasteboard.withUniqueName()
++ defer { pasteboard.releaseGlobally() }
++ pasteboard.setString("original", forType: .string)
++ let manager = SystemPasteboardManager(pasteboard: pasteboard)
++ let snapshot = try XCTUnwrap(manager.captureSnapshot())
++ XCTAssertTrue(manager.writeTemporaryText("dictation", sessionID: "session"))
++ pasteboard.clearContents()
++ pasteboard.setString("new user copy", forType: .string)
++ XCTAssertFalse(manager.restoreTemporarySnapshot(snapshot, sessionID: "session", expectedText: "dictation"))
++ XCTAssertEqual(pasteboard.string(forType: .string), "new user copy")
++ }
++
++ func testMatchingMarkersDoNotOverrideNewerClipboardGeneration() throws {
++ let pasteboard = NSPasteboard.withUniqueName()
++ defer { pasteboard.releaseGlobally() }
++ pasteboard.setString("original", forType: .string)
++ let manager = SystemPasteboardManager(pasteboard: pasteboard)
++ let snapshot = try XCTUnwrap(manager.captureSnapshot())
++ XCTAssertTrue(manager.writeTemporaryText("dictation", sessionID: "session"))
++ let temporary = try XCTUnwrap(pasteboard.pasteboardItems?.first)
++ let copy = NSPasteboardItem()
++ for type in temporary.types {
++ try copy.setData(XCTUnwrap(temporary.data(forType: type)), forType: type)
++ }
++ pasteboard.clearContents()
++ XCTAssertTrue(pasteboard.writeObjects([copy]))
++ XCTAssertFalse(manager.isOwned(sessionID: "session", expectedText: "dictation"))
++ XCTAssertFalse(manager.restoreTemporarySnapshot(snapshot, sessionID: "session", expectedText: "dictation"))
++ XCTAssertEqual(pasteboard.string(forType: .string), "dictation")
++ }
++
++ func testUnchangedTemporaryClipboardCanBeRestored() throws {
++ let pasteboard = NSPasteboard.withUniqueName()
++ defer { pasteboard.releaseGlobally() }
++ pasteboard.setString("original", forType: .string)
++ let manager = SystemPasteboardManager(pasteboard: pasteboard)
++ let snapshot = try XCTUnwrap(manager.captureSnapshot())
++ XCTAssertTrue(manager.writeTemporaryText("dictation", sessionID: "session"))
++ XCTAssertTrue(manager.restoreTemporarySnapshot(snapshot, sessionID: "session", expectedText: "dictation"))
++ XCTAssertEqual(pasteboard.string(forType: .string), "original")
+ }
+}