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

42.3 KB
Raw Blame
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"
    case noEditableTarget = "no_editable_target"
    case pasteNotLanded = "paste_not_landed"

    var userFacingMessage: String? {
        switch self {
        case .accessibilityNotTrusted:
            "Enable Accessibility to insert text"
        case .noEditableTarget:
            "No text field focused"
        case .pasteNotLanded, .clipboardSnapshotFailed, .clipboardWriteFailed,
             .pasteCommandFailed, .targetUnavailable, .targetRestoreFailed:
            "Oops, text wasn't inserted"
        case .emptyText:
            nil
        }
    }

    /// Second line shown under the title in the overlay failure card.
    static func userFacingDetail(forMessage message: String) -> String? {
        switch message {
        case TextDeliveryFailure.accessibilityNotTrusted.userFacingMessage:
            nil
        default:
            "Your transcript is saved. Copy it and paste it into a text field."
        }
    }
}

enum TextDeliveryResult: Equatable {
    case cancelled
    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 {
    var changeCount: Int { get }
    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
    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
protocol PasteCommandPosting: AnyObject {
    func postGlobalPasteCommand() async -> Bool
}

@MainActor
final class SystemPasteboardManager: PasteboardManaging {
    // Explicitly nonisolated: on macOS 15.4+ the synthesized main-actor deinit can abort until the OS runtime has the fix (swiftlang/swift#88036).
    nonisolated deinit {}

    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 concealedType = NSPasteboard.PasteboardType("org.nspasteboard.ConcealedType")
    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)?
    private var temporaryTextProvider: (sessionID: String, provider: TemporaryPasteboardTextProvider)?

    init(pasteboard: NSPasteboard = .general) {
        self.pasteboard = pasteboard
    }

    var changeCount: Int { self.pasteboard.changeCount }

    func recordAudit(_ event: String, detail: String) {
        ClipboardAudit.record(event, pasteboard: self.pasteboard, detail: detail)
    }

    /// A representation larger than this is left out of the snapshot: the
    /// paste must never wait on copying it, and the small ones (strings, file
    /// URLs) still restore. A missing snapshot would block the paste, so an
    /// oversized clipboard yields a smaller snapshot rather than none.
    static let maximumRepresentationBytes = 32 * 1024 * 1024
    /// Decoding and re-encoding an image to PNG costs time proportional to its
    /// pixels; skip it for large sources and keep their original bytes only.
    static let maximumPortableImageSourceBytes = 16 * 1024 * 1024

    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 skippedBytes = 0
            var skippedTypes: [String] = []
            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] = []
                var skippedOversizedRepresentation = false
                representations.reserveCapacity(sourceTypes.count)
                for type in sourceTypes {
                    guard let data = sourceItem.data(forType: type) else {
                        failure = ("unavailable_representation", itemIndex, type)
                        break itemLoop
                    }
                    guard data.count <= Self.maximumRepresentationBytes else {
                        skippedOversizedRepresentation = true
                        skippedBytes += data.count
                        skippedTypes.append(type.rawValue)
                        continue
                    }
                    representations.append(.init(type: type, data: data))
                    totalBytes += data.count
                    totalRepresentations += 1
                }
                // File URLs are small references, not file contents. Preserve them and
                // offer a plain filename when a large accompanying payload was omitted.
                if skippedOversizedRepresentation,
                   !representations.contains(where: { $0.type == .string }),
                   let fileData = representations.first(where: { $0.type == .fileURL })?.data,
                   let url = URL(dataRepresentation: fileData, relativeTo: nil, isAbsolute: true),
                   url.isFileURL, !url.lastPathComponent.isEmpty
                {
                    let nameData = Data(url.lastPathComponent.utf8)
                    representations.append(.init(type: .string, data: nameData))
                    totalBytes += nameData.count
                    totalRepresentations += 1
                }
                guard !representations.isEmpty else { continue }
                let item = PasteboardSnapshot.Item(representations: representations)
                let portableImage = skippedOversizedRepresentation ? nil : 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) " +
                    "skippedBytes=\(skippedBytes) skippedTypes=\(skippedTypes.joined(separator: ",")) " +
                    "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()
        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),
              item.setData(Data(), forType: Self.concealedType),
              item.setString(sessionID, forType: Self.sessionType)
        else {
            return false
        }

        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) {
            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 }

        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
    }

    func isOwned(sessionID: String, expectedText: String) -> Bool {
        ClipboardAudit.record("ownership_check", pasteboard: self.pasteboard, detail: "session=\(sessionID) expectedChangeCount=\(self.temporaryWrite?.changeCount ?? -1)")
        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 {
        // 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 }
        let restored = self.restore(snapshot, ifUnchangedSince: temporaryWrite.changeCount)
        self.temporaryTextProvider = nil
        return restored
    }

    func restore(_ snapshot: PasteboardSnapshot) -> Bool {
        self.restore(snapshot, ifUnchangedSince: nil)
    }

    private func restore(_ snapshot: PasteboardSnapshot, ifUnchangedSince changeCount: Int?) -> Bool {
        guard !snapshot.items.isEmpty else {
            // Every representation was too large to keep; leave the transcript
            // on the clipboard rather than clearing it.
            self.log("clipboard_restore_skipped reason=nothing_captured")
            return true
        }
        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)
        }

        ClipboardAudit.record("restore_begin", pasteboard: self.pasteboard, detail: "expectedChangeCount=\(changeCount ?? -1)")
        defer { ClipboardAudit.record("restore_end", pasteboard: self.pasteboard) }
        // 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,
                  representation.data.count <= Self.maximumPortableImageSourceBytes,
                  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: @autoclosure () -> 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
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()
        guard !events.isEmpty else { return false }

        // 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: Self.pasteEventTapLocation)
        }
        return true
    }

    /// 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 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 []
        }

        vDown.flags = Self.commandFlags
        vUp.flags = Self.commandFlags
        // Mark the paste as ours so the hotkey tap passes it through untouched.
        let events = [vDown, vUp]
        for event in events {
            event.setIntegerValueField(.eventSourceUserData, value: TypingService.synthesizedEventUserData)
        }
        return events
    }
}

