Skip to content

fix: add clipboard fallback for Write Mode selection reading (#259) - #387

Closed
postoso wants to merge 7 commits into
altic-dev:mainfrom
postoso:fix/259-writemode-clipboard
Closed

postoso wants to merge 7 commits into
altic-dev:mainfrom
postoso:fix/259-writemode-clipboard

Conversation

@postoso

@postoso postoso commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

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 changeCount until the target app writes, read the copied string, then
    restore the user's previous pasteboard.
  • The snapshot/restore logic is extracted from TypingService into a shared PasteboardSnapshot
    value type, so the paste path and this read path share one implementation.
  • The copy key code is resolved against the active keyboard layout via the same TIS/UCKeyTranslate
    mechanism the Cmd+V path uses (extracted into a shared LayoutAwareKeyCode), so it lands on the
    right physical key on Dvorak, AZERTY and similar. Falls back to the ANSI key code when layout data
    is unavailable.
  • After the copy, a bounded settle watch observes late pasteboard writes and attempts to restore the
    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.

PasteboardObservation is that value. It holds a generation, a PasteboardSnapshot, and a
plain-text projection computed from that snapshot's own captured Data representations. It is
accepted only if changeCount is identical before and after the capture, and only a generation with
readable text carries a snapshot at all, so an unreadable one cannot be adopted as a restore target
by accident.

LateWriteArbiter is the state machine. It owns a moving restore target: once a write has been
positively 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 every
representation 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 Data value, and that case is
re-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 main when AX returns
no 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 TypingService as well as Cmd+C here. It is the same bug in both places (on layouts
like 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

  • 🐞 Bug fix
  • ✨ New feature
  • 💥 Breaking change
  • 🧹 Chore
  • 📝 Documentation update

Related Issue or Discussion

Closes #259

Testing

  • Tested on Intel Mac
  • Tested on Apple Silicon Mac
  • Tested on macOS version:
  • Ran linter locally: swiftlint --strict --config .swiftlint.yml Sources
  • Ran formatter locally: swiftformat --config .swiftformat Sources
  • Ran tests locally

Detail, all re-derived on the exact revision being pushed:

  • swiftlint --strict --config .swiftlint.yml over the whole repo: clean, 0 violations across 158
    files.
  • xcodebuild build-for-testing, signed, Apple Silicon: succeeds. The only build warnings are the
    pre-existing CTranscribe.framework/Versions/Current symlink ones, unrelated to this change.
  • This PR adds 41 tests to DictationE2ETests. The full class runs 122 tests with 0 failures on this
    revision.
  • I have not run the entire existing suite on this revision, only the test class this PR touches, so
    CI remains the authority on the rest.

Screenshots / Video

  • No UI/visual changes; screenshots/video are not applicable.

Notes

What this establishes

Stated narrowly on purpose.

  1. For each readable late-write decision, the text used to classify and the captured pasteboard state
    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.
  2. The restore target moves to the latest accepted readable external write. Subject to the restore
    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.
  3. Before posting Cmd+C, a capture for which no data(forType:) call produced a Data value is
    re-polled for a bounded interval. That mitigates the common clear-or-declare-before-publish
    window. It is not a completeness guarantee.
  4. A valid zero-length AX selected range is treated as an affirmative no-selection answer. Both AX
    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

NSPasteboard exposes no writer provenance, and capture, comparison, restoration and baseline
sampling are not one atomic transaction. Known limitations:

  • Any unrelated readable write during the copy wait or the payload-settle read can be attributed to
    the Cmd+C and returned as the selection. That window opens before the key events are posted.
  • If Cmd+C times out, a legitimate readable external write inside the late-write window can be
    treated as the delayed copy and restored over.
  • An external write whose plain text equals the copied text is treated as ours even when its HTML,
    RTF or metadata differ.
  • A nil, empty or non-text generation cannot be told apart from a writer caught between
    clearContents() and its payload. An unreadable late-write observation is not adopted as the
    moving 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.
  • A writer that cleared before our restore can publish after it, landing at the generation our
    restore created. Every poll then sees an unchanged generation and that write is never adopted.
  • Restore is clearContents() then writeObjects, not atomic. A clear landing between those two can
    leave the restore's items published into the external writer's generation, producing a merged state
    the arbiter may then coherently adopt.
  • The pre-operation settle interval is measured from the call, not from the generation accepted at
    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.
  • Snapshot capture is incomplete when a declared representation returns nil. capture records
    only types whose data(forType:) returns non-nil and does not remember that another declared type
    existed and failed to read. If .string reads while a promised .html, .rtf or custom type does
    not, 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.
  • In an AX-opaque editor, no-selection is still indistinguishable from AX unavailability. Since some
    editors define Cmd+C with a caret as "copy current line", the fallback can return the current line
    as though it were a selection.
  • If the copy's payload publishes after the settle helper gives up, no copy text is recorded and the
    late payload may remain, be treated as external, or be overwritten.
  • Once the polling horizon or the restore budget is reached, a delayed write can remain.
  • Restore writes can fail. clearContents() always lands, so a rejected write leaves the clipboard
    empty or incomplete. That is reported as a failure and logged, never as a restore.
  • If the pasteboard will not hold still for a coherent pre-operation capture across three attempts,
    the fallback is skipped and no selection is returned.
  • The caret check accepts any nonnegative, non-NSNotFound location with zero length as a caret
    without 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.length before comparing it, so an extreme malformed
    positive 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 producing
    another 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 a
read 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: main has no clipboard fallback and no settle watch at all, so on
main none of this code runs and no selected context is captured in these apps. The comparisons
below are against the earlier fallback implementations on this branch, not against upstream.

  • Unreadable late writes are no longer restored over. The earlier revision restored on any change
    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.
  • The payload settle widens the wrong-selection window. Waiting up to 30 ms for a readable
    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.
  • A new skip-entirely failure mode. If the pasteboard will not hold still for a coherent
    pre-operation capture, the fallback is abandoned and no selection is returned. The earlier revision
    would have proceeded from the inconsistent capture. Upstream main had no clipboard fallback and
    also returned no selected context, so this is worse only relative to the earlier revision.
  • Cost on a large non-text clipboard. Under churn, stable capture may repeatedly copy the
    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 changeCount afterwards. A re-read can sample a count an external writer has
already 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:

Behavior Result
clearContents() return value equals the post-clear changeCount confirmed
setString after a clear does not advance changeCount confirmed
A payload published into a cleared generation is readable with no second bump confirmed
writeObjects after a clear does not advance changeCount confirmed
Multi-item string(forType:) joins item texts with newlines confirmed, including a leading newline for an empty first item

The last one is also stated in NSPasteboard.h, and it is why the text projection concatenates every
text-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 writeObjects did advance changeCount, every
restore 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 landing
    mid-capture, so the discard path is proven rather than raced.
  • readSettledObservation(from:capture:) lets a test make the terminal capture unstable, proving the
    helper returns nothing instead of an earlier observation.
  • restoreClipboardDefensively(settleWindowMicros:) lets a test set the polling horizon to zero, so
    the final-edge reconciliation is the only thing that can act.
  • restoreClipboardDefensively(performRestore:) and the matching arbiter parameter let a test land an
    external 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 horizon
    directly, 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, so
    tests can drive the real accessibility branch with a genuine AXValue instead of needing a live
    focused 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:

Reverted invariant Result
moving restore target removed moving-target and coherence tests fail
retarget captures the live pasteboard instead of the observation coherence test fails, and only that one
baseline resynchronized on an unreadable generation no-resync test fails, and only that one
payload-settle helper falls back to an earlier observation no-resurrection test fails, and only that one
retarget baselines on a live read instead of the observed generation the observed-payload test fails on both its assertions
final-edge reconciliation deleted final-edge test fails
initial restore baselines on a live re-read initial-baseline test fails, and only that one
arbiter synthetic restore baselines on a live re-read arbiter-baseline test fails, and only that one
pre-operation capture adopts a representation-empty snapshot without waiting rich-text-copy test fails
pre-operation gate keyed on readable text instead of captured representations data-bearing-clipboard timing test fails
a rejected restore write is reported as a restore restore-failure test fails, and only that one
the settle loop stops after its first restore keeps-watching test fails, and only that one
NSNotFound or a negative location treated as a valid caret NSNotFound test and the fallback-still-reached test fail
the caret confirmation never reaches the caller confirmed-caret propagation test fails
fallback still fires when only one strategy confirms a caret both mixed-state tests fail, one per direction

What is still not pinned

Naming these rather than leaving them to be discovered:

  • The Command modifier state passed to UCKeyTranslate is still unpinned.
    LayoutAwareKeyCode.virtualKeyCode defaults carbonModifierState to zero and the existing layout
    tests 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.
  • Two tokens on the accessibility path are not mutation-covered. The confirmation flag is pinned
    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. Covering
    them would mean injecting the element resolvers into the one externally called method.
  • The pre-operation empty-settlement path is bounded by the horizon, not generation-relative, so the
    data-loss path named above has no test that could pass only if it were fixed.
  • Completeness-aware capture is not implemented, so the partial-capture loss named above is
    undetected rather than merely unfixed.

I would rather say all of that plainly than have the table imply a completeness it does not have.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +69 to +71
let pasteboard = NSPasteboard.general
let snapshot = PasteboardSnapshot.capture(from: pasteboard)
let changeCountBeforeCopy = pasteboard.changeCount

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@postoso

postoso commented Jun 22, 2026

Copy link
Copy Markdown
Contributor Author

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.

@postoso
postoso force-pushed the fix/259-writemode-clipboard branch from 110b975 to c7fbc7f Compare June 26, 2026 04:22

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@postoso

postoso commented Jun 26, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@postoso

postoso commented Jun 26, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +632 to +633
let cKey = LayoutAwareKeyCode.virtualKeyCode(for: "c", qwertyFallback: sentinel)
let vKey = LayoutAwareKeyCode.virtualKeyCode(for: "v", qwertyFallback: sentinel)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

postoso and others added 4 commits August 13, 2026 21:33
…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.
@postoso
postoso force-pushed the fix/259-writemode-clipboard branch from c7fbc7f to 8de9731 Compare August 14, 2026 02:08
@greptile-apps

greptile-apps Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Greptile Summary

Adds a synthetic, layout-aware Cmd+C fallback for reading selections unavailable through Accessibility APIs while preserving clipboard contents.

  • Extracts shared keyboard-layout resolution and pasteboard snapshot/session helpers.
  • Coordinates selection reads with clipboard-based text insertion.
  • Adds bounded late-write arbitration and expanded integration coverage for clipboard races.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (2): Last reviewed commit: "fix(write-mode): gate pre-operation capt..." | Re-trigger Greptile

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@postoso

postoso commented Aug 16, 2026

Copy link
Copy Markdown
Contributor Author

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@postoso

postoso commented Sep 20, 2026

Copy link
Copy Markdown
Contributor Author

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 postoso:fix/259-writemode-clipboard. If #259 becomes a priority, say so and I will rebase it and take your answer on that question.

@postoso postoso closed this Sep 20, 2026
@abhinavm24 abhinavm24 mentioned this pull request Oct 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[🐞 BUG] Write Mode cannot read selected text from any Application

1 participant