Skip to content

armgit / herdr

Public Imported from GitHub
0

the runtime your coding agents live on

fix(windows): avoid redundant clipboard history entries (#4709)

JJ Liebigeef191430742
diff --git a/src/client/clipboard_forwarding.rs b/src/client/clipboard_forwarding.rs
index 2de5f49f5..f3ba282b2 100644
--- a/src/client/clipboard_forwarding.rs
+++ b/src/client/clipboard_forwarding.rs
@@ -11,6 +11,5 @@ pub(super) fn forward_clipboard(data: &str) -> bool {
warn!("received invalid clipboard payload from server");
return false;
};
- crate::selection::write_osc52_bytes(&bytes);
- true
+ crate::selection::write_osc52_bytes(&bytes)
}
diff --git a/src/client/tests/mod.rs b/src/client/tests/mod.rs
index 035d00d39..323af2f87 100644
--- a/src/client/tests/mod.rs
+++ b/src/client/tests/mod.rs
@@ -961,11 +961,3 @@ fn terminal_control_scroll_command_maps_to_attach_scroll() {
assert_eq!(direction, AttachScrollDirection::Up);
assert_eq!(lines, 3);
}
-
-#[test]
-fn forward_clipboard_uses_local_clipboard_path() {
- let _guard = env_lock().lock().unwrap();
- let _ssh = EnvVarGuard::set("SSH_CONNECTION", "1 2 3 4");
- assert!(forward_clipboard("dGVzdA=="));
- assert!(!forward_clipboard("not base64"));
-}
diff --git a/src/platform/fallback.rs b/src/platform/fallback.rs
index 21d13ba08..82744f5ea 100644
--- a/src/platform/fallback.rs
+++ b/src/platform/fallback.rs
@@ -235,6 +235,11 @@ pub fn read_clipboard_text() -> Option<String> {
None
}
+/// Unsupported platform stub.
+pub fn clipboard_text_matches(_bytes: &[u8]) -> Option<bool> {
+ None
+}
+
/// Unsupported platform stub.
pub fn open_url(_url: &str) -> std::io::Result<Option<std::process::Child>> {
Err(std::io::Error::new(
diff --git a/src/platform/linux.rs b/src/platform/linux.rs
index c73584e53..706a0f04a 100644
--- a/src/platform/linux.rs
+++ b/src/platform/linux.rs
@@ -795,6 +795,10 @@ pub fn read_clipboard_text() -> Option<String> {
None
}
+pub fn clipboard_text_matches(_bytes: &[u8]) -> Option<bool> {
+ None
+}
+
pub fn open_url(url: &str) -> std::io::Result<Option<std::process::Child>> {
Command::new("xdg-open")
.arg(url)
diff --git a/src/platform/macos.rs b/src/platform/macos.rs
index 8c5293428..23776d612 100644
--- a/src/platform/macos.rs
+++ b/src/platform/macos.rs
@@ -672,6 +672,10 @@ pub fn read_clipboard_text() -> Option<String> {
}
}
+pub fn clipboard_text_matches(_bytes: &[u8]) -> Option<bool> {
+ None
+}
+
pub fn open_url(url: &str) -> std::io::Result<Option<std::process::Child>> {
Command::new("open")
.arg(url)
diff --git a/src/platform/windows.rs b/src/platform/windows.rs
index 292be4a44..867701aac 100644
--- a/src/platform/windows.rs
+++ b/src/platform/windows.rs
@@ -7,7 +7,7 @@ use std::{
path::PathBuf,
ptr::{copy_nonoverlapping, null_mut},
sync::{
- atomic::{AtomicU64, Ordering as AtomicOrdering},
+ atomic::{AtomicU32, AtomicU64, Ordering as AtomicOrdering},
Arc, LazyLock, Mutex, OnceLock,
},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
@@ -329,7 +329,8 @@ use windows_sys::{
System::{
Console::GetConsoleWindow,
DataExchange::{
- CloseClipboard, EmptyClipboard, GetClipboardData, OpenClipboard,
+ CloseClipboard, CountClipboardFormats, EmptyClipboard, EnumClipboardFormats,
+ GetClipboardData, GetClipboardOwner, GetClipboardSequenceNumber, OpenClipboard,
RegisterClipboardFormatW, SetClipboardData,
},
Diagnostics::{
@@ -350,7 +351,7 @@ use windows_sys::{
GlobalAlloc, GlobalLock, GlobalSize, GlobalUnlock, VirtualQueryEx, GMEM_MOVEABLE,
MEMORY_BASIC_INFORMATION,
},
- Ole::{CF_DIB, CF_DIBV5, CF_UNICODETEXT},
+ Ole::{CF_DIB, CF_DIBV5, CF_LOCALE, CF_OEMTEXT, CF_TEXT, CF_UNICODETEXT},
Threading::{
GetCurrentProcess, GetExitCodeProcess, GetProcessTimes, IsWow64Process2,
OpenProcess, OpenThread, QueryFullProcessImageNameW, ResumeThread,
@@ -2355,6 +2356,8 @@ pub fn process_exists(pid: u32) -> bool {
ok && exit_code == STILL_ACTIVE
}
+static LAST_CLIPBOARD_WRITE_SEQUENCE: AtomicU32 = AtomicU32::new(0);
+
pub fn write_clipboard(bytes: &[u8]) -> bool {
let Ok(text) = std::str::from_utf8(bytes) else {
return false;
@@ -2397,6 +2400,16 @@ pub fn write_clipboard(bytes: &[u8]) -> bool {
return false;
}
+ // Closing may generate additional text formats and advance the sequence.
+ drop(_clipboard);
+ // Read the sequence first: a later writer must not become our last write.
+ let sequence = GetClipboardSequenceNumber();
+ let sequence = if GetClipboardOwner() == owner {
+ sequence
+ } else {
+ 0
+ };
+ LAST_CLIPBOARD_WRITE_SEQUENCE.store(sequence, AtomicOrdering::Relaxed);
true
}
}
@@ -2405,6 +2418,76 @@ pub fn read_clipboard_text() -> Option<String> {
None
}
+/// Whether the system clipboard currently holds exactly this text.
+///
+/// Returns `None` when the clipboard changed since our last write, cannot be read,
+/// or has non-text formats.
+/// Kept separate from [`read_clipboard_text`] so unsupported modal paste on
+/// Windows is unchanged.
+pub fn clipboard_text_matches(bytes: &[u8]) -> Option<bool> {
+ let current = read_clipboard_unicode_text()?;
+ Some(clipboard_text_equals(&current, bytes))
+}
+
+fn clipboard_text_equals(current: &str, bytes: &[u8]) -> bool {
+ let Ok(payload) = std::str::from_utf8(bytes) else {
+ return false;
+ };
+ normalized_clipboard_newlines(payload) == normalized_clipboard_newlines(current)
+}
+
+fn normalized_clipboard_newlines(text: &str) -> std::borrow::Cow<'_, str> {
+ if text.contains("\r\n") {
+ std::borrow::Cow::Owned(text.replace("\r\n", "\n"))
+ } else {
+ std::borrow::Cow::Borrowed(text)
+ }
+}
+
+fn plain_text_clipboard_format(format: u32) -> bool {
+ format == CF_UNICODETEXT as u32
+ || format == CF_TEXT as u32
+ || format == CF_OEMTEXT as u32
+ || format == CF_LOCALE as u32
+}
+
+fn read_clipboard_unicode_text() -> Option<String> {
+ const MAX_CLIPBOARD_TEXT_BYTES: usize = 1024 * 1024;
+
+ for attempt in 0..10 {
+ if unsafe { OpenClipboard(null_mut()) } != 0 {
+ let _clipboard = ClipboardGuard;
+ let sequence = unsafe { GetClipboardSequenceNumber() };
+ if sequence == 0
+ || sequence != LAST_CLIPBOARD_WRITE_SEQUENCE.load(AtomicOrdering::Relaxed)
+ {
+ return None;
+ }
+ let format_count = unsafe { CountClipboardFormats() };
+ if format_count <= 0 {
+ return None;
+ }
+ let mut format = 0;
+ for _ in 0..format_count {
+ format = unsafe { EnumClipboardFormats(format) };
+ if format == 0 || !plain_text_clipboard_format(format) {
+ return None;
+ }
+ }
+ let bytes = clipboard_global_bytes(CF_UNICODETEXT as u32, MAX_CLIPBOARD_TEXT_BYTES)?;
+ let units = bytes
+ .chunks_exact(2)
+ .map(|pair| u16::from_ne_bytes([pair[0], pair[1]]))
+ .take_while(|unit| *unit != 0);
+ return String::from_utf16(&units.collect::<Vec<_>>()).ok();
+ }
+ if attempt < 9 {
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ }
+ None
+}
+
pub fn open_url(url: &str) -> std::io::Result<Option<std::process::Child>> {
let operation = wide_null("open");
let url = wide_null(url);
@@ -3037,6 +3120,31 @@ mod tests {
AllocConsole, FreeConsole, GetConsoleProcessList, GetConsoleWindow,
};
+ #[test]
+ fn clipboard_text_equals_normalizes_line_endings() {
+ assert!(super::clipboard_text_equals("hello", b"hello"));
+ assert!(super::clipboard_text_equals("a\r\nb", b"a\nb"));
+ assert!(super::clipboard_text_equals("a\nb", b"a\r\nb"));
+ assert!(!super::clipboard_text_equals("hello ", b"hello"));
+ assert!(!super::clipboard_text_equals("hello", b"world"));
+ assert!(!super::clipboard_text_equals("hello", &[0xff]));
+ assert!(!super::clipboard_text_equals("a\rb", b"a\nb"));
+ }
+
+ #[test]
+ fn clipboard_format_check_rejects_rich_content() {
+ for format in [
+ super::CF_UNICODETEXT,
+ super::CF_TEXT,
+ super::CF_OEMTEXT,
+ super::CF_LOCALE,
+ ] {
+ assert!(super::plain_text_clipboard_format(format as u32));
+ }
+ assert!(!super::plain_text_clipboard_format(super::CF_DIB as u32));
+ assert!(!super::plain_text_clipboard_format(0xC000));
+ }
+
#[test]
fn windows_standard_plugin_runtime_paths_drop_only_disk_and_unc_verbatim_prefixes() {
assert_eq!(
diff --git a/src/selection.rs b/src/selection.rs
index 5f81fdcd8..9b47b2e06 100644
--- a/src/selection.rs
+++ b/src/selection.rs
@@ -358,14 +358,22 @@ fn should_prefer_osc52() -> bool {
///
/// Some terminals still only honor BEL-terminated OSC 52 writes, so herdr
/// emits BEL here even though ST works in newer emulators.
-pub fn write_osc52_bytes(bytes: &[u8]) {
- if !should_prefer_osc52() && crate::platform::write_clipboard(bytes) {
- return;
+///
+/// Returns false when the clipboard already holds the same text or output fails.
+pub fn write_osc52_bytes(bytes: &[u8]) -> bool {
+ let prefer_osc52 = should_prefer_osc52();
+ if !prefer_osc52 && crate::platform::clipboard_text_matches(bytes) == Some(true) {
+ tracing::debug!(bytes = bytes.len(), "suppressed duplicate clipboard write");
+ return false;
}
- let sequence = osc52_sequence(bytes);
- let _ = std::io::stdout().write_all(sequence.as_bytes());
- let _ = std::io::stdout().flush();
+ if !prefer_osc52 && crate::platform::write_clipboard(bytes) {
+ true
+ } else {
+ let sequence = osc52_sequence(bytes);
+ let mut stdout = std::io::stdout();
+ stdout.write_all(sequence.as_bytes()).is_ok() && stdout.flush().is_ok()
+ }
}
#[cfg(test)]