For years, macOS clipboard managers have shared the same structural compromise. AppKit's NSPasteboard exposes a monotonic integer, changeCount, but provides no public delegate, callback, or notification when another app writes to the clipboard. A developer building a prototype writes a timer that polls NSPasteboard.general.changeCount every half second.
At 0.5 seconds, a clipboard monitor wakes the CPU up to 7,200 times an hour just to ask macOS a single question: did anything change yet? Most of the time, the answer is no.
Deck began with adaptive polling and shortcut interception, then asked a different question: if Apple's own Spotlight knows the exact instant the clipboard changes without burning battery on a polling loop, why keep asking macOS at all? Why not let the system daemon tell Deck when the pasteboard changes?
Why Polling Hits a Wall
Adaptive polling can soften the cost of changeCount checks, and Deck still maintains a full adaptive poller as a fallback layer in ClipboardService+Polling.swift. It scales the interval dynamically between 0.5s and 15.0s using Low Power Mode (isLowPowerModeEnabled), thermal pressure (.serious / .critical), and user idle time, while applying a 25% timer leeway (50–500 ms) so macOS can coalesce wakeups.
Even with those safeguards, polling has two intrinsic limits:
- Latency vs. battery trade-off: Stretching the idle ceiling to 15 seconds saves power, yet programmatic copies—such as CLI output, script writes, or right-click Copy actions—wait longer to appear unless the user presses
⌘Cor⌘X. - Wasted wakeups: Whenever the user is active at the keyboard without copying, an active poller still wakes the
.utilityqueue thousands of times a day to read the exact same integer.
What we wanted was an event-driven trigger with zero steady-state polling overhead, without sacrificing compatibility if macOS ever changes an internal daemon interface.
Letting pboard Notify Deck
In macOS, NSPasteboard is backed by the pboard daemon (com.apple.pasteboard.1). Apple's Spotlight client subscribes to invalidation notifications from pboard over Mach XPC rather than polling changeCount.
Deck implements a narrow Objective-C runtime bridge, DeckPrivatePasteboardEventBridge, that speaks directly to com.apple.pasteboard.1 via xpc_connection_create_mach_service:
- Session creation: Deck sends
com.apple.pboard.createforApple CFPasteboard generaland receives itscom.apple.pboard.uuid, currentgeneration, andchangecounters. - Invalidation subscription: Deck sends
com.apple.pboard.get-countsto enterpboard's invalidation client set, followed bycom.apple.pboard.refresh-cachewithcom.apple.pboard.includeAvailableData = false. - Push delivery: Whenever any process invalidates the general pasteboard,
pboardpushes an asynchronous XPC dictionary containingcom.apple.pboard.invalidate-entries,com.apple.pboard.invalidate-cache, orcom.apple.pboard.flush-entries. - Immediate re-subscription: Upon receiving a push, Deck dispatches the change trigger to
ClipboardServiceand re-enterspboard's invalidation client set viaresubscribePboardInvalidationOnQueueWithReason:.
static BOOL DeckPBPboardMessageIsInvalidation(NSString *message) {
return [message isEqualToString:@"com.apple.pboard.invalidate-entries"] ||
[message isEqualToString:@"com.apple.pboard.invalidate-cache"] ||
[message isEqualToString:@"com.apple.pboard.flush-entries"];
}A deliberate architectural boundary keeps this safe across macOS releases: the XPC bridge is strictly a "pasteboard changed" doorbell. Deck never reads clipboard payloads over private XPC messages. All content inspection, type resolution, and snapshot creation remain on standard public NSPasteboard.general APIs. If the bridge fails to start or stops delivering events, Deck falls back to adaptive polling with zero loss of functionality.
The bridge also exposes one additional system signal: [+[DeckPrivatePasteboardEventBridge generalPasteboardShouldExcludeFromHistory]](github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Clipboard/DeckPrivatePasteboardEventBridge.m#L285-L295), which invokes Spotlight's -[NSPasteboard _shouldExcludeFromHistory] selector when present so system-excluded generations are never recorded.
Lifecycle, Resiliency, and Adaptive Fallback
A daemon XPC connection cannot be trusted blindly across sleep/wake cycles, screen locks, or OS updates. ClipboardService+PrivatePasteboardEvents.swift wraps the bridge in a three-state machine:
| Mode | Trigger behavior | Background timer | When active |
|---|---|---|---|
.disabled | Adaptive polling + ⌘C/⌘X probes | 0.5s – 15.0s | Bridge unavailable, disabled via UserDefaults, or restart budget exhausted |
.probing | Bridge active, polling kept as proof | 0.5s – 2.0s | Immediately after startup until the first real GUI-session event confirms delivery |
.eventDriven | pboard XPC push + finite debounce | 5.0s warmup (120s), then 30.0s watchdog | Normal steady state after validation |
Wakeup Reduction in Numbers
Moving from active 0.5s polling to the .eventDriven watchdog changes the baseline timer profile dramatically:
| Monitoring strategy | Baseline timer interval | Timer wakeups / hour |
|---|---|---|
| Naive fixed timer | 0.5s | 7,200 |
| Adaptive polling (idle ceiling) | 0.5s – 15.0s | 240 – 7,200 |
pboard XPC push + 30s watchdog | 30.0s (idle health check) | 120 |
At 30.0s (privatePasteboardHealthInterval), baseline timer wakeups drop by 60x compared to a 0.5s poller—from 7,200/hr down to 120/hr—and even beat a 15s idle poller by 2x while responding within milliseconds when a copy actually occurs.
Settling, Sleep/Wake, and Watchdog Recovery
Real-world pasteboard traffic introduces subtle races that the event pipeline handles explicitly:
- Finite settle debounce (
12ms,35ms,75ms): Mirroring Spotlight's ~10 ms settle window, Deck waits 12 ms before readingNSPasteboard, with two bounded retries (35ms,75ms) to absorb sleep/wake lag or promised-metadata churn without returning to polling. - Stale token & generation ordering: After wake,
pboardcan return protocol error-22(EINVAL) onrefresh-cachewhen the cachedchangetoken is stale, or return metadata for an older generation. The bridge retries without the stale token and ignores out-of-order generation rollbacks. - Sleep and screen-lock transitions: Observers on
NSWorkspace.willSleepNotification,didWakeNotification,screensDidSleepNotification, andscreensDidWakeNotificationsuspend the XPC connection cleanly before sleep and re-bootstrap on wake, backed by exponential-backoff restarts (10s,20s,40s,80s, up to 4 attempts). - Low-wakeup
⌘C/⌘Xfallback probes: When polling is active, Deck keeps only a lightweight.flagsChangedlistener alive and arms.keyDownonly while Command is held, firing a short< 350msprobe sequence (25ms,55ms,90ms,170ms) without maintaining a permanent global keystroke monitor.
Reading NSPasteboard Safely
Detecting a change is only half the problem. Reading NSPasteboard on MainActor can still block or miss data if three edge cases are ignored in ClipboardService+Capture.swift:
- Unpopulated
clearContents()race: Some apps callclearContents()—incrementingchangeCountand triggeringpboard—milliseconds before writing their payload. Deck runs a bounded retry schedule (20ms,50ms,100ms,250ms,500ms) untilpasteboard.typespopulates. - Universal Clipboard quarantine: Content copied on an iPhone or iPad arrives with
com.apple.is-remote-clipboardbefore the remote payload hydrates locally. Readingdata(forType:)prematurely can block the main thread waiting on Continuity. Deck quarantines unhydrated remote generations for up to30.0s(universalClipboardReadQuarantineDuration) and honors a2.5stext grace window so Handoff copies are captured reliably once ready without stalling the UI. - Main-thread vs. background split:
makePasteboardSnapshot(sourceApp:)captures a bounded snapshot onMainActor, then immediately hands rich-text parsing, lossless raster-to-PNG conversion (#176for uncompressed TIFF/BMP screenshots), representation encoding, and thumbnail generation to a detached.userInitiatedtask.
Type Resolution and OOM Guards
A single copy operation can place twenty or more UTIs on the pasteboard simultaneously. Deck walks PasteboardType.supportedTypes in strict priority order:
- Images:
.png,.tiff,.jpeg,.heic,.heif,.gif,.webp,.bmp - Rich text:
.rtfd,.flatRTFD,.rtf(if plain.stringis also present alongside RTFD, Deck stores plain text to avoid heavy RTFD decoding) - Files:
.fileURL - URLs:
public.url - Plain text:
.string
When none of those primary types match, ClipboardItem.resolveTextFallbackPayload walks a three-stage fallback chain—HTML extraction (checking for Figma markers first), UTF-16 external/plain text, and any remaining type conforming to UTType.text—while skipping an exclusion set of noisy WebKit, Chromium, and Microsoft OLE metadata types.
To ensure a 200 MB image or private editor blob never crashes the background helper, Deck enforces layered memory limits:
| Guard | Limit | Where enforced |
|---|---|---|
| Per-type unsupported cap | 1 MB | ClipboardService+PasteboardSnapshot.swift |
| Total unsupported snapshot budget | 4 MB | ClipboardService+PasteboardSnapshot.swift |
| SQLite blob offload threshold | 512 KB | Constants.swift |
| Inline image paste cap (when file URL exists) | 25 MB | ClipboardService.swift |
| Direct image load ceiling | 100 MB | ClipboardItem+Thumbnails.swift |
Images above 512 KB are written to standalone blob files instead of fragmenting SQLite pages, and thumbnails are decoded progressively with CGImageSourceCreateThumbnailAtIndex rather than loading full bitmaps into RAM.
IDE Anchors and Figma Payloads
Two kinds of copies carry hidden structure that generic clipboard managers discard:
- IDE source anchors: When copying text from VS Code, Cursor, Windsurf, Xcode, JetBrains IDEs, Sublime Text, or Zed,
IDEAnchorServicerecords aSourceAnchorwith file path, line, and column. Zed provideszed-metadatadirectly on the pasteboard; Sublime uses its session state plus window title; VS Code-family, Xcode, and JetBrains editors are queried via Accessibility (AXUIElement) under strict BFS budgets (maxDepth: 8 / maxNodes: 2000for Electron editors,4 / 200for Xcode and JetBrains). Clicking the anchor jumps straight back to that line. - Figma design payloads: Copying a frame in Figma puts HTML on
NSPasteboardcontaining base64-encoded vector/component data wrapped in(figma)and(figmeta)markers. WhencontainsFigmaMarkermatches, Deck aborts text fallback so the design payload is never flattened into plain text, preservingfileKey,pasteID,dataType, andorg.chromium.source-urlfor intact restoration and container inspection.
Design Trade-offs
Using com.apple.pasteboard.1 directly comes with an obvious engineering constraint: private XPC protocols are undocumented and can change in any major macOS release. That is why the entire bridge was designed around two invariants:
- Zero payload coupling: Private XPC carries only invalidation triggers, never clipboard data.
- Self-demoting state machine: If
.probingsees three clipboard changes without an XPC push—or the.eventDrivenwatchdog catches three missed events—Deck cleanly demotes itself back to adaptive polling.
The result is a monitor that stays asleep when you are not copying, wakes immediately when pboard invalidates, and remains resilient even if Apple rewrites the pasteboard daemon tomorrow. Deck is source-available—you can inspect the full bridge and capture pipeline on GitHub or download Deck for macOS.