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

fix(clipboard): preserve enabled transcription backup when delivery fails

altic-dev7d6d0e7caeb1
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 407e3687..e1c9ae98 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -2885,8 +2885,7 @@ struct ContentView: View {
// When FluidVoice itself is frontmost, the bound editor already receives `finalText`.
let shouldCopyToClipboard = shouldPersistOutputs &&
!sendsExistingDraft &&
- SettingsStore.shared.copyTranscriptionToClipboard &&
- !isFluidFrontmost
+ SettingsStore.shared.copyTranscriptionToClipboard
let shouldTypeExternally = shouldPersistOutputs && !isFluidFrontmost
var didTypeExternally = false
@@ -2910,12 +2909,9 @@ struct ContentView: View {
&& !self.isSpokenSendBlockedApp(appInfo)
// Dispatch insertion as soon as the destination app is ready; the
// overlay hides asynchronously after output so it cannot delay paste.
- let focusReady: Bool
- if typingTarget.shouldRestoreOriginalFocus {
- focusReady = await self.restoreFocusToRecordingTarget()
- } else {
- focusReady = true
- }
+ let focusReady = await self.prepareRecordingTargetForDelivery(
+ finalText, keepBackup: shouldCopyToClipboard, needsRestoration: typingTarget.shouldRestoreOriginalFocus
+ )
if spokenSendAllowed {
NotchContentState.shared.setSpokenSendIndicatorState(.sending)
@@ -3003,6 +2999,10 @@ struct ContentView: View {
}
}
+ if !shouldTypeExternally {
+ await PasteDeliveryCoordinator.shared.copyBackup(finalText, enabled: shouldCopyToClipboard)
+ }
+
// Submit raw fallback delivery before failure UI or notification work can
// compete with it on the main actor. Sandbox runs never present either.
if shouldShowAIProcessingFailure {
@@ -3623,7 +3623,7 @@ struct ContentView: View {
NotchOverlayManager.shared.updateTranscriptionText("Inserting")
let typingTarget = self.resolveTypingTargetPID()
if typingTarget.shouldRestoreOriginalFocus,
- !(await self.restoreFocusToRecordingTarget())
+ !(await self.prepareRecordingTargetForDelivery(transcript, keepBackup: SettingsStore.shared.copyTranscriptionToClipboard))
{
self.showTextDeliveryFailure(.targetRestoreFailed, transcript: transcript)
return
@@ -3740,7 +3740,7 @@ struct ContentView: View {
if shouldTypeExternally {
let typingTarget = self.resolveTypingTargetPID()
if typingTarget.shouldRestoreOriginalFocus {
- guard await self.restoreFocusToRecordingTarget() else {
+ guard await self.prepareRecordingTargetForDelivery(finalText, keepBackup: SettingsStore.shared.copyTranscriptionToClipboard) else {
self.showTextDeliveryFailure(.targetRestoreFailed, transcript: finalText)
return
}
@@ -3753,8 +3753,8 @@ struct ContentView: View {
if case let .recoverableFailure(failure) = result {
self.showTextDeliveryFailure(failure, transcript: finalText)
}
- } else if SettingsStore.shared.copyTranscriptionToClipboard {
- ClipboardService.copyToClipboard(finalText)
+ } else {
+ await PasteDeliveryCoordinator.shared.copyBackup(finalText, enabled: SettingsStore.shared.copyTranscriptionToClipboard)
}
}
@@ -3869,7 +3869,7 @@ struct ContentView: View {
if shouldTypeExternally {
let typingTarget = self.resolveTypingTargetPID()
if typingTarget.shouldRestoreOriginalFocus {
- guard await self.restoreFocusToRecordingTarget() else {
+ guard await self.prepareRecordingTargetForDelivery(finalText, keepBackup: SettingsStore.shared.copyTranscriptionToClipboard) else {
self.showTextDeliveryFailure(.targetRestoreFailed, transcript: finalText)
return
}
@@ -3883,8 +3883,8 @@ struct ContentView: View {
self.showTextDeliveryFailure(failure, transcript: finalText)
return
}
- } else if SettingsStore.shared.copyTranscriptionToClipboard {
- ClipboardService.copyToClipboard(finalText)
+ } else {
+ await PasteDeliveryCoordinator.shared.copyBackup(finalText, enabled: SettingsStore.shared.copyTranscriptionToClipboard)
}
NotchOverlayManager.shared.updateTranscriptionText("")
@@ -3927,7 +3927,7 @@ struct ContentView: View {
// Type the rewritten text
let typingTarget = self.resolveTypingTargetPID()
if typingTarget.shouldRestoreOriginalFocus {
- guard await self.restoreFocusToRecordingTarget() else {
+ guard await self.prepareRecordingTargetForDelivery(self.rewriteModeService.rewrittenText, keepBackup: SettingsStore.shared.copyTranscriptionToClipboard) else {
self.showTextDeliveryFailure(
.targetRestoreFailed,
transcript: self.rewriteModeService.rewrittenText
@@ -4148,6 +4148,13 @@ struct ContentView: View {
}
/// Restores only the window and element captured when recording started.
+ private func prepareRecordingTargetForDelivery(_ transcript: String, keepBackup: Bool, needsRestoration: Bool = true) async -> Bool {
+ guard needsRestoration else { return true }
+ return await PasteDeliveryCoordinator.shared.prepareForDelivery(transcript, preserveTranscriptOnClipboard: keepBackup) {
+ await self.restoreFocusToRecordingTarget()
+ }
+ }
+
private func restoreFocusToRecordingTarget() async -> Bool {
guard let context = NotchContentState.shared.recordingTargetContext else { return false }
let pid = context.pid
diff --git a/Sources/Fluid/Services/PasteDeliveryCoordinator.swift b/Sources/Fluid/Services/PasteDeliveryCoordinator.swift
index d90ccb94..2a22fef4 100644
--- a/Sources/Fluid/Services/PasteDeliveryCoordinator.swift
+++ b/Sources/Fluid/Services/PasteDeliveryCoordinator.swift
@@ -55,6 +55,7 @@ struct PasteboardSnapshot: Equatable {
@MainActor
protocol PasteboardManaging: AnyObject {
+ var changeCount: Int { get }
func captureSnapshot() -> PasteboardSnapshot?
func writeTemporaryText(_ text: String, sessionID: String) -> Bool
func writeIntentionalText(_ text: String) -> Bool
@@ -97,6 +98,8 @@ final class SystemPasteboardManager: PasteboardManaging {
self.pasteboard = pasteboard
}
+ var changeCount: Int { self.pasteboard.changeCount }
+
func recordAudit(_ event: String, detail: String) {
ClipboardAudit.record(event, pasteboard: self.pasteboard, detail: detail)
}
@@ -558,6 +561,7 @@ final class PasteDeliveryCoordinator {
private var lease: ClipboardLease?
private var isDelivering = false
private var deliveryWaiters: [CheckedContinuation<Void, Never>] = []
+ private var lastWrittenChangeCount: Int?
init(
pasteboard: PasteboardManaging? = nil,
@@ -587,9 +591,13 @@ final class PasteDeliveryCoordinator {
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)
}
@@ -597,10 +605,11 @@ final class PasteDeliveryCoordinator {
let sessionID = UUID().uuidString
let writeStartedAt = ProcessInfo.processInfo.systemUptime
guard self.pasteboard.writeTemporaryText(text, sessionID: sessionID) else {
- self.restoreAfterFailure(originalSnapshot, sessionID: sessionID, expectedText: text, generation: generation, reason: "clipboard_write_failed")
+ 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))"
)
@@ -610,7 +619,7 @@ final class PasteDeliveryCoordinator {
let commandPostedAt = ProcessInfo.processInfo.systemUptime
self.pasteboard.recordAudit("command_after", detail: "session=\(sessionID) success=\(commandPosted)")
guard commandPosted else {
- self.restoreAfterFailure(originalSnapshot, sessionID: sessionID, expectedText: text, generation: generation, reason: "paste_command_failed")
+ self.finishFailedDelivery(originalSnapshot, sessionID: sessionID, text: text, originalChangeCount: originalChangeCount, keepBackup: preserveTranscriptOnClipboard)
self.log("delivery_failed generation=\(generation) reason=paste_command_failed")
return .recoverableFailure(.pasteCommandFailed)
}
@@ -635,6 +644,47 @@ final class PasteDeliveryCoordinator {
return .commandPosted
}
+ /// Keep backup independent of destination readiness, including callers that never enter typing.
+ func prepareForDelivery(
+ _ text: String,
+ preserveTranscriptOnClipboard: Bool,
+ prepare: () async -> Bool
+ ) async -> Bool {
+ let changeCount = self.pasteboard.changeCount
+ let generation = self.generation
+ let ready = await prepare()
+ if !ready, self.generation == generation {
+ await self.copyBackup(text, enabled: preserveTranscriptOnClipboard, expectedChangeCount: changeCount)
+ }
+ 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) async -> Bool {
+ guard enabled, !text.isEmpty else { return false }
+ let requestedChangeCount = expectedChangeCount ?? self.pasteboard.changeCount
+ await self.acquireDeliverySlot()
+ defer { self.releaseDeliverySlot() }
+ 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
@@ -692,23 +742,36 @@ final class PasteDeliveryCoordinator {
let restoreStartedAt = ProcessInfo.processInfo.systemUptime
if lease.shouldKeepTranscript {
- let didWrite = self.pasteboard.writeIntentionalText(lease.text)
+ let didWrite = self.writeBackup(lease.text)
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 restoreAfterFailure(
+ private func finishFailedDelivery(
_ snapshot: PasteboardSnapshot,
sessionID: String,
- expectedText: String,
- generation: UInt64,
- reason: String
+ text: String,
+ originalChangeCount: Int,
+ keepBackup: Bool
) {
- let didRestore = self.pasteboard.restoreTemporarySnapshot(snapshot, sessionID: sessionID, expectedText: expectedText)
- self.log("failure_restore generation=\(generation) reason=\(reason) success=\(didRestore)")
+ 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) {
diff --git a/Sources/Fluid/Services/TypingService.swift b/Sources/Fluid/Services/TypingService.swift
index db7b1d17..9e356d57 100644
--- a/Sources/Fluid/Services/TypingService.swift
+++ b/Sources/Fluid/Services/TypingService.swift
@@ -490,6 +490,7 @@ final class TypingService {
// Check accessibility permissions first
guard AXIsProcessTrusted() else {
+ await PasteDeliveryCoordinator.shared.copyBackup(text, enabled: preserveTranscriptOnClipboard)
self.bench("request_return reason=accessibility_not_trusted")
self.log("[TypingService] ERROR: Accessibility permissions required for text injection")
self.log("[TypingService] Current accessibility status: \(AXIsProcessTrusted())")
@@ -518,9 +519,7 @@ final class TypingService {
)
} else if await self.insertTextDirectlyOffMain(text, preferredTargetPID: preferredTargetPID) {
deliveryPath = .direct
- if preserveTranscriptOnClipboard {
- _ = ClipboardService.copyToClipboard(text)
- }
+ await PasteDeliveryCoordinator.shared.copyBackup(text, enabled: preserveTranscriptOnClipboard)
result = .commandPosted
} else {
deliveryPath = .clipboardFallback
@@ -575,6 +574,7 @@ final class TypingService {
exactFocusIsActive: Self.isExactFocusTargetActive(requiredFocusTarget)
)
else {
+ await PasteDeliveryCoordinator.shared.copyBackup(plan.plainText, enabled: preserveTranscriptOnClipboard)
completion?(.actionSuppressed)
return
}
diff --git a/Tests/ClipboardBackupReproduction.md b/Tests/ClipboardBackupReproduction.md
new file mode 100644
index 00000000..5cecd753
--- /dev/null
+++ b/Tests/ClipboardBackupReproduction.md
@@ -0,0 +1,40 @@
+# Clipboard backup regression tests
+
+Run with a full Xcode toolchain (without changing the system-wide selection):
+
+```sh
+DEVELOPER_DIR=/Applications/Xcode-beta6.app/Contents/Developer sh Tests/run_clipboard_backup_reproduction.sh
+DEVELOPER_DIR=/Applications/Xcode-beta6.app/Contents/Developer sh scripts/test_dictation_target.sh
+```
+
+The backup runner compiles production `PasteDeliveryCoordinator.swift`, including
+`SystemPasteboardManager`, and `DictationTargetPolicy.swift`. Each case uses an isolated
+named macOS pasteboard. Injected command posters send no keys; optional I/O failures
+are injected at the pasteboard boundary. Logging and unused keyboard constants are
+standalone adapters. The general clipboard, preferences, microphone, and installed app
+are not accessed by this runner.
+
+31 cases cover:
+
+- Backup off/on with successful posting, failed snapshots, failed writes before and
+ after touching the clipboard, failed command posting, and newer user copies during
+ failed writes/posts or before settlement.
+- Both experimental-toggle positions, with external focus present or missing, using
+ the production preparation boundary and an injected unsuccessful focus restoration.
+- A backup queued behind an active paste, with backup off/on and newer user copies.
+- Stale failed preparation after a newer user copy, paste delivery, or standalone copy.
+
+Checks include delivery results, final clipboard text, permanent-copy call counts,
+absence of duplicate backup writes, zero commands after failed preparation, and no
+clipboard mutation for disabled backup when insertion is skipped. Successful posting
+is a simulated command-post result, not proof that a destination app consumed text.
+
+Before the fix, the first 10 cases had three failures: with backup enabled,
+snapshot/write/command failure retained the old clipboard instead of the transcript.
+The runner now expects all cases to pass and exits nonzero on a regression. The
+existing XCTest assertion for command failure with backup enabled is also updated.
+
+The separate destination-policy suite covers 10 app/field-switch and missing-target
+cases. These tests do not perform live Accessibility restoration, record speech, or
+exercise ContentView/history persistence end to end. Failed preparation is injected
+into the same production coordinator boundary used by ContentView.
diff --git a/Tests/ClipboardBackupReproductionTests.swift b/Tests/ClipboardBackupReproductionTests.swift
new file mode 100644
index 00000000..97ce374c
--- /dev/null
+++ b/Tests/ClipboardBackupReproductionTests.swift
@@ -0,0 +1,222 @@
+import AppKit
+
+/// Runs the production coordinator and SystemPasteboardManager on a private pasteboard.
+/// Only command posting and optional I/O failures are injected; no keys are sent.
+/// Assertions cover backup failure recovery and preservation of newer user copies.
+@main
+@MainActor
+enum ClipboardBackupReproductionTests {
+ static func main() async {
+ var failures = 0
+ var cases = 0
+ for keepBackup in [false, true] {
+ for scenario in Scenario.allCases {
+ cases += 1
+ let board = NSPasteboard(name: .init("fluidvoice.backup-reproduction.\(UUID().uuidString)"))
+ defer { board.releaseGlobally() }
+ let manager = InjectedPasteboard(board: board, scenario: scenario)
+ precondition(manager.base.writeIntentionalText("old clipboard"))
+ let poster = InjectedCommandPoster(succeeds: scenario != .commandFailure && scenario != .externalCopyDuringFailedPost)
+ if scenario == .externalCopyDuringFailedPost {
+ poster.onPost = { precondition(manager.base.writeIntentionalText("new user copy")) }
+ }
+ let coordinator = PasteDeliveryCoordinator(
+ pasteboard: manager,
+ commandPoster: poster,
+ settlementDelayNanoseconds: .max
+ )
+ let result = await coordinator.deliver("dictated text", preserveTranscriptOnClipboard: keepBackup)
+ if scenario == .newerUserCopy {
+ precondition(manager.base.writeIntentionalText("new user copy"))
+ }
+ coordinator.runPendingSettlementForTesting()
+
+ let expectedResult: TextDeliveryResult = switch scenario {
+ case .snapshotFailure: .recoverableFailure(.clipboardSnapshotFailed)
+ case .writeFailure, .earlyWriteFailure, .externalCopyDuringFailedWrite: .recoverableFailure(.clipboardWriteFailed)
+ case .commandFailure, .externalCopyDuringFailedPost: .recoverableFailure(.pasteCommandFailed)
+ case .success, .newerUserCopy: .commandPosted
+ }
+ let hasNewerCopy = scenario == .newerUserCopy || scenario == .externalCopyDuringFailedPost || scenario == .externalCopyDuringFailedWrite
+ let expectedText = hasNewerCopy
+ ? "new user copy" : (keepBackup ? "dictated text" : "old clipboard")
+ let expectedPosts = [.snapshotFailure, .writeFailure, .earlyWriteFailure, .externalCopyDuringFailedWrite].contains(scenario) ? 0 : 1
+ let actualText = board.string(forType: .string)
+ let isTemporary = board.types?.contains(.init("org.nspasteboard.TransientType")) == true
+ // Restored old content is deliberately marked transient to avoid duplicate
+ // clipboard-manager entries. An enabled transcript backup must be permanent.
+ let permanentBackup = !keepBackup || !isTemporary
+ let passed = result == expectedResult && actualText == expectedText
+ && poster.postCount == expectedPosts && permanentBackup
+ && manager.intentionalWrites == (keepBackup && !hasNewerCopy ? 1 : 0)
+ if !passed { failures += 1 }
+ print("\(passed ? "PASS" : "FAIL"): backup=\(keepBackup) scenario=\(scenario.rawValue) result=\(result) clipboard=\(actualText ?? "nil") posts=\(poster.postCount)")
+ }
+ }
+ let preparation = await self.testPreparation()
+ cases += preparation.cases
+ failures += preparation.failures
+ let ordering = await self.testOrdering()
+ cases += ordering.cases
+ failures += ordering.failures
+ print("\(cases - failures)/\(cases) passed; \(failures) backup contract failures. No system clipboard or real paste commands used.")
+ exit(failures == 0 ? 0 : 1)
+ }
+
+ static func testPreparation() async -> (cases: Int, failures: Int) {
+ var failures = 0
+ var cases = 0
+ for backup in [false, true] {
+ for returnToStart in [false, true] {
+ for focusedPID: Int32? in [200, nil] {
+ cases += 1
+ let board = NSPasteboard(name: .init("fluidvoice.preparation.\(UUID().uuidString)"))
+ defer { board.releaseGlobally() }
+ let manager = InjectedPasteboard(board: board, scenario: .success)
+ precondition(manager.base.writeIntentionalText("old clipboard"))
+ let originalChangeCount = manager.changeCount
+ let poster = InjectedCommandPoster(succeeds: true)
+ let coordinator = PasteDeliveryCoordinator(pasteboard: manager, commandPoster: poster)
+ let target = DictationTargetPolicy.resolve(
+ returnToStartingField: returnToStart, focusedPID: focusedPID,
+ ownPID: 999, originalPID: 100, originalFieldIsFocused: false
+ )
+ let ready = await coordinator.prepareForDelivery("dictated text", preserveTranscriptOnClipboard: backup) {
+ // Deterministically fail whenever restoration is requested.
+ !target.shouldRestoreOriginalFocus
+ }
+ let expectedCopy = backup && target.shouldRestoreOriginalFocus
+ let passed = ready == !target.shouldRestoreOriginalFocus
+ && board.string(forType: .string) == (expectedCopy ? "dictated text" : "old clipboard")
+ && manager.intentionalWrites == (expectedCopy ? 1 : 0)
+ && poster.postCount == 0
+ && (expectedCopy || manager.changeCount == originalChangeCount)
+ if !passed { failures += 1 }
+ print("\(passed ? "PASS" : "FAIL"): preparation backup=\(backup) returnToStart=\(returnToStart) externalFocus=\(focusedPID != nil)")
+ }
+ }
+ }
+ return (cases, failures)
+ }
+
+ static func testOrdering() async -> (cases: Int, failures: Int) {
+ var failures = 0
+ var cases = 0
+ for backup in [false, true] {
+ for externalCopy in [false, true] {
+ cases += 1
+ let board = NSPasteboard(name: .init("fluidvoice.queued-backup.\(UUID().uuidString)"))
+ defer { board.releaseGlobally() }
+ let manager = InjectedPasteboard(board: board, scenario: .success)
+ precondition(manager.base.writeIntentionalText("old clipboard"))
+ let poster = InjectedCommandPoster(succeeds: true)
+ let coordinator = PasteDeliveryCoordinator(pasteboard: manager, commandPoster: poster, settlementDelayNanoseconds: .max)
+ _ = await coordinator.deliver("first", preserveTranscriptOnClipboard: false)
+ var started = false
+ let pending = Task { @MainActor in
+ started = true
+ return await coordinator.copyBackup("second", enabled: backup)
+ }
+ for _ in 0..<100 where !started {
+ await Task.yield()
+ }
+ let protectedFirst = board.string(forType: .string) == "first"
+ if externalCopy { precondition(manager.base.writeIntentionalText("new user copy")) }
+ coordinator.runPendingSettlementForTesting()
+ let copied = await pending.value
+ let expected = externalCopy ? "new user copy" : (backup ? "second" : "old clipboard")
+ let passed = protectedFirst && board.string(forType: .string) == expected
+ && copied == (backup && !externalCopy) && poster.postCount == 1
+ && manager.intentionalWrites == (backup && !externalCopy ? 1 : 0)
+ if !passed { failures += 1 }
+ print("\(passed ? "PASS" : "FAIL"): queued backup=\(backup) newerUserCopy=\(externalCopy)")
+ }
+ }
+ // A newer dictation or user copy while focus restoration waits must win.
+ for newerOutput in ["user copy", "paste", "copy only"] {
+ cases += 1
+ let board = NSPasteboard(name: .init("fluidvoice.stale-backup.\(UUID().uuidString)"))
+ defer { board.releaseGlobally() }
+ let manager = InjectedPasteboard(board: board, scenario: .success)
+ precondition(manager.base.writeIntentionalText("old clipboard"))
+ let coordinator = PasteDeliveryCoordinator(pasteboard: manager, commandPoster: InjectedCommandPoster(succeeds: true), settlementDelayNanoseconds: .max)
+ let ready = await coordinator.prepareForDelivery("stale text", preserveTranscriptOnClipboard: true) {
+ if newerOutput == "paste" {
+ _ = await coordinator.deliver("newer text", preserveTranscriptOnClipboard: true)
+ coordinator.runPendingSettlementForTesting()
+ } else if newerOutput == "copy only" {
+ _ = await coordinator.copyBackup("newer text", enabled: true)
+ } else {
+ precondition(manager.base.writeIntentionalText("newer text"))
+ }
+ return false
+ }
+ let passed = !ready && board.string(forType: .string) == "newer text"
+ if !passed { failures += 1 }
+ print("\(passed ? "PASS" : "FAIL"): stale preparation newerOutput=\(newerOutput)")
+ }
+ return (cases, failures)
+ }
+}
+
+private enum Scenario: String, CaseIterable {
+ case success, snapshotFailure, writeFailure, earlyWriteFailure, commandFailure, newerUserCopy
+ case externalCopyDuringFailedWrite, externalCopyDuringFailedPost
+}
+
+@MainActor
+private final class InjectedCommandPoster: PasteCommandPosting {
+ let succeeds: Bool
+ private(set) var postCount = 0
+ var onPost: (() -> Void)?
+
+ init(succeeds: Bool) { self.succeeds = succeeds }
+
+ func postGlobalPasteCommand() async -> Bool {
+ self.postCount += 1
+ self.onPost?()
+ return self.succeeds
+ }
+}
+
+@MainActor
+private final class InjectedPasteboard: PasteboardManaging {
+ let base: SystemPasteboardManager
+ let scenario: Scenario
+ var changeCount: Int { self.base.changeCount }
+ private(set) var intentionalWrites = 0
+
+ init(board: NSPasteboard, scenario: Scenario) {
+ self.base = SystemPasteboardManager(pasteboard: board)
+ self.scenario = scenario
+ }
+
+ func captureSnapshot() -> PasteboardSnapshot? {
+ self.scenario == .snapshotFailure ? nil : self.base.captureSnapshot()
+ }
+
+ func writeTemporaryText(_ text: String, sessionID: String) -> Bool {
+ if self.scenario == .earlyWriteFailure { return false }
+ let written = self.base.writeTemporaryText(text, sessionID: sessionID)
+ if self.scenario == .externalCopyDuringFailedWrite {
+ precondition(self.base.writeIntentionalText("new user copy"))
+ return false
+ }
+ // Exercise cleanup after a write that touched the clipboard but reports failure.
+ return self.scenario == .writeFailure ? false : written
+ }
+
+ func writeIntentionalText(_ text: String) -> Bool {
+ self.intentionalWrites += 1
+ return 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)
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift b/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift
index 438290aa..7bb994e9 100644
--- a/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift
+++ b/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift
@@ -172,7 +172,7 @@ final class PasteDeliveryCoordinatorTests: XCTestCase {
XCTAssertFalse(pasteboard.isTemporary)
}
- func testPasteCommandFailureRestoresOriginalClipboardWhenCopyPreferenceIsEnabled() async {
+ func testPasteCommandFailureKeepsTranscriptWhenCopyPreferenceIsEnabled() async {
let pasteboard = FakePasteboardManager(text: "before")
let coordinator = PasteDeliveryCoordinator(
pasteboard: pasteboard,
@@ -183,9 +183,9 @@ final class PasteDeliveryCoordinatorTests: XCTestCase {
let result = await coordinator.deliver("dictated text", preserveTranscriptOnClipboard: true)
XCTAssertEqual(result, .recoverableFailure(.pasteCommandFailed))
- XCTAssertEqual(pasteboard.text, "before")
- XCTAssertEqual(pasteboard.restoreCount, 1)
- XCTAssertEqual(pasteboard.intentionalWriteCount, 0)
+ XCTAssertEqual(pasteboard.text, "dictated text")
+ XCTAssertEqual(pasteboard.restoreCount, 0)
+ XCTAssertEqual(pasteboard.intentionalWriteCount, 1)
}
func testIncompleteSnapshotDoesNotTouchClipboardOrPostPasteCommand() async {
@@ -451,6 +451,7 @@ final class TextInsertionModeMigrationTests: XCTestCase {
@MainActor
private final class FakePasteboardManager: PasteboardManaging {
+ private(set) var changeCount = 0
private(set) var text: String
private(set) var restoreCount = 0
private(set) var intentionalWriteCount = 0
@@ -481,6 +482,7 @@ private final class FakePasteboardManager: PasteboardManaging {
}
func writeTemporaryText(_ text: String, sessionID: String) -> Bool {
+ self.changeCount += 1
self.temporaryWriteCount += 1
self.text = text
self.sessionID = sessionID
@@ -490,6 +492,7 @@ private final class FakePasteboardManager: PasteboardManaging {
}
func writeIntentionalText(_ text: String) -> Bool {
+ self.changeCount += 1
self.intentionalWriteCount += 1
self.text = text
self.sessionID = nil
@@ -502,6 +505,7 @@ private final class FakePasteboardManager: PasteboardManaging {
}
func restore(_ snapshot: PasteboardSnapshot) -> Bool {
+ self.changeCount += 1
self.restoreCount += 1
self.sessionID = nil
self.isTemporary = false
@@ -525,6 +529,7 @@ private final class FakePasteboardManager: PasteboardManaging {
}
func simulateExternalCopy(_ text: String) {
+ self.changeCount += 1
self.text = text
self.sessionID = nil
self.isTemporary = false
diff --git a/Tests/Support/ClipboardBackupStandaloneSupport.swift b/Tests/Support/ClipboardBackupStandaloneSupport.swift
new file mode 100644
index 00000000..661604df
--- /dev/null
+++ b/Tests/Support/ClipboardBackupStandaloneSupport.swift
@@ -0,0 +1,18 @@
+import AppKit
+
+// Compile-only adapters for app-wide logging and the unused real command poster.
+// The production delivery coordinator and pasteboard implementation are compiled unchanged.
+// Fatal keyboard getters prevent this isolated harness from ever posting real keys.
+enum TypingService {
+ 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") }
+}
+
+enum ClipboardAudit {
+ static func record(_ event: String, pasteboard: NSPasteboard, detail: String = "") {}
+}
+
+final class DebugLogger {
+ static let shared = DebugLogger()
+ func benchmark(_ category: String, message: String, source: String) {}
+}
diff --git a/Tests/run_clipboard_backup_reproduction.sh b/Tests/run_clipboard_backup_reproduction.sh
new file mode 100644
index 00000000..d757e0cd
--- /dev/null
+++ b/Tests/run_clipboard_backup_reproduction.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-backup-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/ClipboardBackupReproductionTests.swift \
+ -o "$task_test_dir/tests"
+"$task_test_dir/tests"