# Event-Driven Clipboard Monitoring on macOS

> How Deck replaced constant pasteboard polling with a reverse-engineered pboard XPC invalidation bridge—cutting baseline timer wakeups by 60x while keeping public NSPasteboard reads, OOM caps, and 7-IDE anchor tracking.

Engineering · 2026-12-05 · 7 min read

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`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Clipboard/ClipboardService%2BPolling.swift#L178-L245). 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 `⌘C` or `⌘X`.
- **Wasted wakeups:** Whenever the user is active at the keyboard without copying, an active poller still wakes the `.utility` queue 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`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Clipboard/DeckPrivatePasteboardEventBridge.m#L299-L391), that speaks directly to `com.apple.pasteboard.1` via `xpc_connection_create_mach_service`:

1. **Session creation:** Deck sends `com.apple.pboard.create` for `Apple CFPasteboard general` and receives its `com.apple.pboard.uuid`, current `generation`, and `change` counters.
2. **Invalidation subscription:** Deck sends `com.apple.pboard.get-counts` to enter `pboard`'s invalidation client set, followed by `com.apple.pboard.refresh-cache` with `com.apple.pboard.includeAvailableData = false`.
3. **Push delivery:** Whenever any process invalidates the general pasteboard, `pboard` pushes an asynchronous XPC dictionary containing `com.apple.pboard.invalidate-entries`, `com.apple.pboard.invalidate-cache`, or `com.apple.pboard.flush-entries`.
4. **Immediate re-subscription:** Upon receiving a push, Deck dispatches the change trigger to `ClipboardService` and re-enters `pboard`'s invalidation client set via [`resubscribePboardInvalidationOnQueueWithReason:`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Clipboard/DeckPrivatePasteboardEventBridge.m#L608-L717).

```objc
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]`](https://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`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Clipboard/ClipboardService%2BPrivatePasteboardEvents.swift#L75-L232) 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 reading `NSPasteboard`, 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, `pboard` can return protocol error `-22` (`EINVAL`) on `refresh-cache` when the cached `change` token 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`, and `screensDidWakeNotification` suspend 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`/`⌘X` fallback probes:** When polling is active, Deck keeps only a lightweight `.flagsChanged` listener alive and arms `.keyDown` only while Command is held, firing a short `< 350ms` probe 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`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Clipboard/ClipboardService%2BCapture.swift#L25-L194):

- **Unpopulated `clearContents()` race:** Some apps call `clearContents()`—incrementing `changeCount` and triggering `pboard`—milliseconds before writing their payload. Deck runs a bounded retry schedule (`20ms`, `50ms`, `100ms`, `250ms`, `500ms`) until `pasteboard.types` populates.
- **Universal Clipboard quarantine:** Content copied on an iPhone or iPad arrives with `com.apple.is-remote-clipboard` before the remote payload hydrates locally. Reading `data(forType:)` prematurely can block the main thread waiting on Continuity. Deck quarantines unhydrated remote generations for up to `30.0s` (`universalClipboardReadQuarantineDuration`) and honors a `2.5s` text 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 on `MainActor`, then immediately hands rich-text parsing, lossless raster-to-PNG conversion (`#176` for uncompressed TIFF/BMP screenshots), representation encoding, and thumbnail generation to a detached `.userInitiated` task.

## Type Resolution and OOM Guards

A single copy operation can place twenty or more UTIs on the pasteboard simultaneously. Deck walks [`PasteboardType.supportedTypes`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Core/Pasteboard/PasteboardTypes.swift#L10-L17) in strict priority order:

1. **Images:** `.png`, `.tiff`, `.jpeg`, `.heic`, `.heif`, `.gif`, `.webp`, `.bmp`
2. **Rich text:** `.rtfd`, `.flatRTFD`, `.rtf` (if plain `.string` is also present alongside RTFD, Deck stores plain text to avoid heavy RTFD decoding)
3. **Files:** `.fileURL`
4. **URLs:** `public.url`
5. **Plain text:** `.string`

When none of those primary types match, [`ClipboardItem.resolveTextFallbackPayload`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Models/ClipboardItem%2BPayloadResolution.swift#L248-L271) 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`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Clipboard/ClipboardService%2BPasteboardSnapshot.swift#L33-L34) |
| Total unsupported snapshot budget | 4 MB | `ClipboardService+PasteboardSnapshot.swift` |
| SQLite blob offload threshold | 512 KB | [`Constants.swift`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Utilities/Constants.swift#L193) |
| Inline image paste cap (when file URL exists) | 25 MB | [`ClipboardService.swift`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Clipboard/ClipboardService.swift#L13) |
| Direct image load ceiling | 100 MB | [`ClipboardItem+Thumbnails.swift`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Models/ClipboardItem%2BThumbnails.swift#L12) |

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**, [`IDEAnchorService`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Context/IDEAnchorService.swift#L59-L81) records a `SourceAnchor` with file path, line, and column. Zed provides `zed-metadata` directly 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: 2000` for Electron editors, `4 / 200` for Xcode and JetBrains). Clicking the anchor jumps straight back to that line.
- **Figma design payloads:** Copying a frame in Figma puts HTML on `NSPasteboard` containing base64-encoded vector/component data wrapped in `(figma)` and `(figmeta)` markers. When [`containsFigmaMarker`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Models/ClipboardItem%2BPayloadResolution.swift#L378-L381) matches, Deck aborts text fallback so the design payload is never flattened into plain text, preserving `fileKey`, `pasteID`, `dataType`, and `org.chromium.source-url` for 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:

1. **Zero payload coupling:** Private XPC carries only invalidation triggers, never clipboard data.
2. **Self-demoting state machine:** If `.probing` sees three clipboard changes without an XPC push—or the `.eventDriven` watchdog 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](https://github.com/yuzeguitarist/Deck/tree/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Clipboard) or [download Deck for macOS](https://deckclip.app/download).

---

- HTML: https://deckclip.app/newsroom/clipboard-monitoring
- 中文: https://deckclip.app/zh-cn/newsroom/clipboard-monitoring.md

© 2026 Yuze Pan
