Skip to content
C.W.K.
Stream
Lesson 05 of 06 · published

Borrow the Clipboard, Return It Clean

~10 min · pasteboard, clipboard, etiquette, privacy

Level 0Unlit
0 XP0/48 lessons0/13 achievements
0/100 XP to next level100 XP to go0% complete
"The clipboard is the user's, not yours. If you borrow it to paste, put it back the way you found it."

The Paste Rung Has a Debt

The pasteboard + Cmd+V rung is the workhorse of insertion, but it uses a shared resource: the user's clipboard. If Firekeeper writes your dictation to the clipboard to paste it, it just clobbered whatever you had copied — a URL, a paragraph, an image. That's rude and surprising. So the paste rung owes an etiquette: save the current clipboard first, write the transcript, paste, then restore the original clipboard once the paste has settled.

Save, Paste, Restore

1. save    = read + stash the current pasteboard contents
2. write   = put the transcript on the pasteboard (marked transient)
3. paste   = synthesize Cmd+V
4. settle  = wait briefly for the paste to land
5. restore = put the original contents back
            (skip restore if something else wrote in the meantime)

Two subtleties make this safe. Mark Firekeeper's clipboard write as transient where possible, so clipboard-history tools don't record your dictation as if you'd copied it. And before restoring, check that nothing else wrote to the clipboard in the window — if it did, don't clobber the newer content. Etiquette that overwrites a fresh copy is worse than no etiquette.

The Secure-Field Line

There's one place where the entire dance is off: secure fields. If the target is a password field, Firekeeper never reads or restores the pasteboard around it, and the insertion refuses outright. Reading the clipboard near a secure context, or leaving a transcript sitting on it, is exactly the kind of behavior a voice tool must never do. The secure-field check from target capture flows all the way down here: it doesn't just block insertion, it blocks the clipboard handling too.

Leave shared state exactly as you found it. When a feature has to borrow a resource the user also uses — the clipboard, the frontmost window, the audio device — it owes a save-and-restore. The measure of a well-behaved tool is that after it acts, the parts of the system it merely borrowed are indistinguishable from untouched.

Code

Save, paste, restore — and never near a secure field·swift
func pasteInsert(_ text: String, restoreClipboard: Bool) async -> InsertResult {
    // The secure-field refusal ran earlier: nothing reaches the clipboard there.
    let pb = NSPasteboard.general
    // 1. save: every item and every representation, or nothing
    let saved = restoreClipboard ? PasteboardSnapshot.capture(from: pb) : nil
    let acceptsPaste = focusedTargetAcceptsPaste()     // asked now, not at start
    let frontBefore = NSWorkspace.shared.frontmostApplication?.processIdentifier

    pb.clearContents()                                  // 2. write, marked transient
    pb.setString("", forType: .init("org.nspasteboard.TransientType"))
    pb.setString(text, forType: .string)
    let ourChange = pb.changeCount

    synthesizeCmdV()                                    // 3. paste
    try? await Task.sleep(for: .milliseconds(350))     // 4. settle (Electron reads lazily)

    // 5. restore ONLY on the all-clear (FirekeeperKit PasteTargetRole)
    let landed = PasteTargetRole.mayRestoreClipboard(
        frontAppUnchanged: NSWorkspace.shared.frontmostApplication?.processIdentifier == frontBefore,
        pasteboardUntouchedSinceOurWrite: pb.changeCount == ourChange,
        targetAcceptsPaste: acceptsPaste)
    if let saved, landed { saved.restore(to: pb) }

    // No API confirms a paste: report what is known, not what was hoped.
    if saved != nil, !landed { return .copiedToClipboard("could not confirm the paste") }
    // No snapshot (restore off, or an incomplete capture): nothing was put back,
    // the transcript stays on the clipboard, and this still reports .pasted.
    return .pasted
}

External links

Exercise

Find a feature in some app that borrows a shared system resource (clipboard, camera, the frontmost window, keyboard focus). Does it return that resource to its prior state, or leave a trace? Describe the save-paste-restore-style dance it would need, including the check that prevents it from clobbering something newer.
Hint
The complete dance is always: stash the prior state, use the resource, then restore — but with a guard that detects whether the world changed while you held it. Without that guard, 'restore' becomes 'overwrite whatever happened in the meantime,' turning a courtesy into a data-loss bug. The change-count check is what makes borrowing safe.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign in — Please sign in to comment.

No comments yet — be the first.