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

Make dictation paste more reliable (#1267)

ALTIC5b7c420558bb
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 3e84dc64..a2a2caf9 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -88,37 +88,10 @@ jobs:
- name: Show Xcode version
run: xcodebuild -version
- - name: Run standalone onboarding regressions
- run: sh Tests/run_onboarding_tests.sh
-
- - name: Run release highlights regressions
- run: sh Tests/run_release_highlights_tests.sh
-
- - name: Run history decode recovery regressions
- run: sh Tests/run_history_decode_recovery_tests.sh
-
- - name: Run settings backup concurrency regressions
- run: python3 Tests/run_settings_backup_concurrency_tests.py
-
- - name: Run meeting backup refresh regressions
- run: python3 Tests/run_meeting_backup_refresh_tests.py
-
- # Tiny Whisper GGUF output is nondeterministic on hosted macOS runners.
- # Keep this E2E assertion in the suite for local validation, but skip it in CI.
- - name: Build and test (excluding flaky Tiny Whisper E2E)
- run: |
- set -o pipefail
- mkdir -p build/test-results
- xcodebuild test \
- -project Fluid.xcodeproj \
- -scheme Fluid \
- -destination 'platform=macOS,arch=arm64' \
- -resultBundlePath build/test-results/Fluid.xcresult \
- -skip-testing:FluidDictationIntegrationTests/DictationE2ETests/testDictationEndToEnd_whisperTiny_transcribesFixture \
- CODE_SIGN_IDENTITY="" \
- CODE_SIGNING_REQUIRED=NO \
- CODE_SIGNING_ALLOWED=NO \
- 2>&1 | tee build/test-results/xcodebuild.log | xcpretty
+ - name: Run shared CI checks
+ env:
+ CI_RESULT_DIR: build/test-results
+ run: bash Tests/run_ci_checks.sh
- name: Collect crash reports
if: always()
diff --git a/Sources/Fluid/AppDelegate.swift b/Sources/Fluid/AppDelegate.swift
index f7bd1f34..51ed2eeb 100644
--- a/Sources/Fluid/AppDelegate.swift
+++ b/Sources/Fluid/AppDelegate.swift
@@ -79,6 +79,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele
// Bring up file logging + crash handlers immediately during launch.
_ = FileLogger.shared
TypingService.startKeyboardLayoutTracking()
+ DictationAccessibilityPreparation.shared.start()
_ = TranscriptionHistoryStore.shared
#if arch(arm64)
Task {
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index 5d47d865..3eeee98e 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -3672,11 +3672,11 @@ final class SettingsStore: ObservableObject {
}
/// Whether a card is shown when a paste could not be confirmed in the target field.
- /// Off by default: the read-back is a guess, and a wrong guess interrupts for nothing.
+ /// Enabled by default for strong unchanged-field results; explicit user choices persist.
var showPasteCheckAlerts: Bool {
get {
let value = self.defaults.object(forKey: Keys.showPasteCheckAlerts)
- return value as? Bool ?? false
+ return value as? Bool ?? true
}
set {
objectWillChange.send()
diff --git a/Sources/Fluid/Services/DictationAccessibilityPreparation.swift b/Sources/Fluid/Services/DictationAccessibilityPreparation.swift
new file mode 100644
index 00000000..598c7b53
--- /dev/null
+++ b/Sources/Fluid/Services/DictationAccessibilityPreparation.swift
@@ -0,0 +1,97 @@
+import AppKit
+import ApplicationServices
+
+/// Requests Electron's documented accessibility support before a dictation
+/// captures its destination. Never changes focus, reads text or sends input.
+@MainActor
+final class DictationAccessibilityPreparation {
+ static let shared = DictationAccessibilityPreparation()
+ private let worker = DictationAccessibilityPreparationWorker()
+ private var observer: NSObjectProtocol?
+ private var pending: Task<Void, Never>?
+
+ nonisolated deinit {}
+
+ func start() {
+ guard self.observer == nil else { return }
+ self.prepare(NSWorkspace.shared.frontmostApplication)
+ self.observer = NSWorkspace.shared.notificationCenter.addObserver(
+ forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .main
+ ) { [weak self] notification in
+ let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication
+ MainActor.assumeIsolated { self?.prepare(app) }
+ }
+ }
+
+ private func prepare(_ app: NSRunningApplication?) {
+ self.pending?.cancel()
+ guard let app, app.processIdentifier != getpid(), let bundleURL = app.bundleURL else { return }
+ let request = DictationAccessibilityPreparationWorker.Request(
+ pid: app.processIdentifier, launchedAt: app.launchDate, bundleURL: bundleURL
+ )
+ self.pending = Task(priority: .utility) {
+ let result = await self.worker.prepare(request)
+ guard !Task.isCancelled, result == .enabled else { return }
+ DebugLogger.shared.info("FOCUS_ACCESSIBILITY enabled pid=\(request.pid)", source: "DictationAccessibilityPreparation")
+ }
+ }
+}
+
+actor DictationAccessibilityPreparationWorker {
+ nonisolated struct Request: Hashable, Sendable {
+ let pid: pid_t
+ let launchedAt: Date?
+ let bundleURL: URL
+ }
+
+ nonisolated enum Outcome: Equatable, Sendable {
+ case enabled, unsupported, untrusted, stale, cancelled
+ case failed(Int32)
+ }
+
+ private let isTrusted: @Sendable () -> Bool
+ private let supportsPreparation: @Sendable (Request) -> Bool
+ private let enable: @Sendable (Request) -> Outcome
+ private let capacity: Int
+ private var prepared: [Request: Outcome] = [:]
+ private var order: [Request] = []
+
+ init(
+ capacity: Int = 64,
+ isTrusted: @escaping @Sendable () -> Bool = { AXIsProcessTrusted() },
+ supportsPreparation: @escaping @Sendable (Request) -> Bool = { request in
+ FileManager.default.fileExists(atPath: request.bundleURL.appendingPathComponent("Contents/Frameworks/Electron Framework.framework").path)
+ },
+ enable: @escaping @Sendable (Request) -> Outcome = { request in
+ guard let app = NSRunningApplication(processIdentifier: request.pid),
+ !app.isTerminated, app.bundleURL == request.bundleURL, app.launchDate == request.launchedAt
+ else { return .stale }
+ let element = AXUIElementCreateApplication(request.pid)
+ AXUIElementSetMessagingTimeout(element, 0.15)
+ let result = AXUIElementSetAttributeValue(element, "AXManualAccessibility" as CFString, kCFBooleanTrue)
+ return result == .success ? .enabled : .failed(result.rawValue)
+ }
+ ) {
+ self.capacity = max(1, capacity)
+ self.isTrusted = isTrusted
+ self.supportsPreparation = supportsPreparation
+ self.enable = enable
+ }
+
+ func prepare(_ request: Request) -> Outcome {
+ guard !Task.isCancelled else { return .cancelled }
+ guard request.pid > 0, request.pid != getpid() else { return .stale }
+ // A missing permission is not cached: granting it must permit a later attempt.
+ guard self.isTrusted() else { return .untrusted }
+ if let previous = self.prepared[request] { return previous }
+ let result = self.supportsPreparation(request) ? self.enable(request) : .unsupported
+ // Failed requests may succeed on the next activation; never poll or retry
+ // during a recording. Successful/unsupported processes are bounded in memory.
+ if result == .enabled || result == .unsupported {
+ if self.order.count == self.capacity { self.prepared.removeValue(forKey: self.order.removeFirst()) }
+ self.order.append(request)
+ self.prepared[request] = result
+ }
+ return result
+ }
+}
diff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swift
index 79fa8990..72cefd77 100644
--- a/Sources/Fluid/Services/MenuBarManager.swift
+++ b/Sources/Fluid/Services/MenuBarManager.swift
@@ -151,8 +151,10 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
.store(in: &self.cancellables)
NotificationCenter.default.addObserver(forName: .fluidPasteNotLanded, object: nil, queue: .main) { [weak self] note in
- guard let transcript = note.userInfo?["transcript"] as? String else { return }
- Task { @MainActor [weak self] in self?.showPasteNotLandedFailure(transcript: transcript) }
+ guard let transcript = note.userInfo?["transcript"] as? String,
+ let verificationID = note.userInfo?["verificationID"] as? UInt64,
+ let postedAt = note.userInfo?["postedAt"] as? TimeInterval else { return }
+ Task { @MainActor [weak self] in self?.showPasteNotLandedFailure(transcript: transcript, verificationID: verificationID, postedAt: postedAt) }
}
// Subscribe to recording state changes
@@ -497,8 +499,13 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
/// A verified non-landing paste re-presents the overlay in its failure
/// state so the transcript can be copied.
- func showPasteNotLandedFailure(transcript: String) {
- guard !self.overlayVisible, !self.isProcessingActive, self.asrService?.isRunning != true else { return }
+ func showPasteNotLandedFailure(transcript: String, verificationID: UInt64, postedAt: TimeInterval) {
+ guard PasteRecoveryPresentationPolicy.shared.claim(
+ verificationID,
+ alertsEnabled: SettingsStore.shared.showPasteCheckAlerts,
+ isBusy: self.overlayVisible || self.isProcessingActive || self.asrService?.isRunning == true,
+ userActed: PasteVerifier.userActedAfterPaste(secondsSinceLastInput: PasteVerifier.secondsSinceLastUserInput(), secondsSincePaste: ProcessInfo.processInfo.systemUptime - postedAt)
+ ) else { return }
DeliveryFailureOverlayController.shared.show(kind: .pasteNotLanded, transcript: transcript)
}
@@ -510,6 +517,8 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
return
}
+ PasteRecoveryPresentationPolicy.shared.beginDelivery()
+
self.pendingHideOperation?.cancel()
self.pendingHideOperation = nil
self.pendingShowOperation?.cancel()
diff --git a/Sources/Fluid/Services/PasteDeliveryCoordinator.swift b/Sources/Fluid/Services/PasteDeliveryCoordinator.swift
index 0bcef16b..0ee9478e 100644
--- a/Sources/Fluid/Services/PasteDeliveryCoordinator.swift
+++ b/Sources/Fluid/Services/PasteDeliveryCoordinator.swift
@@ -80,10 +80,48 @@ protocol PasteboardManaging: AnyObject {
func restore(_ snapshot: PasteboardSnapshot) -> Bool
func restoreTemporarySnapshot(_ snapshot: PasteboardSnapshot, sessionID: String, expectedText: String) -> Bool
func recordAudit(_ event: String, detail: String)
+ func observeTemporaryTextRead(sessionID: String, onRead: @escaping @MainActor @Sendable (TimeInterval) -> Void) -> Bool
}
extension PasteboardManaging {
func recordAudit(_: String, detail _: String) {}
+ func observeTemporaryTextRead(sessionID _: String, onRead _: @escaping @MainActor @Sendable (TimeInterval) -> Void) -> Bool { false }
+}
+
+/// Supplies immutable text on demand. A read receipt means somebody requested
+/// the data, not that the intended editor inserted it. Never use it to retry.
+/// AppKit may request data off the main thread; only receipt bookkeeping is locked.
+private final nonisolated class TemporaryPasteboardTextProvider: NSObject, NSPasteboardItemDataProvider, @unchecked Sendable {
+ let text: String
+ private let lock = NSLock()
+ private var firstReadAt: TimeInterval?
+ private var readHandler: (@MainActor @Sendable (TimeInterval) -> Void)?
+
+ init(text: String) {
+ self.text = text
+ }
+
+ func observe(_ handler: @escaping @MainActor @Sendable (TimeInterval) -> Void) {
+ self.lock.lock()
+ self.readHandler = handler
+ let readAt = self.firstReadAt
+ self.lock.unlock()
+ if let readAt { Task { @MainActor in handler(readAt) } }
+ }
+
+ func pasteboard(_: NSPasteboard?, item: NSPasteboardItem, provideDataForType type: NSPasteboard.PasteboardType) {
+ guard type == .string, item.setString(self.text, forType: type) else { return }
+ self.lock.lock()
+ guard self.firstReadAt == nil else {
+ self.lock.unlock()
+ return
+ }
+ let readAt = ProcessInfo.processInfo.systemUptime
+ self.firstReadAt = readAt
+ let handler = self.readHandler
+ self.lock.unlock()
+ if let handler { Task { @MainActor in handler(readAt) } }
+ }
}
@MainActor
@@ -113,6 +151,7 @@ final class SystemPasteboardManager: PasteboardManaging {
private let pasteboard: NSPasteboard
private var temporaryWrite: (sessionID: String, changeCount: Int)?
+ private var temporaryTextProvider: (sessionID: String, provider: TemporaryPasteboardTextProvider)?
init(pasteboard: NSPasteboard = .general) {
self.pasteboard = pasteboard
@@ -249,7 +288,8 @@ final class SystemPasteboardManager: PasteboardManaging {
func writeTemporaryText(_ text: String, sessionID: String) -> Bool {
let item = NSPasteboardItem()
- guard item.setString(text, forType: .string),
+ let provider = TemporaryPasteboardTextProvider(text: text)
+ guard item.setDataProvider(provider, forTypes: [.string]),
item.setString(Bundle.main.bundleIdentifier ?? "com.FluidApp.Fluid", forType: Self.sourceType),
item.setData(Data(), forType: Self.transientType),
item.setData(Data(), forType: Self.autoGeneratedType),
@@ -262,6 +302,7 @@ final class SystemPasteboardManager: PasteboardManaging {
ClipboardAudit.record("temporary_begin", pasteboard: self.pasteboard, detail: "session=\(sessionID)")
let clearedChangeCount = self.pasteboard.clearContents()
self.temporaryWrite = (sessionID, clearedChangeCount)
+ self.temporaryTextProvider = (sessionID, provider)
let didWrite = self.pasteboard.writeObjects([item])
ClipboardAudit.record("temporary_end", pasteboard: self.pasteboard, detail: "session=\(sessionID) success=\(didWrite)")
if self.hasTemporaryText(sessionID: sessionID, expectedText: text) {
@@ -278,6 +319,7 @@ final class SystemPasteboardManager: PasteboardManaging {
ClipboardAudit.record("intentional_begin", pasteboard: self.pasteboard)
self.pasteboard.clearContents()
let success = self.pasteboard.writeObjects([item]) && self.pasteboard.string(forType: .string) == text
+ self.temporaryTextProvider = nil
ClipboardAudit.record("intentional_end", pasteboard: self.pasteboard, detail: "success=\(success)")
return success
}
@@ -292,13 +334,24 @@ final class SystemPasteboardManager: PasteboardManaging {
}
private func hasTemporaryText(sessionID: String, expectedText: String) -> Bool {
- self.pasteboard.string(forType: .string) == expectedText &&
+ // Reading our own string would fulfill the promise and manufacture a
+ // receipt before the target app has even received Cmd+V.
+ self.temporaryTextProvider?.sessionID == sessionID &&
+ self.temporaryTextProvider?.provider.text == expectedText &&
self.pasteboard.string(forType: Self.sessionType) == sessionID
}
+ func observeTemporaryTextRead(sessionID: String, onRead: @escaping @MainActor @Sendable (TimeInterval) -> Void) -> Bool {
+ guard let temporaryTextProvider, temporaryTextProvider.sessionID == sessionID else { return false }
+ temporaryTextProvider.provider.observe(onRead)
+ return true
+ }
+
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)
+ let restored = self.restore(snapshot, ifUnchangedSince: temporaryWrite.changeCount)
+ self.temporaryTextProvider = nil
+ return restored
}
func restore(_ snapshot: PasteboardSnapshot) -> Bool {
@@ -569,6 +622,13 @@ final class SystemPasteboardManager: PasteboardManaging {
@MainActor
final class SystemPasteCommandPoster: PasteCommandPosting {
+ // Paste is an application shortcut. Inject into the login session rather
+ // than changing HID modifier state or passing through hardware hotkey taps.
+ nonisolated static let pasteEventTapLocation = CGEventTapLocation.cgSessionEventTap
+ // Flutter synchronizes Command from its left/right device bits, rather
+ // than the generic Command flag alone. Match a physical left-Command chord.
+ nonisolated static let commandFlags: CGEventFlags = [.maskCommand, CGEventFlags(rawValue: UInt64(NX_DEVICELCMDKEYMASK))]
+
func postGlobalPasteCommand() async -> Bool {
guard AXIsProcessTrusted() else { return false }
let events = Self.makePasteEvents()
@@ -577,32 +637,27 @@ final class SystemPasteCommandPoster: PasteCommandPosting {
// The coordinator verifies pasteboard ownership before reaching this point,
// so the temporary item is ready to consume without an additional delay.
for event in events {
- event.post(tap: .cghidEventTap)
+ event.post(tap: Self.pasteEventTapLocation)
}
return true
}
- /// Command down, V down, V up, Command up. Pressing and releasing Command
- /// explicitly matters: setting the flag on V alone leaves the HID state
- /// reporting Command as held, which later blocks the send key.
+ /// The V events carry Command, as in a normal application paste. Posting
+ /// this pair at HID level used to leave Command held in HID state; the
+ /// session-level route avoids changing that physical-key state instead.
nonisolated static func makePasteEvents() -> [CGEvent] {
let pasteKeyCode = TypingService.pasteVirtualKeyCode
- let commandKeyCode = CGKeyCode(kVK_Command)
let source = CGEventSource(stateID: .combinedSessionState)
- guard let cmdDown = CGEvent(keyboardEventSource: source, virtualKey: commandKeyCode, keyDown: true),
- let vDown = CGEvent(keyboardEventSource: source, virtualKey: pasteKeyCode, keyDown: true),
- let vUp = CGEvent(keyboardEventSource: source, virtualKey: pasteKeyCode, keyDown: false),
- let cmdUp = CGEvent(keyboardEventSource: source, virtualKey: commandKeyCode, keyDown: false)
+ guard let vDown = CGEvent(keyboardEventSource: source, virtualKey: pasteKeyCode, keyDown: true),
+ let vUp = CGEvent(keyboardEventSource: source, virtualKey: pasteKeyCode, keyDown: false)
else {
return []
}
- cmdDown.flags = .maskCommand
- vDown.flags = .maskCommand
- vUp.flags = .maskCommand
- cmdUp.flags = []
+ vDown.flags = Self.commandFlags
+ vUp.flags = Self.commandFlags
// Mark the paste as ours so the hotkey tap passes it through untouched.
- let events = [cmdDown, vDown, vUp, cmdUp]
+ let events = [vDown, vUp]
for event in events {
event.setIntegerValueField(.eventSourceUserData, value: TypingService.synthesizedEventUserData)
}
@@ -614,6 +669,7 @@ final class SystemPasteCommandPoster: PasteCommandPosting {
final class PasteDeliveryCoordinator {
static let shared = PasteDeliveryCoordinator()
nonisolated static let defaultSettlementDelayNanoseconds: UInt64 = 500_000_000
+ nonisolated static let defaultReadTimeoutNanoseconds: UInt64 = 1_000_000_000
private struct ClipboardLease {
let originalSnapshot: PasteboardSnapshot
@@ -622,12 +678,16 @@ final class PasteDeliveryCoordinator {
let generation: UInt64
let shouldKeepTranscript: Bool
let isOutputValid: @MainActor () -> Bool
+ let commandPostedAt: TimeInterval
+ let pipelineID: String?
+ var readAt: TimeInterval?
var settlementTask: Task<Void, Never>?
}
private let pasteboard: PasteboardManaging
private let commandPoster: PasteCommandPosting
private let settlementDelayNanoseconds: UInt64
+ private let readTimeoutNanoseconds: UInt64
private var generation: UInt64 = 0
private var lease: ClipboardLease?
private var isDelivering = false
@@ -637,11 +697,13 @@ final class PasteDeliveryCoordinator {
init(
pasteboard: PasteboardManaging? = nil,
commandPoster: PasteCommandPosting? = nil,
- settlementDelayNanoseconds: UInt64 = PasteDeliveryCoordinator.defaultSettlementDelayNanoseconds
+ settlementDelayNanoseconds: UInt64 = PasteDeliveryCoordinator.defaultSettlementDelayNanoseconds,
+ readTimeoutNanoseconds: UInt64 = PasteDeliveryCoordinator.defaultReadTimeoutNanoseconds
) {
self.pasteboard = pasteboard ?? SystemPasteboardManager()
self.commandPoster = commandPoster ?? SystemPasteCommandPoster()
self.settlementDelayNanoseconds = settlementDelayNanoseconds
+ self.readTimeoutNanoseconds = readTimeoutNanoseconds
}
func deliver(
@@ -715,12 +777,23 @@ final class PasteDeliveryCoordinator {
generation: generation,
shouldKeepTranscript: preserveTranscriptOnClipboard,
isOutputValid: isOutputValid,
+ commandPostedAt: commandPostedAt,
+ pipelineID: DebugLogger.pipelineID,
+ readAt: nil,
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)
+ let observesReads = self.pasteboard.observeTemporaryTextRead(sessionID: sessionID) { [weak self] readAt in
+ self?.temporaryTextWasRead(sessionID: sessionID, generation: generation, readAt: readAt)
+ }
+ self.scheduleSettlement(
+ sessionID: sessionID,
+ generation: generation,
+ delayNanoseconds: observesReads ? self.readTimeoutNanoseconds : self.settlementDelayNanoseconds,
+ readTimedOut: observesReads
+ )
return .commandPosted
}
@@ -795,20 +868,34 @@ final class PasteDeliveryCoordinator {
self.settleIfCurrent(sessionID: lease.sessionID, generation: lease.generation)
}
- private func scheduleSettlement(sessionID: String, generation: UInt64) {
- let settlementDelayNanoseconds = self.settlementDelayNanoseconds
+ private func temporaryTextWasRead(sessionID: String, generation: UInt64, readAt: TimeInterval) {
+ guard let lease = self.lease, lease.sessionID == sessionID,
+ lease.generation == generation, lease.readAt == nil
+ else { return }
+ self.lease?.readAt = readAt
+ self.lease?.settlementTask?.cancel()
+ DebugLogger.$pipelineID.withValue(lease.pipelineID) {
+ DebugLogger.shared.info(
+ "PASTE_READ generation=\(generation) elapsedMs=\(Int(max(0, readAt - lease.commandPostedAt) * 1000))",
+ source: "TypingService"
+ )
+ self.scheduleSettlement(sessionID: sessionID, generation: generation, delayNanoseconds: self.settlementDelayNanoseconds)
+ }
+ }
+
+ private func scheduleSettlement(sessionID: String, generation: UInt64, delayNanoseconds: UInt64, readTimedOut: Bool = false) {
let scheduledAt = ProcessInfo.processInfo.systemUptime
let task = Task { @MainActor [weak self] in
- try? await Task.sleep(nanoseconds: settlementDelayNanoseconds)
+ try? await Task.sleep(nanoseconds: delayNanoseconds)
guard !Task.isCancelled else { return }
- self?.log("settlement_begin generation=\(generation) elapsedMs=\((ProcessInfo.processInfo.systemUptime - scheduledAt) * 1000) scheduledDelayMs=\(settlementDelayNanoseconds / 1_000_000)")
- self?.settleIfCurrent(sessionID: sessionID, generation: generation)
+ self?.log("settlement_begin generation=\(generation) elapsedMs=\((ProcessInfo.processInfo.systemUptime - scheduledAt) * 1000) scheduledDelayMs=\(delayNanoseconds / 1_000_000)")
+ self?.settleIfCurrent(sessionID: sessionID, generation: generation, readTimedOut: readTimedOut)
}
self.lease?.settlementTask = task
- self.log("settlement_scheduled generation=\(generation) delayMs=\(settlementDelayNanoseconds / 1_000_000)")
+ self.log("settlement_scheduled generation=\(generation) delayMs=\(delayNanoseconds / 1_000_000)")
}
- private func settleIfCurrent(sessionID: String, generation: UInt64) {
+ private func settleIfCurrent(sessionID: String, generation: UInt64, readTimedOut: Bool = false) {
guard let lease = self.lease,
lease.generation == generation,
lease.sessionID == sessionID
@@ -825,8 +912,14 @@ final class PasteDeliveryCoordinator {
}
let restoreStartedAt = ProcessInfo.processInfo.systemUptime
- if lease.shouldKeepTranscript, lease.isOutputValid() {
+ // A late Cmd+V can still be queued in the target. Restoring the old
+ // clipboard now would paste unrelated content. Materialize the promised
+ // text and release the slot; a timeout alone does not prove failure.
+ if lease.shouldKeepTranscript || readTimedOut, lease.isOutputValid() {
let didWrite = self.writeBackup(lease.text)
+ if readTimedOut {
+ DebugLogger.shared.info("PASTE_READ_TIMEOUT generation=\(generation) transcriptRetained=\(didWrite)", source: "TypingService")
+ }
self.log("intentional_copy_settled generation=\(generation) success=\(didWrite) elapsedMs=\((ProcessInfo.processInfo.systemUptime - restoreStartedAt) * 1000)")
} else {
let didRestore = self.pasteboard.restoreTemporarySnapshot(lease.originalSnapshot, sessionID: sessionID, expectedText: lease.text)
diff --git a/Sources/Fluid/Services/PasteVerifier.swift b/Sources/Fluid/Services/PasteVerifier.swift
index f1887232..14c65b12 100644
--- a/Sources/Fluid/Services/PasteVerifier.swift
+++ b/Sources/Fluid/Services/PasteVerifier.swift
@@ -3,8 +3,8 @@ import ApplicationServices
import Foundation
/// Reads the focused element back after a paste to learn whether the text
-/// landed. `notLanded` is returned only when the same element, its value,
-/// its character count and its caret all stayed unchanged across two reads.
+/// landed. `notLanded` requires an unchanged caret plus an unchanged readable
+/// value or character count in the same element through the final check.
/// Every other situation is `unknown`, and the caller stays silent.
enum PasteVerifier {
struct Snapshot {
@@ -66,12 +66,11 @@ enum PasteVerifier {
)
}
- /// Delays before each read-back. The verdict is only "not landed" after
- /// the last one, so a slow app that applies the paste late never draws a
- /// failure card.
+ /// Bounded read-back grace, separate from the one-second clipboard timeout.
+ /// A late paste inside this window does not produce a failure verdict.
static let firstCheckDelay: TimeInterval = 0.15
static let secondCheckDelay: TimeInterval = 0.35
- static let finalCheckDelay: TimeInterval = 1.0
+ static let finalCheckDelay: TimeInterval = 1.5
static var totalDecisionDelay: TimeInterval { self.firstCheckDelay + self.secondCheckDelay + self.finalCheckDelay }
/// A key press or click after the paste means the user acted on the field
@@ -84,27 +83,41 @@ enum PasteVerifier {
nonisolated static func secondsSinceLastUserInput() -> TimeInterval {
min(
CGEventSource.secondsSinceLastEventType(.hidSystemState, eventType: .keyDown),
- CGEventSource.secondsSinceLastEventType(.hidSystemState, eventType: .leftMouseDown)
+ CGEventSource.secondsSinceLastEventType(.hidSystemState, eventType: .leftMouseDown),
+ CGEventSource.secondsSinceLastEventType(.hidSystemState, eventType: .rightMouseDown),
+ CGEventSource.secondsSinceLastEventType(.hidSystemState, eventType: .otherMouseDown)
)
}
/// Call off the main thread after the paste command was posted.
- nonisolated static func verify(before: Snapshot, pastedText: String) async -> Verdict {
+ nonisolated static func verify(
+ before: Snapshot,
+ pastedText: String,
+ capture: () -> Snapshot? = { Self.capture() },
+ wait: (TimeInterval) async -> Bool = { delay in
+ do {
+ try await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
+ return !Task.isCancelled
+ } catch {
+ return false
+ }
+ }
+ ) async -> Verdict {
let needle = self.normalize(pastedText)
guard !needle.isEmpty else { return .unknown(reason: "empty_text") }
guard before.value != nil || before.characterCount != nil || before.caret != nil else {
return .unknown(reason: "before_unreadable")
}
- try? await Task.sleep(nanoseconds: UInt64(self.firstCheckDelay * 1_000_000_000))
- guard let first = self.capture() else { return .unknown(reason: "after_unreadable") }
+ guard await wait(self.firstCheckDelay) else { return .unknown(reason: "cancelled") }
+ guard let first = capture() else { return .unknown(reason: "after_unreadable") }
guard CFEqual(first.element, before.element) else { return .unknown(reason: "focus_moved") }
if let verdict = self.confirmation(before: before, after: first, needle: needle) { return verdict }
// Nothing changed yet. Give slow apps a second chance before deciding.
- try? await Task.sleep(nanoseconds: UInt64(self.secondCheckDelay * 1_000_000_000))
- guard let second = self.capture(), CFEqual(second.element, before.element) else {
+ guard await wait(self.secondCheckDelay) else { return .unknown(reason: "cancelled") }
+ guard let second = capture(), CFEqual(second.element, before.element) else {
return .unknown(reason: "focus_moved_late")
}
if let verdict = self.confirmation(before: before, after: second, needle: needle) { return verdict }
@@ -112,8 +125,8 @@ enum PasteVerifier {
// Still unchanged. A failure card is disruptive, so wait once more for
// apps that apply Cmd+V on a later run-loop turn before deciding.
- try? await Task.sleep(nanoseconds: UInt64(self.finalCheckDelay * 1_000_000_000))
- guard let final = self.capture(), CFEqual(final.element, before.element) else {
+ guard await wait(self.finalCheckDelay) else { return .unknown(reason: "cancelled") }
+ guard let final = capture(), CFEqual(final.element, before.element) else {
return .unknown(reason: "focus_moved_final")
}
if let verdict = self.confirmation(before: before, after: final, needle: needle) { return verdict }
@@ -126,11 +139,11 @@ enum PasteVerifier {
let valueKnown = before.value != nil && after.value != nil
let countKnown = before.characterCount != nil && after.characterCount != nil
let caretKnown = before.caret != nil && after.caret != nil
- guard valueKnown, countKnown, caretKnown else {
+ guard valueKnown || countKnown, caretKnown else {
return .unknown(reason: "signals_incomplete value=\(valueKnown) count=\(countKnown) caret=\(caretKnown)")
}
- guard before.value == after.value,
- before.characterCount == after.characterCount,
+ guard !valueKnown || before.value == after.value,
+ !countKnown || before.characterCount == after.characterCount,
before.caret?.location == after.caret?.location,
before.caret?.length == after.caret?.length
else { return .unknown(reason: "changed_without_text") }
@@ -144,13 +157,17 @@ enum PasteVerifier {
return .confirmed(method: "value")
}
}
+ let insertedLength = needle.utf16.count
+ let countDelta = insertedLength - (before.caret?.length ?? 0)
if let beforeCount = before.characterCount, let afterCount = after.characterCount,
- afterCount - beforeCount == needle.count || afterCount - beforeCount == needle.count + 1
+ afterCount != beforeCount,
+ afterCount - beforeCount == countDelta || afterCount - beforeCount == countDelta + 1
{
return .confirmed(method: "count")
}
if let beforeCaret = before.caret, let afterCaret = after.caret,
- afterCaret.location - beforeCaret.location - beforeCaret.length == needle.count
+ afterCaret.location - beforeCaret.location == insertedLength,
+ afterCaret.length == 0
{
return .confirmed(method: "caret")
}
@@ -189,6 +206,31 @@ enum PasteVerifier {
}
}
+/// Warning identity only: never controls capture, clipboard writes or retries.
+/// A new delivery/recording invalidates older checks across TypingService instances.
+@MainActor
+final class PasteRecoveryPresentationPolicy {
+ static let shared = PasteRecoveryPresentationPolicy()
+ private var generation: UInt64 = 0
+ private var presentedGeneration: UInt64?
+
+ nonisolated deinit {}
+
+ @discardableResult
+ func beginDelivery() -> UInt64 {
+ self.generation &+= 1
+ return self.generation
+ }
+
+ func isCurrent(_ id: UInt64) -> Bool { self.generation == id }
+
+ func claim(_ id: UInt64, alertsEnabled: Bool, isBusy: Bool, userActed: Bool) -> Bool {
+ guard alertsEnabled, !isBusy, !userActed, self.isCurrent(id), self.presentedGeneration != id else { return false }
+ self.presentedGeneration = id
+ return true
+ }
+}
+
extension Notification.Name {
/// Posted on the main queue with `userInfo["transcript"]` when a paste
/// was verified to not land.
diff --git a/Sources/Fluid/Services/TypingService.swift b/Sources/Fluid/Services/TypingService.swift
index fef9a5c6..5014b85e 100644
--- a/Sources/Fluid/Services/TypingService.swift
+++ b/Sources/Fluid/Services/TypingService.swift
@@ -473,6 +473,7 @@ final class TypingService {
isOutputValid: @escaping @MainActor () -> Bool = { true }
) async -> TextDeliveryResult {
guard isOutputValid() else { return .cancelled }
+ let verificationID = PasteRecoveryPresentationPolicy.shared.beginDelivery()
let requestedAt = ProcessInfo.processInfo.systemUptime
var closeTrace = OverlayCloseTrace("typing.delivery")
defer { closeTrace.finish() }
@@ -581,10 +582,10 @@ final class TypingService {
toggleStopRequestedAt: toggleStopRequestedAt,
completedAt: completedAt
)
- if verifiesLanding, SettingsStore.shared.showPasteCheckAlerts,
- result == .commandPosted, deliveryPath != .direct, let verificationBefore
- {
- self.verifyPasteLanded(text, before: verificationBefore)
+ if verifiesLanding, result == .commandPosted, deliveryPath != .direct, let verificationBefore {
+ self.verifyPasteLanded(text, before: verificationBefore, verificationID: verificationID, postedAt: completedAt, isOutputValid: isOutputValid)
+ } else if verifiesLanding, result == .commandPosted, deliveryPath != .direct {
+ DebugLogger.shared.info("PASTE_VERIFY unknown reason=baseline_unavailable", source: "TypingService")
}
// The caller starts correction tracking after completing delivery UI.
return result
@@ -697,6 +698,10 @@ final class TypingService {
toggleStopRequestedAt: TimeInterval?,
completedAt: TimeInterval = ProcessInfo.processInfo.systemUptime
) {
+ DebugLogger.shared.info(
+ "TEXT_DELIVERY path=\(path.rawValue) result=\(String(describing: result)) elapsedMs=\(max(0, Self.elapsedMs(from: requestedAt, to: completedAt)))",
+ source: "TypingService"
+ )
guard let outcome = Self.analyticsOutcome(for: result) else { return }
let isClipboardDispatch = outcome == .dispatched &&
(path == .clipboard || path == .clipboardFallback)
@@ -713,27 +718,32 @@ final class TypingService {
)
}
- /// Off-main read-back after a paste. Logs every verdict; only a certain
- /// `notLanded` reaches the UI.
- private func verifyPasteLanded(_ text: String, before: PasteVerifier.Snapshot) {
+ /// Bounded off-main read-back always records diagnostics. The preference-controlled card
+ /// remains separate, so turning alerts off cannot hide evidence of a miss.
+ private func verifyPasteLanded(_ text: String, before: PasteVerifier.Snapshot, verificationID: UInt64, postedAt: TimeInterval, isOutputValid: @escaping @MainActor () -> Bool) {
+ let pipelineID = DebugLogger.pipelineID
Task.detached(priority: .utility) {
- let startedAt = ProcessInfo.processInfo.systemUptime
- var verdict = await PasteVerifier.verify(before: before, pastedText: text)
- if case .notLanded = verdict, PasteVerifier.userActedAfterPaste(
- secondsSinceLastInput: PasteVerifier.secondsSinceLastUserInput(),
- secondsSincePaste: ProcessInfo.processInfo.systemUptime - startedAt
- ) {
- verdict = .unknown(reason: "user_input_after_paste")
- }
- let app = NSRunningApplication(processIdentifier: before.pid)?.bundleIdentifier ?? "pid\(before.pid)"
- DebugLogger.shared.info(
- "PASTE_VERIFY \(verdict.logDescription) app=\(app) before[\(before.summary)] " +
- "elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - startedAt) * 1000).rounded()))",
- source: "TypingService"
- )
- guard case .notLanded = verdict else { return }
- await MainActor.run {
- NotificationCenter.default.post(name: .fluidPasteNotLanded, object: nil, userInfo: ["transcript": text])
+ await DebugLogger.$pipelineID.withValue(pipelineID) {
+ let startedAt = postedAt
+ var verdict = await PasteVerifier.verify(before: before, pastedText: text)
+ if case .notLanded = verdict, PasteVerifier.userActedAfterPaste(
+ secondsSinceLastInput: PasteVerifier.secondsSinceLastUserInput(),
+ secondsSincePaste: ProcessInfo.processInfo.systemUptime - startedAt
+ ) {
+ verdict = .unknown(reason: "user_input_after_paste")
+ }
+ let app = NSRunningApplication(processIdentifier: before.pid)?.bundleIdentifier ?? "pid\(before.pid)"
+ DebugLogger.shared.info(
+ "PASTE_VERIFY \(verdict.logDescription) app=\(app) before[\(before.summary)] " +
+ "elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - startedAt) * 1000).rounded()))",
+ source: "TypingService"
+ )
+ guard case .notLanded = verdict else { return }
+ await MainActor.run {
+ guard isOutputValid(), PasteRecoveryPresentationPolicy.shared.isCurrent(verificationID),
+ SettingsStore.shared.showPasteCheckAlerts else { return }
+ NotificationCenter.default.post(name: .fluidPasteNotLanded, object: nil, userInfo: ["transcript": text, "verificationID": verificationID, "postedAt": postedAt])
+ }
}
}
}
diff --git a/Tests/DictationAccessibilityPreparationTests.swift b/Tests/DictationAccessibilityPreparationTests.swift
new file mode 100644
index 00000000..c068c6f2
--- /dev/null
+++ b/Tests/DictationAccessibilityPreparationTests.swift
@@ -0,0 +1,96 @@
+import AppKit
+
+final class DebugLogger: @unchecked Sendable {
+ static let shared = DebugLogger()
+ func info(_ message: String, source: String) {}
+}
+
+private final class Probe: @unchecked Sendable {
+ private let lock = NSLock()
+ var trusted = true
+ var supported = true
+ var result = DictationAccessibilityPreparationWorker.Outcome.enabled
+ private(set) var checks = 0
+ private(set) var writes = 0
+
+ func isTrusted() -> Bool { self.lock.withLock { self.trusted } }
+ func supports(_ request: DictationAccessibilityPreparationWorker.Request) -> Bool {
+ self.lock.withLock { self.checks += 1; return self.supported }
+ }
+
+ func enable(_ request: DictationAccessibilityPreparationWorker.Request) -> DictationAccessibilityPreparationWorker.Outcome {
+ self.lock.withLock { self.writes += 1; return self.result }
+ }
+
+ func worker(capacity: Int = 64) -> DictationAccessibilityPreparationWorker {
+ .init(capacity: capacity, isTrusted: { self.isTrusted() }, supportsPreparation: { self.supports($0) }, enable: { self.enable($0) })
+ }
+}
+
+@main
+enum DictationAccessibilityPreparationTests {
+ static func request(_ pid: pid_t = 123, launchedAt: Date? = Date(timeIntervalSince1970: 1)) -> DictationAccessibilityPreparationWorker.Request {
+ .init(pid: pid, launchedAt: launchedAt, bundleURL: URL(fileURLWithPath: "/Applications/Fixture.app"))
+ }
+
+ static func main() async {
+ let probe = Probe(), worker = probe.worker()
+ let request = self.request()
+ let first = await worker.prepare(request)
+ precondition(first == .enabled)
+ for _ in 0..<20 {
+ _ = await worker.prepare(request)
+ }
+ precondition(probe.writes == 1 && probe.checks == 1, "Repeat activations must not repeat disk/AX work")
+ _ = await worker.prepare(self.request(124))
+ _ = await worker.prepare(self.request(123, launchedAt: Date(timeIntervalSince1970: 2)))
+ precondition(probe.writes == 3, "Relaunch/PID reuse must receive fresh preparation")
+
+ let unsupported = Probe(); unsupported.supported = false
+ let native = unsupported.worker()
+ let nativeResult = await native.prepare(request)
+ precondition(nativeResult == .unsupported)
+ _ = await native.prepare(request)
+ precondition(unsupported.writes == 0 && unsupported.checks == 1, "Native apps must receive no AX writes")
+
+ let permission = Probe(); permission.trusted = false
+ let permissionWorker = permission.worker()
+ let denied = await permissionWorker.prepare(request)
+ precondition(denied == .untrusted && permission.checks == 0 && permission.writes == 0)
+ permission.trusted = true
+ let granted = await permissionWorker.prepare(request)
+ precondition(granted == .enabled && permission.writes == 1)
+
+ let failed = Probe(); failed.result = .failed(-25_212)
+ let retryWorker = failed.worker()
+ _ = await retryWorker.prepare(request)
+ failed.result = .enabled
+ let retry = await retryWorker.prepare(request)
+ precondition(retry == .enabled && failed.writes == 2, "A failed attempt must not suppress later activations")
+
+ let bounded = Probe(), small = bounded.worker(capacity: 2)
+ _ = await small.prepare(self.request(1)); _ = await small.prepare(self.request(2))
+ _ = await small.prepare(self.request(3)); _ = await small.prepare(self.request(1))
+ precondition(bounded.writes == 4, "Old entries must be evicted")
+ let invalid = await small.prepare(self.request(0))
+ let own = await small.prepare(self.request(getpid()))
+ precondition(invalid == .stale && own == .stale && bounded.writes == 4)
+
+ let cancelledProbe = Probe(), cancelledWorker = cancelledProbe.worker()
+ let gate = Task {
+ withUnsafeCurrentTask { $0?.cancel() }
+ return await cancelledWorker.prepare(request)
+ }
+ let cancelled = await gate.value
+ precondition(cancelled == .cancelled && cancelledProbe.writes == 0)
+
+ let rapidProbe = Probe(), rapid = rapidProbe.worker()
+ await withTaskGroup(of: Void.self) { group in
+ for _ in 0..<50 {
+ group.addTask { _ = await rapid.prepare(request) }
+ }
+ }
+ precondition(rapidProbe.checks == 1 && rapidProbe.writes == 1, "Concurrent duplicates must coalesce")
+ print("PASS: once-per-process preparation, relaunch/PID reuse, native-app non-effects, permission grant, failure retry, bounded eviction, invalid/self targets, cancellation and concurrent activation")
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift b/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift
index bf16c62f..2380ae55 100644
--- a/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift
+++ b/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift
@@ -132,13 +132,17 @@ final class PasteDeliveryCoordinatorTests: XCTestCase {
XCTAssertEqual(pasteboard.restoreCount, 1)
}
- func testPasteCheckAlertsDefaultOffAndRoundTripThroughBackup() {
+ func testPasteCheckAlertsDefaultOnAndPreserveExplicitOffThroughBackup() {
let settings = SettingsStore.shared
let original = settings.showPasteCheckAlerts
defer { settings.showPasteCheckAlerts = original }
UserDefaults.standard.removeObject(forKey: "ShowPasteCheckAlerts")
+ XCTAssertTrue(settings.showPasteCheckAlerts)
+
+ settings.showPasteCheckAlerts = false
XCTAssertFalse(settings.showPasteCheckAlerts)
+ XCTAssertEqual(settings.makeBackupPayload().showPasteCheckAlerts, false)
settings.showPasteCheckAlerts = true
XCTAssertTrue(settings.showPasteCheckAlerts)
@@ -539,10 +543,9 @@ final class PasteDeliveryCoordinatorTests: XCTestCase {
XCTAssertEqual(state.textDeliveryFailureTranscript, "retained output")
}
- func testPasteNotLandedVerdictWaitsAtLeastOneAndAHalfSeconds() {
- // A slow app that applies Cmd+V late must never draw a failure card.
- XCTAssertGreaterThanOrEqual(PasteVerifier.totalDecisionDelay, 1.5)
- XCTAssertEqual(PasteVerifier.finalCheckDelay, 1.0)
+ func testPasteNotLandedVerdictGivesLateAppsTwoSeconds() {
+ XCTAssertEqual(PasteVerifier.totalDecisionDelay, 2)
+ XCTAssertEqual(PasteVerifier.finalCheckDelay, 1.5)
}
func testAccessibilityMessagingTimeoutIsBounded() {
diff --git a/Tests/FluidDictationIntegrationTests/SpokenSendTests.swift b/Tests/FluidDictationIntegrationTests/SpokenSendTests.swift
index 14aa46c7..423c1fcf 100644
--- a/Tests/FluidDictationIntegrationTests/SpokenSendTests.swift
+++ b/Tests/FluidDictationIntegrationTests/SpokenSendTests.swift
@@ -339,26 +339,25 @@ final class SpokenSendTests: XCTestCase {
// MARK: - Adversarial: paste key sequence
- func testPasteSequencePressesAndReleasesCommandExplicitly() throws {
+ func testPasteSequenceUsesSessionVEventsWithLeftCommandFlags() throws {
let events = SystemPasteCommandPoster.makePasteEvents()
- XCTAssertEqual(events.count, 4)
+ XCTAssertEqual(SystemPasteCommandPoster.pasteEventTapLocation, .cgSessionEventTap)
+ XCTAssertEqual(events.count, 2)
let keyCodes = events.map { CGKeyCode($0.getIntegerValueField(.keyboardEventKeycode)) }
XCTAssertEqual(keyCodes, [
- CGKeyCode(kVK_Command), TypingService.pasteVirtualKeyCode, TypingService.pasteVirtualKeyCode, CGKeyCode(kVK_Command),
+ TypingService.pasteVirtualKeyCode, TypingService.pasteVirtualKeyCode,
])
- // Modifier presses are flagsChanged events, exactly like a physical Command key.
- XCTAssertEqual(events.map(\.type), [.flagsChanged, .keyDown, .keyUp, .flagsChanged])
+ // The chord posts V down/up rather than physical Command-key events.
+ XCTAssertEqual(events.map(\.type), [.keyDown, .keyUp])
// Command has to be the only modifier. A leaked Shift, Option, Control, or Fn
// turns Cmd+V into a different shortcut, and a bare V is what inserts "v".
- XCTAssertEqual(events[0].flags, .maskCommand)
- XCTAssertEqual(events[1].flags, .maskCommand)
- XCTAssertEqual(events[2].flags, .maskCommand)
- XCTAssertEqual(events[3].flags, CGEventFlags(), "the final event must release Command")
+ XCTAssertEqual(events[0].flags, [.maskCommand, CGEventFlags(rawValue: UInt64(NX_DEVICELCMDKEYMASK))])
+ XCTAssertEqual(events[1].flags, [.maskCommand, CGEventFlags(rawValue: UInt64(NX_DEVICELCMDKEYMASK))])
}
func testPasteSequenceIsInvisibleToTheHotkeyTap() throws {
let events = SystemPasteCommandPoster.makePasteEvents()
- XCTAssertEqual(events.count, 4)
+ XCTAssertEqual(events.count, 2)
for event in events {
XCTAssertTrue(GlobalHotkeyManager.isSynthesizedTypingEvent(event))
}
diff --git a/Tests/PasteCommandEventTests.swift b/Tests/PasteCommandEventTests.swift
new file mode 100644
index 00000000..4c37fd75
--- /dev/null
+++ b/Tests/PasteCommandEventTests.swift
@@ -0,0 +1,24 @@
+import AppKit
+
+/// Constructs the production events only. Never calls postGlobalPasteCommand.
+@main
+@MainActor
+enum PasteCommandEventTests {
+ static func main() {
+ precondition(SystemPasteCommandPoster.pasteEventTapLocation == .cgSessionEventTap)
+ let events = SystemPasteCommandPoster.makePasteEvents()
+ precondition(events.count == 2)
+ precondition(events.map(\.type) == [.keyDown, .keyUp])
+ for event in events {
+ precondition(event.getIntegerValueField(.keyboardEventKeycode) == 9)
+ precondition(event.flags == [.maskCommand, CGEventFlags(rawValue: UInt64(NX_DEVICELCMDKEYMASK))], "No Control, Option, Shift or Fn may leak into Cmd+V")
+ // Flutter's synchronizeModifiers reads this device-dependent bit.
+ precondition(event.flags.rawValue & 0x8 != 0, "Flutter must recognize the left Command key")
+ precondition(event.flags.isDisjoint(with: [.maskControl, .maskAlternate, .maskShift, .maskSecondaryFn]))
+ precondition(event.getIntegerValueField(.eventSourceUserData) == TypingService.synthesizedEventUserData)
+ precondition(event.getIntegerValueField(.eventSourceStateID) == CGEventSourceStateID.combinedSessionState.rawValue)
+ }
+ print("PASS: production paste uses session-level V down/up, Command-only flags, correct source and hotkey bypass tag")
+ print("No events were posted. Physical modifier-state behavior requires the installed-app test.")
+ }
+}
diff --git a/Tests/PasteReadReceiptReproductionTests.swift b/Tests/PasteReadReceiptReproductionTests.swift
new file mode 100644
index 00000000..5e3c7fe0
--- /dev/null
+++ b/Tests/PasteReadReceiptReproductionTests.swift
@@ -0,0 +1,300 @@
+import AppKit
+
+/// Exercises the production data provider and coordinator on private pasteboards.
+/// Only Cmd+V posting is replaced; no system clipboard or keyboard is touched.
+@main
+@MainActor
+enum PasteReadReceiptReproductionTests {
+ static func expect(_ condition: @autoclosure () -> Bool, _ message: String = "Expectation failed", file: StaticString = #filePath, line: UInt = #line) {
+ guard condition() else {
+ FileHandle.standardError.write(Data("FAIL: \(file):\(line): \(message)\n".utf8))
+ exit(1)
+ }
+ }
+
+ static func main() async {
+ FileHandle.standardOutput.write(Data("RUN: testOwnershipChecksDoNotCreateReceipts\n".utf8))
+ await self.testOwnershipChecksDoNotCreateReceipts()
+ FileHandle.standardOutput.write(Data("RUN: testReadBeforeObserverIsNotLost\n".utf8))
+ await self.testReadBeforeObserverIsNotLost()
+ FileHandle.standardOutput.write(Data("RUN: testDelayedConsumerGetsDictation\n".utf8))
+ await self.testDelayedConsumerGetsDictation()
+ FileHandle.standardOutput.write(Data("RUN: testNormalReadRestoresOriginal\n".utf8))
+ await self.testNormalReadRestoresOriginal()
+ FileHandle.standardOutput.write(Data("RUN: testTimeoutRetainsTextAndReleasesQueue\n".utf8))
+ await self.testTimeoutRetainsTextAndReleasesQueue()
+ FileHandle.standardOutput.write(Data("RUN: testExternalCopyWins\n".utf8))
+ await self.testExternalCopyWins(afterRead: false)
+ FileHandle.standardOutput.write(Data("RUN: testExternalCopyWins\n".utf8))
+ await self.testExternalCopyWins(afterRead: true)
+ FileHandle.standardOutput.write(Data("RUN: testCancelledTimeoutRestoresOriginal\n".utf8))
+ await self.testCancelledTimeoutRestoresOriginal()
+ FileHandle.standardOutput.write(Data("RUN: testRepeatedReadsDoNotPostAgain\n".utf8))
+ await self.testRepeatedReadsDoNotPostAgain()
+ FileHandle.standardOutput.write(Data("RUN: testQueuedDeliveryWaitsForReadAndSettlement\n".utf8))
+ await self.testQueuedDeliveryWaitsForReadAndSettlement()
+ FileHandle.standardOutput.write(Data("RUN: testStaleReceiptCannotSettleNewDelivery\n".utf8))
+ await self.testStaleReceiptCannotSettleNewDelivery()
+ FileHandle.standardOutput.write(Data("RUN: testReadReceiptKeepsItsOriginalPipeline\n".utf8))
+ await self.testReadReceiptKeepsItsOriginalPipeline()
+ print("PASS: 12 paste receipt cases; no real keys or system clipboard used")
+ }
+
+ static func board() -> NSPasteboard {
+ NSPasteboard(name: .init("fluidvoice.read-receipt-tests.\(UUID().uuidString)"))
+ }
+
+ static func waitUntil(_ condition: () -> Bool) async {
+ let deadline = ProcessInfo.processInfo.systemUptime + 3
+ while !condition(), ProcessInfo.processInfo.systemUptime < deadline {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ self.expect(condition(), "Condition did not become true before the bounded deadline")
+ }
+
+ static func testOwnershipChecksDoNotCreateReceipts() async {
+ let board = self.board()
+ defer { board.releaseGlobally() }
+ let manager = SystemPasteboardManager(pasteboard: board)
+ self.expect(manager.writeTemporaryText("dictation", sessionID: "one"))
+ var reads = 0
+ self.expect(manager.observeTemporaryTextRead(sessionID: "one") { _ in reads += 1 })
+ for _ in 0..<10 {
+ self.expect(manager.isOwned(sessionID: "one", expectedText: "dictation"))
+ self.expect(!manager.isOwned(sessionID: "one", expectedText: "wrong text"))
+ _ = board.types
+ }
+ try? await Task.sleep(nanoseconds: 20_000_000)
+ self.expect(reads == 0, "Our own ownership/type checks must not manufacture a read receipt")
+ self.expect(board.string(forType: .string) == "dictation")
+ await self.waitUntil { reads == 1 }
+ _ = board.string(forType: .string)
+ try? await Task.sleep(nanoseconds: 20_000_000)
+ self.expect(reads == 1)
+ print("PASS: ownership checks do not consume the promise; the first actual read notifies once")
+ }
+
+ static func testReadBeforeObserverIsNotLost() async {
+ let board = self.board()
+ defer { board.releaseGlobally() }
+ let manager = SystemPasteboardManager(pasteboard: board)
+ self.expect(manager.writeTemporaryText("early read", sessionID: "early"))
+ self.expect(board.string(forType: .string) == "early read")
+ var reads = 0
+ self.expect(manager.observeTemporaryTextRead(sessionID: "early") { _ in reads += 1 })
+ await self.waitUntil { reads == 1 }
+ print("PASS: an immediate consumer read before observer registration is retained")
+ }
+
+ static func testDelayedConsumerGetsDictation() async {
+ let board = self.board()
+ defer { board.releaseGlobally() }
+ let manager = SystemPasteboardManager(pasteboard: board)
+ self.expect(manager.writeIntentionalText("previous clipboard"))
+ let poster = ReceiptTestPoster()
+ let coordinator = PasteDeliveryCoordinator(pasteboard: manager, commandPoster: poster)
+ let result = await coordinator.deliver("delayed dictation", preserveTranscriptOnClipboard: false)
+ self.expect(result == .commandPosted)
+ let temporaryRevision = board.changeCount
+ try? await Task.sleep(nanoseconds: 800_000_000)
+ self.expect(board.changeCount == temporaryRevision, "Must not restore at 500 ms before consumption")
+ self.expect(board.string(forType: .string) == "delayed dictation")
+ await self.waitUntil { board.changeCount != temporaryRevision }
+ self.expect(board.string(forType: .string) == "previous clipboard")
+ self.expect(poster.count == 1)
+ print("PASS: real 800 ms delayed read receives dictation, then the previous clipboard is restored")
+ }
+
+ static func testNormalReadRestoresOriginal() async {
+ let board = self.board()
+ defer { board.releaseGlobally() }
+ let manager = SystemPasteboardManager(pasteboard: board)
+ self.expect(manager.writeIntentionalText("original"))
+ let coordinator = PasteDeliveryCoordinator(pasteboard: manager, commandPoster: ReceiptTestPoster(), settlementDelayNanoseconds: 30_000_000)
+ _ = await coordinator.deliver("normal", preserveTranscriptOnClipboard: false)
+ let revision = board.changeCount
+ self.expect(board.string(forType: .string) == "normal")
+ await self.waitUntil { board.changeCount != revision }
+ self.expect(board.string(forType: .string) == "original")
+ print("PASS: normal read restores the original clipboard")
+ }
+
+ static func testTimeoutRetainsTextAndReleasesQueue() async {
+ let board = self.board()
+ defer { board.releaseGlobally() }
+ let manager = SystemPasteboardManager(pasteboard: board)
+ self.expect(manager.writeIntentionalText("original"))
+ let poster = ReceiptTestPoster()
+ let coordinator = PasteDeliveryCoordinator(pasteboard: manager, commandPoster: poster, settlementDelayNanoseconds: 20_000_000, readTimeoutNanoseconds: 60_000_000)
+ _ = await coordinator.deliver("late first", preserveTranscriptOnClipboard: false)
+ let revision = board.changeCount
+ await self.waitUntil { board.changeCount != revision }
+ self.expect(board.string(forType: .string) == "late first", "Timeout must not expose unrelated clipboard content to a late Cmd+V")
+ self.expect(board.types?.contains(.init("org.nspasteboard.TransientType")) == false)
+ _ = await coordinator.deliver("second", preserveTranscriptOnClipboard: false)
+ let nextRevision = board.changeCount
+ self.expect(board.string(forType: .string) == "second")
+ await self.waitUntil { board.changeCount != nextRevision }
+ self.expect(board.string(forType: .string) == "late first")
+ self.expect(poster.count == 2)
+ print("PASS: timeout retains plain text and releases the queue for the next delivery")
+ }
+
+ static func testExternalCopyWins(afterRead: Bool) async {
+ let board = self.board()
+ defer { board.releaseGlobally() }
+ let manager = SystemPasteboardManager(pasteboard: board)
+ self.expect(manager.writeIntentionalText("original"))
+ let coordinator = PasteDeliveryCoordinator(pasteboard: manager, commandPoster: ReceiptTestPoster(), settlementDelayNanoseconds: 30_000_000, readTimeoutNanoseconds: 60_000_000)
+ _ = await coordinator.deliver("dictation", preserveTranscriptOnClipboard: false)
+ if afterRead { _ = board.string(forType: .string) }
+ board.clearContents()
+ self.expect(board.setString("new user copy", forType: .string))
+ try? await Task.sleep(nanoseconds: 100_000_000)
+ self.expect(board.string(forType: .string) == "new user copy")
+ print("PASS: newer user copy wins afterRead=\(afterRead)")
+ }
+
+ static func testCancelledTimeoutRestoresOriginal() async {
+ let board = self.board()
+ defer { board.releaseGlobally() }
+ let manager = SystemPasteboardManager(pasteboard: board)
+ self.expect(manager.writeIntentionalText("original"))
+ let coordinator = PasteDeliveryCoordinator(pasteboard: manager, commandPoster: ReceiptTestPoster(), readTimeoutNanoseconds: 40_000_000)
+ var valid = true
+ _ = await coordinator.deliver("cancelled", preserveTranscriptOnClipboard: false, isOutputValid: { valid })
+ let revision = board.changeCount
+ valid = false
+ await self.waitUntil { board.changeCount != revision }
+ self.expect(board.string(forType: .string) == "original")
+ print("PASS: cancelled output is not kept as a timeout backup")
+ }
+
+ static func testRepeatedReadsDoNotPostAgain() async {
+ let board = self.board()
+ defer { board.releaseGlobally() }
+ let manager = SystemPasteboardManager(pasteboard: board)
+ self.expect(manager.writeIntentionalText("original"))
+ let poster = ReceiptTestPoster()
+ let coordinator = PasteDeliveryCoordinator(pasteboard: manager, commandPoster: poster, settlementDelayNanoseconds: 10_000_000)
+ for index in 0..<20 {
+ let text = "dictation \(index)"
+ _ = await coordinator.deliver(text, preserveTranscriptOnClipboard: false)
+ let revision = board.changeCount
+ for _ in 0..<3 {
+ self.expect(board.string(forType: .string) == text)
+ }
+ await self.waitUntil { board.changeCount != revision }
+ self.expect(board.string(forType: .string) == "original")
+ }
+ self.expect(poster.count == 20, "Receipts must never retry or duplicate insertion")
+ print("PASS: 20 sequential deliveries restore correctly without duplicate commands")
+ }
+
+ static func testQueuedDeliveryWaitsForReadAndSettlement() async {
+ let board = self.board()
+ defer { board.releaseGlobally() }
+ let manager = SystemPasteboardManager(pasteboard: board)
+ self.expect(manager.writeIntentionalText("original"))
+ let poster = ReceiptTestPoster()
+ let coordinator = PasteDeliveryCoordinator(pasteboard: manager, commandPoster: poster, settlementDelayNanoseconds: 20_000_000)
+ _ = await coordinator.deliver("first", preserveTranscriptOnClipboard: false)
+ var secondResult: TextDeliveryResult?
+ let next = Task { @MainActor in
+ secondResult = await coordinator.deliver("second", preserveTranscriptOnClipboard: false)
+ }
+ try? await Task.sleep(nanoseconds: 40_000_000)
+ self.expect(poster.count == 1 && secondResult == nil)
+ self.expect(board.string(forType: .string) == "first")
+ await self.waitUntil { secondResult != nil }
+ self.expect(secondResult == .commandPosted && poster.count == 2)
+ let revision = board.changeCount
+ self.expect(board.string(forType: .string) == "second")
+ await self.waitUntil { board.changeCount != revision }
+ self.expect(board.string(forType: .string) == "original")
+ await next.value
+ print("PASS: a queued paste cannot replace the first payload before its read and settlement")
+ }
+
+ static func testStaleReceiptCannotSettleNewDelivery() async {
+ let board = self.board()
+ defer { board.releaseGlobally() }
+ let manager = ReceiptObservingPasteboard(board: board)
+ self.expect(manager.base.writeIntentionalText("original"))
+ // This case checks stale receipts; timeout retention has its own case.
+ // Keep the unread lease alive until this test explicitly reads it.
+ let coordinator = PasteDeliveryCoordinator(pasteboard: manager, commandPoster: ReceiptTestPoster(), settlementDelayNanoseconds: 10_000_000, readTimeoutNanoseconds: .max)
+ _ = await coordinator.deliver("first", preserveTranscriptOnClipboard: false)
+ let oldHandler = manager.handlers[0]
+ let firstRevision = board.changeCount
+ self.expect(board.string(forType: .string) == "first")
+ await self.waitUntil { board.changeCount != firstRevision }
+ _ = await coordinator.deliver("second", preserveTranscriptOnClipboard: false)
+ let secondRevision = board.changeCount
+ oldHandler(ProcessInfo.processInfo.systemUptime)
+ try? await Task.sleep(nanoseconds: 30_000_000)
+ self.expect(board.changeCount == secondRevision, "A stale first receipt must not schedule the next delivery's restoration")
+ // A busy CI runner may resume after the old 80 ms timeout. Deliberately
+ // delay the reader so timeout behavior cannot masquerade as a stale receipt.
+ try? await Task.sleep(nanoseconds: 120_000_000)
+ self.expect(board.string(forType: .string) == "second")
+ await self.waitUntil { board.changeCount != secondRevision }
+ let restored = board.string(forType: .string)
+ self.expect(restored == "original", "Current receipt should restore its captured clipboard; got \(String(describing: restored))")
+ print("PASS: a late receipt from the previous generation cannot settle the current paste")
+ }
+
+ static func testReadReceiptKeepsItsOriginalPipeline() async {
+ let board = self.board()
+ defer { board.releaseGlobally() }
+ let manager = SystemPasteboardManager(pasteboard: board)
+ self.expect(manager.writeIntentionalText("original"))
+ let coordinator = PasteDeliveryCoordinator(pasteboard: manager, commandPoster: ReceiptTestPoster())
+ _ = await DebugLogger.$pipelineID.withValue("receipt-trace") {
+ await coordinator.deliver("trace text", preserveTranscriptOnClipboard: false)
+ }
+ self.expect(DebugLogger.pipelineID == nil)
+ // AppKit's reader is outside the request task; its callback must recover
+ // the delivery's trace rather than log under whichever task reads it.
+ _ = DebugLogger.$pipelineID.withValue("unrelated-reader") { board.string(forType: .string) }
+ await self.waitUntil {
+ DebugLogger.shared.infoEvents.contains { $0.message.hasPrefix("PASTE_READ ") && $0.pipelineID == "receipt-trace" }
+ }
+ self.expect(!DebugLogger.shared.infoEvents.contains { $0.message.hasPrefix("PASTE_READ ") && $0.pipelineID == "unrelated-reader" })
+ coordinator.runPendingSettlementForTesting()
+ self.expect(board.string(forType: .string) == "original")
+ print("PASS: a clipboard read outside the request retains its original pipeline ID")
+ }
+}
+
+@MainActor
+private final class ReceiptObservingPasteboard: PasteboardManaging {
+ nonisolated deinit {}
+ let base: SystemPasteboardManager
+ var handlers: [@MainActor @Sendable (TimeInterval) -> Void] = []
+ init(board: NSPasteboard) { self.base = SystemPasteboardManager(pasteboard: board) }
+ var changeCount: Int { self.base.changeCount }
+ func captureSnapshot() -> PasteboardSnapshot? { self.base.captureSnapshot() }
+ func writeTemporaryText(_ text: String, sessionID: String) -> Bool { self.base.writeTemporaryText(text, sessionID: sessionID) }
+ func writeIntentionalText(_ text: String) -> Bool { self.base.writeIntentionalText(text) }
+ func isOwned(sessionID: String, expectedText: String) -> Bool { self.base.isOwned(sessionID: sessionID, expectedText: expectedText) }
+ func restore(_ snapshot: PasteboardSnapshot) -> Bool { self.base.restore(snapshot) }
+ func restoreTemporarySnapshot(_ snapshot: PasteboardSnapshot, sessionID: String, expectedText: String) -> Bool {
+ self.base.restoreTemporarySnapshot(snapshot, sessionID: sessionID, expectedText: expectedText)
+ }
+
+ func observeTemporaryTextRead(sessionID: String, onRead: @escaping @MainActor @Sendable (TimeInterval) -> Void) -> Bool {
+ self.handlers.append(onRead)
+ return self.base.observeTemporaryTextRead(sessionID: sessionID, onRead: onRead)
+ }
+}
+
+@MainActor
+private final class ReceiptTestPoster: PasteCommandPosting {
+ nonisolated deinit {}
+ var count = 0
+ func postGlobalPasteCommand() async -> Bool {
+ self.count += 1
+ return true
+ }
+}
diff --git a/Tests/PasteRecoveryPolicyTests.swift b/Tests/PasteRecoveryPolicyTests.swift
new file mode 100644
index 00000000..b431f73c
--- /dev/null
+++ b/Tests/PasteRecoveryPolicyTests.swift
@@ -0,0 +1,119 @@
+import AppKit
+import ApplicationServices
+
+@main
+@MainActor
+enum PasteRecoveryPolicyTests {
+ static let element = AXUIElementCreateApplication(getpid())
+
+ static func snapshot(_ value: String? = "", count: Int? = 0, caret: CFRange? = CFRange(location: 0, length: 0), element: AXUIElement? = nil) -> PasteVerifier.Snapshot {
+ .init(element: element ?? self.element, pid: getpid(), role: "AXTextArea", value: value, characterCount: count, caret: caret)
+ }
+
+ static func verify(_ before: PasteVerifier.Snapshot, _ after: [PasteVerifier.Snapshot?], text: String = "hello") async -> (PasteVerifier.Verdict, [TimeInterval]) {
+ var index = 0
+ var waits: [TimeInterval] = []
+ let result = await PasteVerifier.verify(
+ before: before,
+ pastedText: text,
+ capture: {
+ defer { index += 1 }
+ return after[min(index, after.count - 1)]
+ },
+ wait: { delay in waits.append(delay); return true }
+ )
+ return (result, waits)
+ }
+
+ static func main() async {
+ let before = self.snapshot()
+ let inserted = self.snapshot("hello", count: 5, caret: CFRange(location: 5, length: 0))
+ let late = await self.verify(before, [before, before, inserted])
+ precondition(late.0 == .confirmed(method: "value"))
+ precondition(late.1.reduce(0, +) == 2, "A late paste must get the full grace window")
+
+ let miss = await self.verify(before, [before, before, before])
+ precondition(miss.0 == .notLanded(reason: "value_count_caret_unchanged"))
+ precondition(miss.1.count == 3 && miss.1.reduce(0, +) == 2)
+
+ let noCount = self.snapshot(count: nil)
+ let result1 = await self.verify(noCount, [noCount]).0
+ precondition(result1 == .notLanded(reason: "value_count_caret_unchanged"))
+ let noValue = self.snapshot(nil)
+ let result2 = await self.verify(noValue, [noValue]).0
+ precondition(result2 == .notLanded(reason: "value_count_caret_unchanged"))
+ let noCaret = self.snapshot(caret: nil)
+ guard case .unknown = await self.verify(noCaret, [noCaret]).0 else { fatalError("Incomplete evidence must not warn") }
+
+ let changed = self.snapshot("other", count: 5, caret: CFRange(location: 2, length: 0))
+ // Use an equal-length replacement so unchanged-count evidence cannot
+ // mistake the unrelated editor change for a failed paste.
+ let selected = self.snapshot("xxxxx", count: 5, caret: CFRange(location: 0, length: 5))
+ guard case .unknown = await self.verify(selected, [changed]).0 else { fatalError("Other changes must stand down") }
+
+ let moved = self.snapshot(element: AXUIElementCreateSystemWide())
+ let result3 = await self.verify(before, [moved]).0
+ precondition(result3 == .unknown(reason: "focus_moved"))
+ let result4 = await self.verify(before, [nil]).0
+ precondition(result4 == .unknown(reason: "after_unreadable"))
+ let cancelled = await PasteVerifier.verify(before: before, pastedText: "hello", capture: { fatalError("Cancelled verification must not read AX") }, wait: { _ in false })
+ precondition(cancelled == .unknown(reason: "cancelled"))
+
+ let emojiBefore = self.snapshot(nil)
+ let emojiAfter = self.snapshot(nil, count: 2, caret: CFRange(location: 2, length: 0))
+ let result5 = await self.verify(emojiBefore, [emojiAfter], text: "😀").0
+ precondition(result5 == .confirmed(method: "count"))
+ let replacementAfter = self.snapshot(nil, count: 5, caret: CFRange(location: 5, length: 0))
+ let replacementBefore = self.snapshot(nil, count: 5, caret: CFRange(location: 0, length: 5))
+ let result6 = await self.verify(replacementBefore, [replacementAfter]).0
+ precondition(result6 == .confirmed(method: "caret"))
+
+ // A six-unit selection replaced by five units expects -1. The optional
+ // newline tolerance must never turn an unchanged count into success.
+ let longerSelection = self.snapshot("xxxxxx", count: 6, caret: CFRange(location: 0, length: 6))
+ let blockedReplacement = await self.verify(longerSelection, [longerSelection])
+ guard blockedReplacement.0 == .notLanded(reason: "value_count_caret_unchanged") else {
+ print("FAIL: a blocked six-to-five replacement was reported as successful: \(blockedReplacement.0)")
+ exit(1)
+ }
+ precondition(blockedReplacement.1.count == 3 && blockedReplacement.1.reduce(0, +) == 2)
+
+ let countOnlySelection = self.snapshot(nil, count: 6, caret: CFRange(location: 0, length: 6))
+ let blockedCountOnly = await self.verify(countOnlySelection, [countOnlySelection])
+ precondition(blockedCountOnly.0 == .notLanded(reason: "value_count_caret_unchanged"))
+ let shorterReplacement = await self.verify(countOnlySelection, [replacementAfter])
+ precondition(shorterReplacement.0 == .confirmed(method: "count"), "An actual shorter replacement must still confirm")
+
+ let selectedEmoji = self.snapshot(nil, count: 3, caret: CFRange(location: 0, length: 3))
+ let blockedEmoji = await self.verify(selectedEmoji, [selectedEmoji], text: "😀")
+ precondition(blockedEmoji.0 == .notLanded(reason: "value_count_caret_unchanged"))
+ let shorterEmoji = await self.verify(selectedEmoji, [emojiAfter], text: "😀")
+ precondition(shorterEmoji.0 == .confirmed(method: "count"))
+
+ let newlineAfter = self.snapshot(nil, count: 6, caret: nil)
+ let newlineInsertion = await self.verify(emojiBefore, [newlineAfter])
+ precondition(newlineInsertion.0 == .confirmed(method: "count"), "An actual +1 newline count change must still confirm")
+ let equalLengthWithNewline = await self.verify(replacementBefore, [newlineAfter])
+ precondition(equalLengthWithNewline.0 == .confirmed(method: "count"), "Equal-length replacement with an actual extra newline must still confirm")
+ let longerSelectionWithNewline = self.snapshot(nil, count: 8, caret: CFRange(location: 0, length: 8))
+ let shorterWithNewline = await self.verify(longerSelectionWithNewline, [newlineAfter])
+ precondition(shorterWithNewline.0 == .confirmed(method: "count"), "A shrinking replacement with newline tolerance must still confirm")
+ print("PASS: blocked one-unit-shorter replacements never confirm unchanged counts; real replacements, emoji and newline tolerance still confirm")
+
+ let policy = PasteRecoveryPresentationPolicy()
+ let first = policy.beginDelivery()
+ precondition(!policy.claim(first, alertsEnabled: false, isBusy: false, userActed: false))
+ precondition(!policy.claim(first, alertsEnabled: true, isBusy: true, userActed: false))
+ precondition(!policy.claim(first, alertsEnabled: true, isBusy: false, userActed: true))
+ precondition(policy.claim(first, alertsEnabled: true, isBusy: false, userActed: false), "Suppressed checks must not consume a valid recovery")
+ precondition(!policy.claim(first, alertsEnabled: true, isBusy: false, userActed: false), "A duplicate must not reopen the card")
+ let second = policy.beginDelivery()
+ precondition(!policy.claim(first, alertsEnabled: true, isBusy: false, userActed: false))
+ precondition(policy.claim(second, alertsEnabled: true, isBusy: false, userActed: false), "A distinct genuine miss must not be hidden by a cooldown")
+ let pending = policy.beginDelivery()
+ _ = policy.beginDelivery() // New recording supersedes a pending check.
+ precondition(!policy.claim(pending, alertsEnabled: true, isBusy: false, userActed: false))
+ print("PASS: late insertion, definite misses, partial signals, changed fields, focus loss, unreadable/cancelled checks, UTF-16, selection replacement")
+ print("PASS: opt-out, busy/user activity suppression, duplicate/stale checks and distinct genuine failures")
+ }
+}
diff --git a/Tests/Support/ClipboardBackupStandaloneSupport.swift b/Tests/Support/ClipboardBackupStandaloneSupport.swift
index 661604df..7c189372 100644
--- a/Tests/Support/ClipboardBackupStandaloneSupport.swift
+++ b/Tests/Support/ClipboardBackupStandaloneSupport.swift
@@ -4,8 +4,13 @@ import AppKit
// The production delivery coordinator and pasteboard implementation are compiled unchanged.
// Fatal keyboard getters prevent this isolated harness from ever posting real keys.
enum TypingService {
+ #if PASTE_EVENT_CONSTRUCTION_TESTS
+ static let pasteVirtualKeyCode: CGKeyCode = 9
+ static let synthesizedEventUserData: Int64 = 0x46565353
+ #else
static var pasteVirtualKeyCode: CGKeyCode { fatalError("Real keyboard posting is forbidden in this harness") }
static var synthesizedEventUserData: Int64 { fatalError("Real keyboard posting is forbidden in this harness") }
+ #endif
}
enum ClipboardAudit {
@@ -13,6 +18,20 @@ enum ClipboardAudit {
}
final class DebugLogger {
+ @TaskLocal static var pipelineID: String?
static let shared = DebugLogger()
+ private let lock = NSLock()
+ private var events: [(message: String, pipelineID: String?)] = []
+ var infoEvents: [(message: String, pipelineID: String?)] {
+ self.lock.lock()
+ defer { self.lock.unlock() }
+ return self.events
+ }
+
func benchmark(_ category: String, message: String, source: String) {}
+ func info(_ message: String, source: String) {
+ self.lock.lock()
+ self.events.append((message, Self.pipelineID))
+ self.lock.unlock()
+ }
}
diff --git a/Tests/run_ci_checks.sh b/Tests/run_ci_checks.sh
new file mode 100644
index 00000000..d2a94c9e
--- /dev/null
+++ b/Tests/run_ci_checks.sh
@@ -0,0 +1,122 @@
+#!/bin/bash
+# The same regression and Xcode test sequence locally and on GitHub Actions.
+set -euo pipefail
+cd "$(dirname "$0")/.."
+
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+if [ ! -d "$task_developer_dir/Platforms/MacOSX.platform" ]; then
+ echo "Full Xcode is required; set DEVELOPER_DIR to an installed Xcode.app." >&2
+ exit 1
+fi
+export DEVELOPER_DIR="$task_developer_dir"
+task_result_dir="${CI_RESULT_DIR:-build/test-results/local-ci-$(date -u +%Y%m%dT%H%M%SZ)}"
+mkdir -p "$task_result_dir"
+
+task_tree_fingerprint() {
+ python3 - <<'PY'
+import hashlib, os, pathlib, subprocess
+paths = subprocess.check_output(['git', 'ls-files', '-z', '--cached', '--others', '--exclude-standard']).split(b'\0')
+digest = hashlib.sha256()
+for raw in sorted(set(paths) - {b''}):
+ path = pathlib.Path(os.fsdecode(raw))
+ digest.update(raw + b'\0')
+ if path.is_symlink():
+ digest.update(b'link:' + os.fsencode(os.readlink(path)))
+ elif path.is_file():
+ digest.update(str(path.stat().st_mode & 0o777).encode() + b':')
+ digest.update(path.read_bytes())
+ else:
+ digest.update(b'deleted')
+print(digest.hexdigest())
+PY
+}
+task_start_tree="$(task_tree_fingerprint)"
+{
+ git rev-parse HEAD
+ echo "tree=$task_start_tree"
+ sw_vers
+ xcodebuild -version
+} > "$task_result_dir/environment.txt"
+
+task_phase="preflight"
+trap 'task_status=$?; if [ "$task_status" != 0 ]; then echo "CI check failed: $task_phase (exit $task_status); results: $task_result_dir" >&2; fi' EXIT
+run_check() {
+ task_phase="$1"
+ shift
+ echo "Running: $task_phase"
+ "$@"
+}
+
+# Fail before the suite when a signed local test host cannot be built.
+if [ "${GITHUB_ACTIONS:-false}" != "true" ]; then
+ task_phase="Apple Development signing preflight"
+ task_signing_team="${DEVELOPMENT_TEAM:-$(python3 - <<'PYTEAM'
+import pathlib, re
+teams = set(re.findall(r'DEVELOPMENT_TEAM = ([A-Z0-9]+);', pathlib.Path('Fluid.xcodeproj/project.pbxproj').read_text()))
+if len(teams) == 1:
+ print(teams.pop())
+PYTEAM
+)}"
+ if [ -z "$task_signing_team" ]; then
+ echo "Set DEVELOPMENT_TEAM to your Apple Development signing team." >&2
+ exit 1
+ fi
+ if ! python3 - "$task_signing_team" <<'PYCERT'
+import re, subprocess, sys
+identities = subprocess.check_output(['security', 'find-identity', '-v', '-p', 'codesigning'], text=True)
+for label in re.findall(r'"(Apple Development:[^"\n]+|Mac Developer:[^"\n]+)"', identities):
+ certificate = subprocess.run(['security', 'find-certificate', '-c', label, '-p'], capture_output=True).stdout
+ subject = subprocess.run(['openssl', 'x509', '-noout', '-subject', '-nameopt', 'RFC2253'], input=certificate, capture_output=True).stdout.decode()
+ team = re.search(r'(?:^|,)OU=([^,]+)', subject)
+ if team and team.group(1) == sys.argv[1]:
+ sys.exit(0)
+sys.exit(1)
+PYCERT
+ then
+ echo "No Apple Development identity with a private key matches DEVELOPMENT_TEAM=$task_signing_team. Set DEVELOPMENT_TEAM to an installed development identity's team, or configure that certificate in Xcode. Local unsigned/ad-hoc tests are not allowed." >&2
+ exit 1
+ fi
+fi
+
+# CI already gates this job on its Linux SwiftLint job. Local runs must perform
+# that check too; formatting validation must not silently edit the tested tree.
+if [ "${GITHUB_ACTIONS:-false}" != "true" ]; then
+ run_check formatting swiftformat --lint --config .swiftformat Sources
+ run_check lint swiftlint --strict --config .swiftlint.yml Sources Tests Package.swift
+fi
+run_check clipboard sh Tests/run_clipboard_backup_reproduction.sh
+run_check clipboard-read-receipts sh Tests/run_paste_read_receipt_tests.sh
+run_check paste-events sh Tests/run_paste_command_event_tests.sh
+run_check keyboard-layouts sh Tests/run_paste_key_cache_tests.sh
+run_check paste-recovery sh Tests/run_paste_recovery_policy_tests.sh
+run_check accessibility-preparation sh Tests/run_dictation_accessibility_preparation_tests.sh
+run_check onboarding sh Tests/run_onboarding_tests.sh
+run_check release-highlights sh Tests/run_release_highlights_tests.sh
+run_check history-decode sh Tests/run_history_decode_recovery_tests.sh
+run_check settings-backup python3 Tests/run_settings_backup_concurrency_tests.py
+run_check meeting-backup python3 Tests/run_meeting_backup_refresh_tests.py
+
+task_phase="Xcode build and tests"
+task_build_args=(test -project Fluid.xcodeproj -scheme Fluid
+ -destination "platform=macOS,arch=$(uname -m)"
+ -resultBundlePath "$task_result_dir/Fluid.xcresult"
+ -skip-testing:FluidDictationIntegrationTests/DictationE2ETests/testDictationEndToEnd_whisperTiny_transcribesFixture)
+# Unsigned test hosts are permitted only on GitHub Actions. Local Debug builds
+# keep their Apple Development identity and existing permissions.
+if [ "${GITHUB_ACTIONS:-false}" = "true" ]; then
+ task_build_args+=(CODE_SIGN_IDENTITY= CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO)
+else
+ task_build_args+=(CODE_SIGN_IDENTITY='Apple Development' CODE_SIGNING_REQUIRED=YES CODE_SIGNING_ALLOWED=YES "DEVELOPMENT_TEAM=$task_signing_team")
+fi
+if command -v xcpretty >/dev/null 2>&1; then
+ xcodebuild "${task_build_args[@]}" 2>&1 | tee "$task_result_dir/xcodebuild.log" | xcpretty
+else
+ xcodebuild "${task_build_args[@]}" 2>&1 | tee "$task_result_dir/xcodebuild.log"
+fi
+
+task_phase="source tree verification"
+if [ "$task_start_tree" != "$(task_tree_fingerprint)" ]; then
+ echo "Source tree changed during validation. Rerun the gate on the final tree." >&2
+ exit 1
+fi
+echo "PASS: complete CI sequence; tree=$task_start_tree" | tee "$task_result_dir/result.txt"
diff --git a/Tests/run_dictation_accessibility_preparation_tests.sh b/Tests/run_dictation_accessibility_preparation_tests.sh
new file mode 100644
index 00000000..ad326320
--- /dev/null
+++ b/Tests/run_dictation_accessibility_preparation_tests.sh
@@ -0,0 +1,13 @@
+#!/bin/sh
+set -eu
+cd "$(dirname "$0")/.."
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+test -d "$task_developer_dir/Platforms/MacOSX.platform"
+export DEVELOPER_DIR="$task_developer_dir"
+task_test_dir=$(mktemp -d /tmp/fluidvoice-accessibility-tests.XXXXXX)
+trap 'rm -rf "$task_test_dir"' EXIT
+xcrun swiftc -O -parse-as-library \
+ Sources/Fluid/Services/DictationAccessibilityPreparation.swift \
+ Tests/DictationAccessibilityPreparationTests.swift \
+ -o "$task_test_dir/tests"
+"$task_test_dir/tests"
diff --git a/Tests/run_paste_command_event_tests.sh b/Tests/run_paste_command_event_tests.sh
new file mode 100644
index 00000000..28bec59f
--- /dev/null
+++ b/Tests/run_paste_command_event_tests.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+set -eu
+cd "$(dirname "$0")/.."
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+test -d "$task_developer_dir/Platforms/MacOSX.platform"
+export DEVELOPER_DIR="$task_developer_dir"
+task_test_dir=$(mktemp -d /tmp/fluidvoice-paste-event-tests.XXXXXX)
+trap 'rm -rf "$task_test_dir"' EXIT
+xcrun swiftc -O -parse-as-library -D PASTE_EVENT_CONSTRUCTION_TESTS \
+ Sources/Fluid/Services/PasteDeliveryCoordinator.swift \
+ Sources/Fluid/Services/DictationTargetPolicy.swift \
+ Tests/Support/ClipboardBackupStandaloneSupport.swift \
+ Tests/PasteCommandEventTests.swift \
+ -o "$task_test_dir/tests"
+"$task_test_dir/tests"
diff --git a/Tests/run_paste_read_receipt_tests.sh b/Tests/run_paste_read_receipt_tests.sh
new file mode 100644
index 00000000..b0f0e822
--- /dev/null
+++ b/Tests/run_paste_read_receipt_tests.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+set -eu
+cd "$(dirname "$0")/.."
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+test -d "$task_developer_dir/Platforms/MacOSX.platform"
+export DEVELOPER_DIR="$task_developer_dir"
+task_test_dir=$(mktemp -d /tmp/fluidvoice-read-receipt-tests.XXXXXX)
+trap 'rm -rf "$task_test_dir"' EXIT
+xcrun swiftc -O -parse-as-library \
+ Sources/Fluid/Services/PasteDeliveryCoordinator.swift \
+ Sources/Fluid/Services/DictationTargetPolicy.swift \
+ Tests/Support/ClipboardBackupStandaloneSupport.swift \
+ Tests/PasteReadReceiptReproductionTests.swift \
+ -o "$task_test_dir/tests"
+"$task_test_dir/tests"
diff --git a/Tests/run_paste_recovery_policy_tests.sh b/Tests/run_paste_recovery_policy_tests.sh
new file mode 100644
index 00000000..ba72b93a
--- /dev/null
+++ b/Tests/run_paste_recovery_policy_tests.sh
@@ -0,0 +1,13 @@
+#!/bin/sh
+set -eu
+cd "$(dirname "$0")/.."
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+test -d "$task_developer_dir/Platforms/MacOSX.platform"
+export DEVELOPER_DIR="$task_developer_dir"
+task_test_dir=$(mktemp -d /tmp/fluidvoice-paste-recovery-tests.XXXXXX)
+trap 'rm -rf "$task_test_dir"' EXIT
+xcrun swiftc -O -parse-as-library \
+ Sources/Fluid/Services/PasteVerifier.swift \
+ Tests/PasteRecoveryPolicyTests.swift \
+ -o "$task_test_dir/tests"
+"$task_test_dir/tests"