hex/src/paste/capture.rs
Dax 341046f8d6
macos 27.3: require keystroke permission for paste, request it, and fail visibly (#2757)
* macos 27.3: require keystroke permission for paste, request it, and fail visibly

macOS 27.3 splits the old Accessibility grant into Accessibility (assistive
technologies) and System & App Protection Override (apps that control other
apps, posting ⌘V included). The Accessibility grant no longer proves Hex may
post a keystroke, so setup read Ready from AXIsProcessTrusted alone, never
asked macOS, and CGEventPost silently dropped every paste while Hex logged a
successful delivery and wrote History.

- Setup counts only the post-event preflight on 27.3+, reusing the native
  27.3 version check already used for the pane's name; below 27.3 nothing
  changes. Allow now calls CGRequestPostEventAccess so macOS can list Hex and
  post its Privacy & Security notification, during setup and in the "fix it"
  flow.
- The post-event preflight keeps its launch-time answer, so a row that stays
  untrusted after a grant reads "Needs a restart" and offers Restart Hex in
  the tour, and the Settings row does the same instead of running a tccutil
  reset that would drop the grant the person just made.
- A paste that would post a keystroke refuses before touching the clipboard
  when 27.3+ has not granted posting, with a HUD error naming System & App
  Protection Override. The shared delivery path already keeps the text for
  Paste last dictation and writes no History entry on a failed insert.

Docs note the 27.3 behavior and that no 27.3 device has verified it.

* macos 27.3: restart once per grant, explain a refused paste, and guard captures

Review fixes for the 27.3 keystroke grant.

- Restart Hex was a dead end: every stale Accessibility row on 27.3 offered
  it, so a grant that never landed looped between "Needs a restart" and a
  launch, and the tour row had no way back to the guide. The one restart is
  now recorded in onboarding-accessibility-restart (cleared when
  Accessibility reads Ready, and by a setup reset or identity change). After
  that restart a stale row falls back to the existing "Still grey? Fix it"
  reset-and-prompt flow, in the tour and in Settings > Permissions needed.
- A refused paste's HUD notice was gated by Labs > Failure notices (off by
  default), so the one failure that needs a person to act showed nothing. Its
  message is now a shared constant that the HUD explains regardless of the
  lab, through tr() with the six main languages and the four extra ones.
- Captures take the same check before touching the clipboard: Paster's
  paste_capture and the capture hand-off. The capture helper's Allow asks
  with CGRequestPostEventAccess so 27.3 can list Hex.
- The keystroke check runs before Labs > Return to app brings another app
  forward, so a refusal doesn't switch apps for a paste that cannot land.
- CGRequestPostEventAccess is a safe fn; request_post_event_access returns
  () and logs its answer instead of returning a bool no caller could use.
  The reset flow's request stays: after the restart fallback it is reachable
  again.

Docs now say what the person sees, which tests cover it, and that the
refusal itself has not run on a 27.3 device.

* macos 27.3: re-arm the restart after a reset, and explain a refused paste last

Second review fixes.

- After the one Restart Hex, "Still grey? Fix it" could never succeed: the
  marker was only cleared on Ready/setup reset/identity change, so reset ->
  grant still showed the reset row and Restart never came back. The reset
  dispatch now clears the one-restart marker for Accessibility on 27.3, so
  every cycle is reset -> grant -> one restart, user-driven. The poll re-reads
  it; Flow and Settings tests cover restart -> stale -> reset -> stale ->
  Restart again.
- A refused Paste Last only played the error tone. It now sends the same
  capture-level failure the dictation path uses, so the HUD notice explains it
  even with Labs > Failure notices off; other Paste Last failures keep the tone
  and log only. A refused capture hand-off still only logs, and the docs now
  say so instead of claiming every path shows the notice.
- Record the one restart only for the Accessibility row: the tour's
  restarts_for_post_event and the Settings stale row's restart. A Screen
  Recording or microphone Restart no longer spends it.
