Repository navigation
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4f46be944e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let pasteboard = NSPasteboard.general | ||
| let snapshot = PasteboardSnapshot.capture(from: pasteboard) | ||
| let changeCountBeforeCopy = pasteboard.changeCount |
There was a problem hiding this comment.
Serialize selection-copy fallback with pasteboard writes
This fallback snapshots and restores NSPasteboard.general without coordinating with TypingService.withTemporaryPasteboardString, whose reliable-paste path keeps a temporary string on the same pasteboard until its async restore completes under pasteboardSessionSemaphore. If the user starts another rewrite during that restore window, TypingService's restore can change changeCount while this code is waiting for Cmd+C, causing the previous clipboard/temporary insertion text to be treated as the selected context and then restoring the wrong snapshot. Please run this copy fallback under the same pasteboard session/lock or otherwise wait for Fluid's pending pasteboard restore to finish before sampling changeCount.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 47516f8a8f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| // timeout we proceed unguarded (no worse than the uncoordinated behavior this guard | ||
| // replaces), the main run loop drains, the paste's `main.sync` completes, and the | ||
| // session frees. We always release before returning (the deferred `endExclusive`). | ||
| let acquiredSession = PasteboardSession.tryBeginExclusive(timeoutMicros: Self.pasteboardSessionWaitMicros) |
There was a problem hiding this comment.
Avoid freezing Edit hotkey behind paste restores
In the Edit/Write hotkey path this selection capture runs on the MainActor via RewriteModeService.captureSelectedText(), so if a previous reliable-paste/clipboard insertion is still holding PasteboardSession for its up-to-5s verification window (common when the target app cannot expose readable AX text and verification times out), this semaphore wait blocks the main thread for the full 5.5s before recording can start and the app appears unresponsive. Please avoid synchronously waiting the whole restore window on the main thread; use a non-blocking/short wait fallback or move the capture off-main.
Useful? React with 👍 / 👎.
| // Always restore the user's previous pasteboard, then defend that restore against a | ||
| // late synthetic-copy write (a slow/busy target app processing our Cmd+C after the | ||
| // read timeout would otherwise clobber the restored clipboard — see the method doc). | ||
| self.restoreClipboardDefensively(snapshot, to: pasteboard) |
There was a problem hiding this comment.
Do not rewrite the clipboard when copy timed out
When the target app ignores Cmd+C because there is no selection, didChange is false, but this still clears and rewrites the user's previous clipboard and then watches for late writes. Since PasteboardSnapshot only restores types for which data(forType:) was captured, entering Write Mode with no selection can unnecessarily damage complex clipboard contents even though Fluid never observed a copy; restore only after an actual pasteboard change, or wait for a late change before restoring.
Useful? React with 👍 / 👎.
536c073 to
110b975
Compare
|
Rebased onto 1.6.0 (current main). Clean replay, no conflicts, the fix is unchanged. xcodebuild builds green and swiftlint --strict is clean. Ready to pull. |
110b975 to
c7fbc7f
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c7fbc7fdb5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| layoutPtr, | ||
| keyCode, | ||
| UInt16(kUCKeyActionDisplay), | ||
| 0, |
There was a problem hiding this comment.
Resolve shortcut keys with Command held
For input sources with a separate Command layer, such as macOS's Dvorak-QWERTY ⌘ layout, the key that produces c/v with no modifiers is not the key that produces the Copy/Paste menu equivalent while Command is down. Because this scan passes modifier state 0 but the callers later post the returned key with .maskCommand, the clipboard fallback can send a different shortcut instead of Cmd+C/Cmd+V on those layouts. Please translate using the Command modifier state that will be posted, or otherwise preserve the ANSI key for command-preserving layouts.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c7fbc7fdb5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ) | ||
|
|
||
| // Read the copied selection only if the pasteboard actually changed. | ||
| let copiedText = didChange ? pasteboard.string(forType: .string) : nil |
There was a problem hiding this comment.
Avoid treating copy-current-line as selected text
When the AX paths fail in editors that copy the current line on an empty selection (for example VS Code with its default empty-selection clipboard behavior), this fallback sees the Cmd+C pasteboard change and returns that line as if it were selected text. That makes pressing the Write/Edit hotkey with only a caret enter rewrite mode using the current line as context instead of the intended no-selection Write Mode path.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c7fbc7fdb5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let cKey = LayoutAwareKeyCode.virtualKeyCode(for: "c", qwertyFallback: sentinel) | ||
| let vKey = LayoutAwareKeyCode.virtualKeyCode(for: "v", qwertyFallback: sentinel) |
There was a problem hiding this comment.
Avoid depending on the user's keyboard layout
This test is tied to whatever input source is active on the machine running the suite. When a developer or CI host has a non-Latin input method selected, no GUI keyboard layout data available, or any input source where TISGetInputSourceProperty(...UnicodeKeyLayoutData) is nil, LayoutAwareKeyCode correctly returns the supplied fallback by design, but the sentinel here makes that path fail the test even though production behavior is valid. Consider forcing a known test layout, or making this assertion conditional on layout data being available.
Useful? React with 👍 / 👎.
…ev#259) Write/Rewrite mode could not read selected text from external apps (Zed, VS Code, Chrome/Docs, Obsidian) because TextSelectionService was AX-tree-only: when kAXFocusedUIElementAttribute returns nothing for Electron / GPU-rendered editors, both AX strategies fail and selection capture returned nil, silently degrading to a fresh prompt instead of rewriting the selection. Add a third fallback in getSelectedText(): synthesize Cmd+C, poll the pasteboard changeCount until the target app writes (bounded timeout, since Cmd+C is async), read the copied string, then always restore the user's previous pasteboard contents. An empty selection produces no pasteboard write, so it times out and returns nil, preserving the existing write-mode behavior. Extract the existing pasteboard snapshot/restore logic from TypingService into a shared PasteboardSnapshot value type so both the paste-insertion path and the new selection-read path use one full-fidelity implementation instead of duplicating it.
…t-aware Cmd+C (altic-dev#259) Address two issues found in code review of the synthetic-Cmd+C selection fallback added in d25796b. 1. Late-write clipboard clobber. getSelectedTextViaClipboard() restored the user's pasteboard unconditionally right after the 300ms copy-wait timeout. A slow/busy target app could process the synthetic Cmd+C *after* that restore, and its delayed pasteboard write would clobber the restored clipboard — leaving the copied selection where the user's content belongs, breaking the "always restore the user's clipboard" guarantee. Replace the unconditional restore with restoreClipboardDefensively(_:to:): restore, record the change count our own restore produced, then poll a short bounded settle window; any further write (the app's late copy) is re-restored. Doubly bounded (200ms total / max 3 re-restores) so it cannot hang, and every exit path ends having just re-restored the user's snapshot so it cannot leave the selection on the clipboard. Synchronous on the main thread, consistent with the existing copy-wait; only paid on this last-resort fallback path. 2. Cmd+C key code was not layout-aware. postSyntheticCopy() hard-coded kVK_ANSI_C, so on Dvorak/AZERTY/QWERTZ it posted Cmd+<wrong-char> and never copied. Extract TypingService's existing TIS/UCKeyTranslate layout lookup (used for Cmd+V) into a shared LayoutAwareKeyCode enum and route both the Cmd+V paste path and the new Cmd+C path through it, re-evaluated per call so runtime layout switches are picked up, with the ANSI key code as fallback. Add LayoutAwareKeyCode unit tests (resolves Latin chars, falls back for an unmappable character, deterministic across calls). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… session (altic-dev#259) The Write/Rewrite selection-read fallback (TextSelectionService. getSelectedTextViaClipboard) snapshotted and restored NSPasteboard.general around a synthetic Cmd+C without coordinating with TypingService's paste path. TypingService.withTemporaryPasteboardString keeps a temporary string on the same pasteboard and defers the user-clipboard restore onto a background queue, holding pasteboardSessionSemaphore until that async restore completes (up to ~5s later). If a new rewrite's selection read sampled changeCount while a prior paste's restore was still pending, the paste's writes were mistaken for the user's copy (wrong selection captured) and the two snapshot/restores fought over the real pasteboard. Extract the semaphore + restore queue out of TypingService into a shared PasteboardSession type (mirroring the PasteboardSnapshot / LayoutAwareKeyCode extractions) so both subsystems share one mutual-exclusion primitive instead of racing parallel locks. The selection read now acquires the same session (bounded wait) around its snapshot -> Cmd+C -> read -> restore sequence, so it cannot sample changeCount or touch the pasteboard while a paste session is in flight. The acquire is a timed wait (tryBeginExclusive). This is load-bearing for deadlock-freedom: the paste path resolves the layout-aware Cmd+V key code via LayoutAwareKeyCode, which does DispatchQueue.main.sync when off-main, so a background paste can hold the session while waiting on the main thread; a blocking acquire on the main-thread selection read would let the two wait on each other. The timeout breaks that inversion (on expiry the read proceeds unguarded, no worse than the prior uncoordinated behavior) and bounds any main-thread stall. TypingService keeps identical behavior (pure rename to the shared session). Adds PasteboardSession unit tests; LayoutAwareKeyCode tests still pass.
Use a short non-blocking pasteboard session wait and skip the synthetic-copy selection fallback on contention to avoid main-thread stalls. Only restore the pasteboard after an observed copy write, preserving complex clipboard contents when Cmd+C times out without changing the pasteboard.
c7fbc7f to
8de9731
Compare
Greptile SummaryAdds a synthetic, layout-aware Cmd+C fallback for reading selections unavailable through Accessibility APIs while preserving clipboard contents.
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8de9731a8b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| return | ||
| } | ||
| restoresRemaining -= 1 | ||
| snapshot.restore(to: pasteboard) |
There was a problem hiding this comment.
Preserve unrelated clipboard writes during settle polling
When the user or a clipboard manager writes new clipboard contents during the 200 ms settle window, the loop treats every changeCount update as a delayed response to Fluid's Cmd+C and restores the stale pre-copy snapshot here. This can silently discard a legitimate clipboard update, including after the synthetic copy was already observed and restored; verify that the new contents belong to the pending synthetic copy or leave unrelated external writes intact, as the paste path does.
Useful? React with 👍 / 👎.
|
Confirmed, the finding is real. I built and tested a payload-aware fix, but I'm holding it back: adversarial review found a stale-restore sequence after a confirmed external write, and the revision that fixed it exposed a second-observation race of its own. The correct version needs one coherent pasteboard observation per change-count generation, shared by both the classification and the restore target, plus deterministic coverage of the interleavings. I'll update this PR once that version is clean rather than iterating in public. |
…rvation The settle watch restored on any pasteboard change, so a genuine clipboard write landing in that window got overwritten. Three earlier attempts each failed adversarial review under specific interleavings. This replaces the fixed restore target and unconditional late-write restore with a payload-aware moving-target arbiter built on one idea: a single immutable observation per poll, carrying both the value used to classify a write and the full snapshot that would become the restore target. PasteboardObservation holds a generation, a full PasteboardSnapshot, and a plain-text projection computed from that snapshot's own bytes, so the text a write is classified by and the state that would be restored cannot diverge. A capture is accepted only when changeCount is equal before and after it. Only a generation with readable text carries a snapshot, so an unreadable one cannot be adopted as a restore target by accident. The settle loop and the final reconciliation call the same routine. restore(to:) now reports the restore generation and write success separately, so a failed write is never reported as a restore. Test seams exist to make the interleaving coverage deterministic rather than raced. Each invariant was reverted one at a time to confirm the intended test fails and the others do not.
Three independent reviews of the prior revision found a data-loss path and several production seams that no test pinned. captureStable accepted an itemless snapshot as a stable pre-operation restore target. A writer between clearContents() and publishing its payload produces exactly that: the clear advances the generation, the later write does not, so both reads agree and an empty snapshot becomes the target that later overwrites the writer's content. It now re-polls a bounded window when the capture is itemless, since a non-text clipboard has items and must pass through untouched. The ambiguity is emptiness, not unreadability. Also: fall through to the clipboard fallback when an accessibility read returns an empty string rather than an error, and resolve the copy key code with the Command modifier actually used by the shortcut, which differs on layouts such as Dvorak - QWERTY Command. Adds tests pinning the restore-failure outcome and the settle loop's continued watching, both of which previously admitted a passing mutant.
…ns, and stop a caret firing a synthetic copy
Two defects found by adversarial review of the previous revision, each pinned by a
mutation watched failing on the mutant and passing clean.
PasteboardSnapshot's settle gate now asks whether any declared representation
produced a Data value, rather than whether the pasteboard has items.
declareTypes(_:owner:) is a common rich-text declare-then-publish path for
applications that expose multiple promised representations: it advances the
generation and leaves one item whose every data(forType:) is nil until the
payload lands. An item-count test called that non-empty and adopted a
representation-less snapshot as the restore target, so the later restore wiped
whatever that writer published. Items carrying data still return immediately, so
image and file-list clipboards are unaffected, and a zero-length Data() is itself
a captured representation, so transient markers survive intact. The property is
named hasNoCapturedRepresentations because "empty" described neither what it
measures nor how it differs from restore's structural item check.
TextSelectionService now distinguishes an accessibility answer from a failed
read. A selected range that reads successfully and reports zero length is a caret
with nothing selected, not an unreadable element, and it no longer falls through
to the clipboard fallback, which is a synchronous Cmd+C on the main thread that
was firing on every no-selection Edit-mode press. kCFNotFound, NSNotFound and all
negative locations remain unavailable rather than becoming caret confirmations:
kCFNotFound is -1 while NSNotFound is Int.max, and macOS 26 has been reported to
return {NSNotFound, 0} for an element with no valid caret, so a kCFNotFound-only
test would have read that as a confirmed caret and suppressed the fallback for
exactly the editors this path exists to serve.
Both accessibility strategies still run before the fallback is considered,
because the system-wide focused element and the frontmost app's focused element
can resolve to different elements and the second may hold a selection the first
could not see. The fallback is suppressed if either strategy affirmatively
reported a caret. That last part is a judgment call on an underdetermined trade
rather than a proof, and the PR body states it plainly and asks for the
maintainer's preference.
getSelectedText(from:) takes a defaulted attribute reader so its accessibility
branches can be driven with a constructed AXValue. Production callers pass
nothing and behave identically.
Several code comments claimed guarantees the implementation does not provide
(full-fidelity capture, reliable copy attribution, unconditional late-write
restoration, a loop that cannot hang) and are corrected here to match what the
code does.
This commit adds 13 tests; the PR now contains 41 added tests. The full
DictationE2ETests class runs 122 tests with 0 failures on this revision, and
SwiftLint --strict is clean across 158 files.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 187a66fcd8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| keyDown.flags = .maskCommand | ||
| keyUp.flags = .maskCommand | ||
|
|
||
| keyDown.post(tap: .cghidEventTap) |
There was a problem hiding this comment.
Prevent synthetic selections from entering clipboard history
When a clipboard-history manager is running, posting Cmd+C publishes the selected text as an ordinary target-app clipboard write, so the manager can persist sensitive content before Fluid restores the previous snapshot. The paste insertion path explicitly adds Transient/AutoGenerated markers in TypingService.makeTransientPasteboardItem, but this target-generated copy cannot carry those markers; restoring the pasteboard afterward does not remove the captured history. Please avoid enabling this fallback without an opt-in/warning or otherwise prevent clipboard-history capture.
Useful? React with 👍 / 👎.
|
Closing this one. The fallback turns on a call I asked for in the body, whether to suppress it when one accessibility strategy confirms a caret and the other cannot resolve its element at all, and nobody has had a chance to weigh in. It has also gone conflicting with main since. The branch is still on my fork at |
Description
Adds a clipboard (synthetic Cmd+C) fallback so Write/Rewrite mode can read the selected text in apps
whose Accessibility tree does not expose it, such as Electron and GPU-rendered editors (Zed, VS Code,
Chrome, Obsidian). Previously selection capture returned nil in those apps and the feature silently
degraded to a fresh prompt instead of rewriting the selection.
Because the fallback has to put the user's clipboard back afterwards, most of this PR is about not
destroying a clipboard write that arrives while it is doing that.
How it works
TextSelectionService.getSelectedText()gains a third fallback after the two AX strategies:synthesize Cmd+C, poll
changeCountuntil the target app writes, read the copied string, thenrestore the user's previous pasteboard.
TypingServiceinto a sharedPasteboardSnapshotvalue type, so the paste path and this read path share one implementation.
UCKeyTranslatemechanism the Cmd+V path uses (extracted into a shared
LayoutAwareKeyCode), so it lands on theright physical key on Dvorak, AZERTY and similar. Falls back to the ANSI key code when layout data
is unavailable.
current target when a readable write is classified as the synthetic copy. Unreadable writes,
restore failures, budget exhaustion and writes outside the observation horizon can remain.
The part worth reviewing
A static analysis pass flagged that the settle watch restored on any pasteboard change, so a genuine
clipboard write landing in that window got overwritten. Fixing that turned out to be harder than it
looks, and three earlier attempts in this PR were wrong in ways that only showed up under specific
interleavings. The current design is built around one idea:
One immutable observation per poll, carrying both the value used to classify the write and the
captured pasteboard state that would become the restore target.
PasteboardObservationis that value. It holds a generation, aPasteboardSnapshot, and aplain-text projection computed from that snapshot's own captured
Datarepresentations. It isaccepted only if
changeCountis identical before and after the capture, and only a generation withreadable text carries a snapshot at all, so an unreadable one cannot be adopted as a restore target
by accident.
LateWriteArbiteris the state machine. It owns a moving restore target: once a write has beenpositively distinguished from the recorded copy text, that write is the user's current clipboard and
becomes what a later matching write is reverted to. The regular settle loop and the final
reconciliation call the same routine, so there is one classifier path rather than two.
Capturing the clipboard before we touch it has the same problem in miniature.
clearContents()empties the pasteboard and advances the generation, and the writer's payload that follows does not
advance it again. So a capture taken inside someone else's clear-then-publish window is internally
consistent and holds nothing, and adopting it would mean restoring an empty clipboard over whatever
they published.
declareTypes(_:owner:)opens the same window with an item already present but everyrepresentation still nil, which is a common rich-text declare-then-publish path for applications that
expose multiple promised pasteboard representations. Rejecting empty outright would be wrong, since a
genuinely empty clipboard has to be preserved as
empty, and so would gating on readable text, since a non-text clipboard must be kept exactly as it
is. So the gate is on whether any declared representation produced a
Datavalue, and that case isre-polled for a bounded interval before being accepted.
Accessibility, and when the fallback should not run. A selected range that reads successfully and
reports zero length is an answer, not a failed read: it means a caret sitting in a field with nothing
selected, which is every ordinary Cocoa text field. Treating it as a failure sent every no-selection
Edit-mode press into the clipboard fallback, which is a synchronous Cmd+C on the main thread. Both AX
strategies still run, because the system-wide focused element and the frontmost app's focused element
can resolve to different elements and the second may hold a selection the first could not see. Only
after both have run without producing text is the fallback considered, and it is suppressed if either
strategy affirmatively reported a caret.
There is a judgment call in that last sentence and I would rather flag it than bury it. The
ambiguous case is one strategy confirming a caret while the other cannot resolve its element at all.
Suppressing there means a selection the second element might have held is missed: no selected context
is captured, and the caller follows the same fresh-prompt path it follows on
mainwhen AX returnsno selection. Write Mode still works, it just is not selection-aware. Not suppressing means firing a real
Cmd+C into an app we could not read, and in editors that define Cmd+C with a caret as "copy current
line" (VS Code among them) that returns the current line as though it had been selected, so Rewrite
Mode would rewrite text the user never selected. I picked suppression because failing to engage is
the status quo while rewriting an unselected line is an active wrong action. That is a preference
about which failure is worse, not a proof: a confirmed caret is evidence about the element that
produced it, and it does not establish anything about the element that could not be read.
I would rather have your call than my guess here. If you would rather the fallback always run
when either element is unreadable, it is a one-line change and I will make it. Distinguishing the two
elements properly (comparing whether both strategies resolved the same element, so one confirmation
is authoritative only when they did) would remove the guess entirely, but it is more than this PR
should take on without your say-so.
Note for the paste path: the layout-aware key-code helper now resolves against the Command
modifier state the shortcut actually carries. That helper is shared, so this changes Cmd+V
resolution in
TypingServiceas well as Cmd+C here. It is the same bug in both places (on layoutslike macOS's built-in "Dvorak - QWERTY ⌘" the key that produces a character unmodified is not the
one that produces it with Command held), and the helper is code this PR introduced, but it does
touch the paste path and you should not have to find that in the diff.
Type of Change
Related Issue or Discussion
Closes #259
Testing
swiftlint --strict --config .swiftlint.yml Sourcesswiftformat --config .swiftformat SourcesDetail, all re-derived on the exact revision being pushed:
swiftlint --strict --config .swiftlint.ymlover the whole repo: clean, 0 violations across 158files.
xcodebuild build-for-testing, signed, Apple Silicon: succeeds. The only build warnings are thepre-existing
CTranscribe.framework/Versions/Currentsymlink ones, unrelated to this change.DictationE2ETests. The full class runs 122 tests with 0 failures on thisrevision.
CI remains the authority on the rest.
Screenshots / Video
Notes
What this establishes
Stated narrowly on purpose.
that may become the restore target come from the same generation-stable observation. The handler
does not classify one observation and then capture a different live state.
budget and a successful restore, a later handled write matching the recorded copy text is reverted
to that target rather than to the older pre-copy clipboard.
data(forType:)call produced aDatavalue isre-polled for a bounded interval. That mitigates the common clear-or-declare-before-publish
window. It is not a completeness guarantee.
strategies still run before the fallback is considered, and the fallback is suppressed if either
strategy affirmatively reported a caret. See the note above on the ambiguous case, which is a
judgment call rather than a proof.
That is the whole claim. It is not a general fix for the underlying race. The classifier does not
determine who wrote anything. It compares text, which is not authorship.
What this does not fix
NSPasteboardexposes no writer provenance, and capture, comparison, restoration and baselinesampling are not one atomic transaction. Known limitations:
the Cmd+C and returned as the selection. That window opens before the key events are posted.
treated as the delayed copy and restored over.
RTF or metadata differ.
clearContents()and its payload. An unreadable late-write observation is not adopted as themoving restore target. Separately, the pre-operation capture may accept a representation-less
snapshot once its bounded settle interval expires, because a genuinely empty clipboard has to stay
representable.
restore created. Every poll then sees an unchanged generation and that write is never adopted.
clearContents()thenwriteObjects, not atomic. A clear landing between those two canleave the restore's items published into the external writer's generation, producing a merged state
the arbiter may then coherently adopt.
its end. A new empty-looking generation arriving near the deadline can be accepted before its
publisher has had the full interval, and its later same-generation payload can then be overwritten.
This is a known data-loss path and the representation gate does not close it.
capturerecordsonly types whose
data(forType:)returns non-nil and does not remember that another declared typeexisted and failed to read. If
.stringreads while a promised.html,.rtfor custom type doesnot, the snapshot is accepted without it and a later restore drops it permanently. The same gap
applies to a readable external write adopted as the moving target, and that path does not go
through the pre-operation settle gate at all, so the gate is unreachable from it.
editors define Cmd+C with a caret as "copy current line", the fallback can return the current line
as though it were a selection.
late payload may remain, be treated as external, or be overwritten.
clearContents()always lands, so a rejected write leaves the clipboardempty or incomplete. That is reported as a failure and logged, never as a restore.
the fallback is skipped and no selection is returned.
NSNotFoundlocation with zero length as a caretwithout checking it against the element's text length, so a location past the end of the value is
treated as a confirmed caret rather than as unusable. Separately, for positive-length ranges the
bounds check computes
range.location + range.lengthbefore comparing it, so an extreme malformedpositive pair could overflow before the comparison rejects it. The known macOS 26
{NSNotFound, 0}sentinel is rejected upstream of both, and I have no evidence of AX producinganother giant positive value, so I have left this as defense-in-depth worth naming rather than
widening the change to chase it.
On timing: the settle watch is a nominal polling horizon plus one terminal reconciliation, not a
wall-clock bound.
data(forType:), string conversion and lazily supplied items have no bound, so aread already in flight can finish past the horizon.
Where this is worse than the earlier clipboard-fallback revisions in this PR
To be clear about the baseline:
mainhas no clipboard fallback and no settle watch at all, so onmainnone of this code runs and no selected context is captured in these apps. The comparisonsbelow are against the earlier fallback implementations on this branch, not against upstream.
in the settle window, so a delayed copy that had cleared but not yet published would be reverted.
This treats an unreadable generation as ambiguous and leaves it, which is right when it is
somebody's image and wrong when it is our own copy mid-publish. In that interleaving the earlier
revision recovered the user's clipboard and this does not.
payload means an unrelated write landing in that window can be returned as the selection. In the
earlier revision that window was effectively zero, because the read happened immediately.
pre-operation capture, the fallback is abandoned and no selection is returned. The earlier revision
would have proceeded from the inconsistent capture. Upstream
mainhad no clipboard fallback andalso returned no selected context, so this is worse only relative to the earlier revision.
pasteboard inside each settlement window and across as many as three outer attempts, so large or
lazily supplied clipboards can incur more than three full captures on the main thread.
One deliberate deviation from the design I worked to
Synthetic restores baseline on the generation returned by
clearContents()inside the restore,rather than re-reading
changeCountafterwards. A re-read can sample a count an external writer hasalready advanced, which records "already handled" for a generation whose contents were never
observed. That is the exact race the returned generation closes. Flagging it because it differs from
the pseudocode I was working to, and it is deliberate rather than drift.
AppKit behaviors this design leans on, probed rather than assumed
Five assumptions here are load-bearing and none of them are clearly documented, so I checked them
with a standalone script against a named pasteboard:
clearContents()return value equals the post-clearchangeCountsetStringafter a clear does not advancechangeCountwriteObjectsafter a clear does not advancechangeCountstring(forType:)joins item texts with newlinesThe last one is also stated in
NSPasteboard.h, and it is why the text projection concatenates everytext-bearing item rather than taking the first. Taking the first would change the selection this
fallback returns and would make two different multi-item clipboards compare equal.
The third and fourth matter beyond documentation: if
writeObjectsdid advancechangeCount, everyrestore would leave the baseline stale by one and the loop could spend its whole budget restoring
over itself.
Test seams
The tests drive the state machine with constructed observations and assert on a returned outcome
value, so each test proves the branch it targets actually ran. The seams exist to make that
deterministic instead of racing a background writer:
PasteboardObservation.capture(from:currentGeneration:)lets a test simulate a write landingmid-capture, so the discard path is proven rather than raced.
readSettledObservation(from:capture:)lets a test make the terminal capture unstable, proving thehelper returns nothing instead of an earlier observation.
restoreClipboardDefensively(settleWindowMicros:)lets a test set the polling horizon to zero, sothe final-edge reconciliation is the only thing that can act.
restoreClipboardDefensively(performRestore:)and the matching arbiter parameter let a test land anexternal write immediately after a restore, which is the only way to show the baseline comes from
the restore's own generation rather than a later live re-read.
PasteboardSnapshot.captureStable(from:emptySettleMicros:)lets a test drive the settle horizondirectly, so "returns a data-bearing clipboard without waiting" is asserted against a clock rather
than merely stated.
getSelectedText(from:confirmedNoSelection:readAttribute:)takes a defaulted attribute reader, sotests can drive the real accessibility branch with a genuine
AXValueinstead of needing a livefocused element.
Production callers pass none of these and behave identically.
I verified the tests actually discriminate by reverting each invariant one at a time and checking
which tests fail:
NSNotFoundor a negative location treated as a valid caretWhat is still not pinned
Naming these rather than leaving them to be discovered:
UCKeyTranslateis still unpinned.LayoutAwareKeyCode.virtualKeyCodedefaultscarbonModifierStateto zero and the existing layouttests omit the argument, so deleting it from the production call sites would leave those tests
green. The change is a no-op except on modifier-dependent layouts, which is exactly what makes it
hard to pin without making one of those layouts active.
where it is set and where it is folded, but the two points that forward it out of
getSelectedText(from:)sit above the injected reader, so no injected value reaches them. Coveringthem would mean injecting the element resolvers into the one externally called method.
data-loss path named above has no test that could pass only if it were fixed.
undetected rather than merely unfixed.
I would rather say all of that plainly than have the table imply a completeness it does not have.