@MainActor
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
        let sessionID: String
        let text: String
        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
    private var deliveryWaiters: [CheckedContinuation<Void, Never>] = []
    private var lastWrittenChangeCount: Int?

    init(
        pasteboard: PasteboardManaging? = nil,
        commandPoster: PasteCommandPosting? = nil,
        settlementDelayNanoseconds: UInt64 = PasteDeliveryCoordinator.defaultSettlementDelayNanoseconds,
        readTimeoutNanoseconds: UInt64 = PasteDeliveryCoordinator.defaultReadTimeoutNanoseconds
    ) {
        self.pasteboard = pasteboard ?? SystemPasteboardManager()
        self.commandPoster = commandPoster ?? SystemPasteCommandPoster()
        self.settlementDelayNanoseconds = settlementDelayNanoseconds
        self.readTimeoutNanoseconds = readTimeoutNanoseconds
    }

    func deliver(
        _ text: String,
        preserveTranscriptOnClipboard: Bool,
        isOutputValid: @escaping @MainActor () -> Bool = { true },
        onCommandPosted: ((TimeInterval) -> Void)? = nil
    ) async -> TextDeliveryResult {
        guard isOutputValid() else { return .cancelled }
        self.log("delivery_policy keepTranscript=\(preserveTranscriptOnClipboard) auditSchema=1")
        let slotRequestedAt = ProcessInfo.processInfo.systemUptime
        await self.acquireDeliverySlot()
        let slotAcquiredAt = ProcessInfo.processInfo.systemUptime
        var settlementOwnsSlot = false
        defer {
            if !settlementOwnsSlot { self.releaseDeliverySlot() }
        }

        guard isOutputValid() else { return .cancelled }
        let startedAt = ProcessInfo.processInfo.systemUptime
        self.generation &+= 1
        let generation = self.generation
        self.log("clipboard_slot_acquired generation=\(generation) waitMs=\((slotAcquiredAt - slotRequestedAt) * 1000)")
        let originalChangeCount = self.pasteboard.changeCount
        let originalSnapshot = self.pasteboard.captureSnapshot()

        guard let originalSnapshot else {
            if preserveTranscriptOnClipboard, self.pasteboard.changeCount == originalChangeCount {
                self.writeBackup(text)
            }
            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.finishFailedDelivery(originalSnapshot, sessionID: sessionID, text: text, originalChangeCount: originalChangeCount, keepBackup: preserveTranscriptOnClipboard)
            self.log("delivery_failed generation=\(generation) reason=clipboard_write_failed")
            return .recoverableFailure(.clipboardWriteFailed)
        }
        self.lastWrittenChangeCount = self.pasteboard.changeCount
        self.log(
            "clipboard_write generation=\(generation) elapsedMs=\(Self.elapsedMs(since: writeStartedAt))"
        )

        self.pasteboard.recordAudit("command_before", detail: "session=\(sessionID)")
        guard isOutputValid() else {
            self.finishFailedDelivery(originalSnapshot, sessionID: sessionID, text: text, originalChangeCount: originalChangeCount, keepBackup: false)
            return .cancelled
        }
        let commandPosted = await self.commandPoster.postGlobalPasteCommand()
        let commandPostedAt = ProcessInfo.processInfo.systemUptime
        self.pasteboard.recordAudit("command_after", detail: "session=\(sessionID) success=\(commandPosted)")
        guard commandPosted else {
            self.finishFailedDelivery(originalSnapshot, sessionID: sessionID, text: text, originalChangeCount: originalChangeCount, keepBackup: preserveTranscriptOnClipboard && isOutputValid())
            if !isOutputValid() { return .cancelled }
            self.log("delivery_failed generation=\(generation) reason=paste_command_failed")
            return .recoverableFailure(.pasteCommandFailed)
        }
        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,
            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
        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
    }

    /// Keep backup independent of destination readiness, including callers that never enter typing.
    func prepareForDelivery(
        _ text: String,
        preserveTranscriptOnClipboard: Bool,
        isOutputValid: @escaping @MainActor () -> Bool = { true },
        prepare: () async -> Bool
    ) async -> Bool {
        guard isOutputValid() else { return false }
        let changeCount = self.pasteboard.changeCount
        let generation = self.generation
        let ready = await prepare()
        guard isOutputValid() else { return false }
        if !ready, self.generation == generation {
            await self.copyBackup(text, enabled: preserveTranscriptOnClipboard, expectedChangeCount: changeCount, isOutputValid: isOutputValid)
        }
        return ready
    }

    /// Serialize standalone copies with active paste leases so cleanup cannot undo the backup.
    @discardableResult
    func copyBackup(_ text: String, enabled: Bool, expectedChangeCount: Int? = nil, isOutputValid: @escaping @MainActor () -> Bool = { true }) async -> Bool {
        guard enabled, isOutputValid(), !text.isEmpty else { return false }
        let requestedChangeCount = expectedChangeCount ?? self.pasteboard.changeCount
        await self.acquireDeliverySlot()
        defer { self.releaseDeliverySlot() }
        guard isOutputValid() else { return false }
        guard self.pasteboard.changeCount == requestedChangeCount ||
            self.pasteboard.changeCount == self.lastWrittenChangeCount
        else {
            self.log("backup_skipped reason=newer_clipboard_copy")
            return false
        }
        self.generation &+= 1
        return self.writeBackup(text)
    }

    @discardableResult
    private func writeBackup(_ text: String) -> Bool {
        guard !text.isEmpty else { return false }
        let copied = self.pasteboard.writeIntentionalText(text)
        if copied { self.lastWrittenChangeCount = self.pasteboard.changeCount }
        self.log("backup_copy success=\(copied)")
        return copied
    }

    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 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: delayNanoseconds)
            guard !Task.isCancelled else { return }
            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=\(delayNanoseconds / 1_000_000)")
    }

    private func settleIfCurrent(sessionID: String, generation: UInt64, readTimedOut: Bool = false) {
        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
        }

        let restoreStartedAt = ProcessInfo.processInfo.systemUptime
        // 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)
            if didRestore { self.lastWrittenChangeCount = self.pasteboard.changeCount }
            self.log("restore_completed generation=\(generation) success=\(didRestore) elapsedMs=\((ProcessInfo.processInfo.systemUptime - restoreStartedAt) * 1000)")
        }
    }

    private func finishFailedDelivery(
        _ snapshot: PasteboardSnapshot,
        sessionID: String,
        text: String,
        originalChangeCount: Int,
        keepBackup: Bool
    ) {
        if keepBackup, self.pasteboard.isOwned(sessionID: sessionID, expectedText: text) ||
            self.pasteboard.changeCount == originalChangeCount
        {
            self.writeBackup(text)
            return
        }
        // A partial write may have cleared the board without installing our text. The
        // manager can still restore that owned revision, but must leave newer copies alone.
        let restored = self.pasteboard.restoreTemporarySnapshot(snapshot, sessionID: sessionID, expectedText: text)
        if restored {
            self.lastWrittenChangeCount = self.pasteboard.changeCount
            if keepBackup { self.writeBackup(text) }
        }
        self.log("failure_restore success=\(restored)")
    }

    private func log(_ message: @autoclosure () -> 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())
    }
}