- Clear the marker only when accessibility_restart_done is set, and skip the
  marker stat entirely below 27.3.
2026-11-24 16:00:56 -05:00

258 lines
8.2 KiB
Rust

//! Insertion only. Neither selecting a capture nor preparing its two parts
//! should take the clipboard, reactivate an app, or affect an Annotate send.
use super::clipboard_restore::CLIPBOARD_RESTORE_DELAY;
use super::{
CLIPBOARD_MANAGER_MARKERS, ClipboardRestore, Paster, capture_clipboard, restore_clipboard,
write_items,
};
use color_eyre::eyre::{Result, eyre};
use objc2::rc::Retained;
use objc2_app_kit::{NSPasteboard, NSPasteboardItem, NSPasteboardTypeString};
use objc2_foundation::{NSData, NSString};
use scrawl_capture::model::ScrawlBundle;
use std::path::Path;
use std::time::Duration;
pub(crate) enum Part<'a> {
Text(&'a str),
Png(&'a [u8]),
}
enum Sheet {
Png(Vec<u8>),
Path(String),
}
pub(crate) struct Payload {
sheet: Option<Sheet>,
summary: String,
}
impl Payload {
/// Annotate's Paste uses the rich summary with the sheet, independent of
/// the *copy* preference. Do not generate a zip, reactivate an app, or
/// consult the send queue. Prepare every part before taking the board.
pub(crate) fn prepare(
directory: &Path,
bundle: &ScrawlBundle,
terminal: bool,
agent_context: bool,
) -> Result<Self> {
let sheet = if bundle.keyframes.is_empty() {
None
} else {
if bundle.contact_sheet != "contact-sheet.png" {
return Err(eyre!("unexpected capture sheet"));
}
let path = directory.join(&bundle.contact_sheet);
let bytes = crate::capture_host::paste_source::read_regular(&path, 32 << 20)
.ok_or_else(|| eyre!("capture sheet unavailable"))?;
if !bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
return Err(eyre!("invalid capture sheet"));
}
Some(if terminal {
Sheet::Path(path.display().to_string())
} else {
Sheet::Png(bytes)
})
};
Ok(Self {
sheet,
summary: scrawl_capture::sketch::summary_markdown_with(
bundle,
directory,
agent_context,
),
})
}
fn first(&self) -> Option<Part<'_>> {
self.sheet.as_ref().map(|sheet| match sheet {
Sheet::Png(bytes) => Part::Png(bytes),
Sheet::Path(path) => Part::Text(path),
})
}
#[cfg(test)]
pub(crate) fn paste_to_fixture(
&self,
board: &NSPasteboard,
paste: impl FnMut() -> Result<()>,
) -> Result<()> {
insert(
board,
&mut ClipboardRestore::default(),
self.first(),
&self.summary,
|| true,
paste,
|_| {},
)
}
}
impl Part<'_> {
fn item(&self) -> Result<Retained<NSPasteboardItem>> {
let item = NSPasteboardItem::new();
let ok = match self {
Self::Text(text) => {
item.setString_forType(&NSString::from_str(text), unsafe { NSPasteboardTypeString })
}
Self::Png(bytes) => item.setData_forType(
&NSData::with_bytes(bytes),
&NSString::from_str("public.png"),
),
};
if !ok
|| !CLIPBOARD_MANAGER_MARKERS
.iter()
.all(|marker| item.setData_forType(&NSData::new(), &NSString::from_str(marker)))
{
return Err(eyre!("could not prepare the capture for paste"));
}
Ok(item)
}
}
impl Paster {
/// The capture owner supplies the sheet (PNG or terminal path), summary,
/// and the target PID from the gesture. No arbitrary text/command mode.
pub(crate) fn paste_capture(
&mut self,
capture: &Payload,
target: &super::recent::Target,
) -> Result<()> {
// Before the clipboard is touched: macOS 27.3 refuses to post ⌘V
// without its keystroke grant, which would otherwise look like a
// capture that landed.
super::ensure_keystroke_access()?;
// A capture's sheet and summary replace what a running dictation
// watch has in front of it, exactly as another dictation would.
super::note_paste();
let revision = self.activity.revision();
self.continuation.clear();
self.prepared_clipboard = None;
insert(
&self.clipboard,
&mut self
.clipboard_restore
.lock()
.unwrap_or_else(|e| e.into_inner()),
capture.first(),
&capture.summary,
|| self.activity.revision() == revision && target.unchanged(),
|| crate::keyboard::post_command('v'),
std::thread::sleep,
)
}
}
/// A paste key has no delivery acknowledgement. Once attempted, never retry
/// it, including on an error posting a key-up. A later copy always wins.
fn insert(
board: &NSPasteboard,
pending: &mut ClipboardRestore,
sheet: Option<Part<'_>>,
summary: &str,
focused: impl Fn() -> bool,
paste: impl FnMut() -> Result<()>,
wait: impl FnMut(Duration),
) -> Result<()> {
if summary.trim().is_empty() || !focused() {
return Err(eyre!("no capture text or the paste target changed"));
}
let sheet = sheet.map(|s| s.item()).transpose()?;
let summary = Part::Text(summary).item()?;
transaction(board, pending, sheet, summary, focused, paste, wait)
}
trait Board {
type Item;
fn generation(&self) -> isize;
fn save(&self) -> Result<super::ClipboardSnapshot>;
fn claim(&self) -> isize;
fn write(&self, value: Self::Item) -> Result<()>;
fn restore(&self, original: &super::ClipboardSnapshot) -> Result<()>;
}
impl Board for NSPasteboard {
type Item = Retained<NSPasteboardItem>;
fn generation(&self) -> isize {
self.changeCount()
}
fn save(&self) -> Result<super::ClipboardSnapshot> {
capture_clipboard(self)
}
fn claim(&self) -> isize {
self.clearContents()
}
fn write(&self, item: Self::Item) -> Result<()> {
write_items(self, &[item])
}
fn restore(&self, original: &super::ClipboardSnapshot) -> Result<()> {
restore_clipboard(self, original)
}
}
fn transaction<B: Board>(
board: &B,
pending: &mut ClipboardRestore,
sheet: Option<B::Item>,
summary: B::Item,
focused: impl Fn() -> bool,
mut paste: impl FnMut() -> Result<()>,
mut wait: impl FnMut(Duration),
) -> Result<()> {
let initial = board.generation();
let snapshot = board.save()?;
let mut owned = None;
let mut attempted = false;
let outcome = (|| {
for item in sheet.into_iter().chain([summary]) {
if !focused() || board.generation() != owned.unwrap_or(initial) {
return Err(eyre!("paste target or clipboard changed"));
}
// clearContents returns *our* ownership count. Reading changeCount
// after writeObjects could instead adopt an intervening copy.
let count = board.claim();
owned = Some(count);
if board.generation() != count {
return Err(eyre!("clipboard changed before writing the capture"));
}
board.write(item)?;
wait(Duration::from_millis(20));
if !focused() || board.generation() != count {
return Err(eyre!("paste target or clipboard changed"));
}
attempted = true;
paste()?;
wait(Duration::from_millis(160));
}
Ok(())
})();
if let Some(count) = owned {
// Share the prior text paste's original, not its transient payload.
let previous = pending
.take_pending(|&last| last == initial)
.unwrap_or(snapshot);
if attempted && board.generation() == count {
wait(CLIPBOARD_RESTORE_DELAY);
}
if board.generation() == count {
board
.restore(&previous)
.map_err(|e| eyre!("capture paste finished with a clipboard restore error: {e}"))?;
}
}
outcome.map_err(|e| {
if attempted {
eyre!("capture may be partially pasted: {e}")
} else {
e
}
})
}
#[cfg(test)]
mod tests;