返回 CodeWhale
clipboard.rs
根目录 / crates / tui / src / tui / clipboard.rs
1 //! Clipboard handling for paste support in TUI
2 //!
3 //! Supports text and image paste operations. Images on the clipboard are
4 //! encoded as PNG and persisted under `~/.codewhale/clipboard-images/` so the
5 //! model can reach them via the existing `@`-mention / file tools (DeepSeek
6 //! V4 does not currently accept inline image input on its Chat Completions
7 //! endpoint, so we materialize the bytes to disk instead of base64-embedding
8 //! them in the request).
9 //!
10 //! OpenHarmony deliberately excludes native desktop/Wayland clipboard APIs.
11 //! Copy falls back to OSC 52 (or tmux `load-buffer -w`), paste arrives through
12 //! terminal input, and image clipboard reads are unavailable.
13
14 #[cfg(all(target_os = "linux", not(target_env = "ohos"), not(test)))]
15 mod primary;
16
17 use std::ffi::OsStr;
18 #[cfg(any(not(test), all(test, unix)))]
19 use std::io::Write;
20 #[cfg(not(test))]
21 use std::io::{self, IsTerminal};
22 use std::path::{Path, PathBuf};
23 #[cfg(any(not(test), all(test, unix)))]
24 use std::process::{Command, Stdio};
25 #[cfg(any(
26 target_os = "macos",
27 target_os = "windows",
28 all(target_os = "linux", not(target_env = "ohos"))
29 ))]
30 use std::time::{SystemTime, UNIX_EPOCH};
31
32 use anyhow::{Context, Result, bail};
33 #[cfg(all(
34 not(test),
35 any(
36 target_os = "macos",
37 target_os = "windows",
38 all(target_os = "linux", not(target_env = "ohos"))
39 )
40 ))]
41 use arboard::Clipboard;
42 #[cfg(any(
43 target_os = "macos",
44 target_os = "windows",
45 all(target_os = "linux", not(target_env = "ohos"))
46 ))]
47 use arboard::ImageData;
48 use base64::Engine as _;
49 #[cfg(any(
50 target_os = "macos",
51 target_os = "windows",
52 all(target_os = "linux", not(target_env = "ohos"))
53 ))]
54 use image::{ImageBuffer, Rgba};
55
56 const OSC52_MAX_BYTES: usize = 100 * 1024;
57 const PRIMARY_MAX_BYTES: usize = 1024 * 1024;
58 #[cfg(any(
59 test,
60 target_os = "macos",
61 target_os = "windows",
62 all(target_os = "linux", not(target_env = "ohos"))
63 ))]
64 const MAX_CLIPBOARD_HTML_BYTES: usize = 1024 * 1024;
65 #[cfg(any(
66 test,
67 target_os = "macos",
68 target_os = "windows",
69 all(target_os = "linux", not(target_env = "ohos"))
70 ))]
71 const MAX_CLIPBOARD_TEXT_BYTES: usize = 16 * 1024 * 1024;
72 #[cfg(any(all(test, unix), all(target_os = "linux", not(target_env = "ohos"))))]
73 const WAYLAND_CLIPBOARD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
74 #[cfg(any(all(test, unix), all(target_os = "linux", not(target_env = "ohos"))))]
75 const WL_PASTE_MAX_BYTES: u64 = MAX_CLIPBOARD_TEXT_BYTES as u64;
76 #[cfg(any(not(test), all(test, unix)))]
77 const TMUX_CLIPBOARD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
78 #[cfg(any(not(test), all(test, unix)))]
79 const TMUX_STDERR_MAX_BYTES: u64 = 64 * 1024;
80
81 /// Convert rich clipboard content without loading its linked resources. Keep
82 /// the plain representation as a lossless fallback for empty/oversized HTML.
83 #[cfg(any(
84 test,
85 target_os = "macos",
86 target_os = "windows",
87 all(target_os = "linux", not(target_env = "ohos"))
88 ))]
89 fn clipboard_markdown(html: &str) -> Option<String> {
90 if html.len() > MAX_CLIPBOARD_HTML_BYTES {
91 return None;
92 }
93 let mut markdown = htmd::HtmlToMarkdown::builder()
94 .options(htmd::options::Options {
95 preformatted_code: true,
96 ..Default::default()
97 })
98 .skip_tags(vec!["script", "style", "head", "iframe", "object"])
99 .build()
100 .convert(html)
101 .ok()?;
102 // A standalone H1 must not become the `# note` memory shortcut. Setext
103 // is equivalent Markdown and remains multi-line after composer trimming.
104 if let Some(heading) = markdown.trim().strip_prefix("# ")
105 && !heading.contains('\n')
106 {
107 markdown = format!("{heading}\n===");
108 }
109 (!markdown.trim().is_empty() && markdown.len() <= MAX_CLIPBOARD_HTML_BYTES).then_some(markdown)
110 }
111
112 #[cfg(any(
113 test,
114 target_os = "macos",
115 target_os = "windows",
116 all(target_os = "linux", not(target_env = "ohos"))
117 ))]
118 fn admit_clipboard_text(text: String) -> Result<String> {
119 if text.len() > MAX_CLIPBOARD_TEXT_BYTES {
120 bail!(
121 "clipboard text is {} bytes, over the {MAX_CLIPBOARD_TEXT_BYTES}-byte limit",
122 text.len()
123 );
124 }
125 Ok(text)
126 }
127
128 #[cfg(any(
129 target_os = "macos",
130 target_os = "windows",
131 all(target_os = "linux", not(target_env = "ohos"))
132 ))]
133 enum NativeClipboardOutcome {
134 Content(ClipboardContent),
135 Rejected,
136 NoImage,
137 }
138
139 #[cfg(any(
140 target_os = "macos",
141 target_os = "windows",
142 all(target_os = "linux", not(target_env = "ohos"))
143 ))]
144 fn resolve_native_clipboard_read<'a, B>(
145 backend: &mut B,
146 prefer_markdown: bool,
147 read_html: impl FnOnce(&mut B) -> Option<String>,
148 read_text: impl FnOnce(&mut B) -> Option<String>,
149 read_image: impl FnOnce(&mut B) -> std::result::Result<ImageData<'a>, String>,
150 save_image: impl FnOnce(&ImageData<'a>) -> Result<PastedImage>,
151 ) -> NativeClipboardOutcome {
152 if prefer_markdown
153 && let Some(html) = read_html(backend)
154 && let Some(markdown) = clipboard_markdown(&html)
155 {
156 return NativeClipboardOutcome::Content(ClipboardContent::Text(markdown));
157 }
158 if let Some(text) = read_text(backend) {
159 return match admit_clipboard_text(text) {
160 Ok(text) => NativeClipboardOutcome::Content(ClipboardContent::Text(text)),
161 Err(error) => {
162 tracing::warn!(
163 target: "codewhale_tui::clipboard",
164 "read: {error}"
165 );
166 NativeClipboardOutcome::Rejected
167 }
168 };
169 }
170 match read_image(backend) {
171 Ok(image) => match save_image(&image) {
172 Ok(pasted) => NativeClipboardOutcome::Content(ClipboardContent::Image(pasted)),
173 Err(error) => {
174 tracing::warn!(
175 target: "codewhale_tui::clipboard",
176 "read: saving the clipboard image failed: {error:#}"
177 );
178 NativeClipboardOutcome::Rejected
179 }
180 },
181 Err(error) => {
182 tracing::warn!(
183 target: "codewhale_tui::clipboard",
184 "read: clipboard has no readable image: {error}"
185 );
186 NativeClipboardOutcome::NoImage
187 }
188 }
189 }
190
191 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
192 enum ClipboardEndpoint {
193 /// The TUI and desktop clipboard live on the same host.
194 NativeHost,
195 /// SSH exported a graphical display (X11 or Wayland), so the native
196 /// clipboard intentionally addresses that forwarded display.
197 ForwardedDisplay,
198 /// No graphical endpoint is available over SSH. Clipboard transfer must
199 /// be requested from the terminal client instead.
200 TerminalClient,
201 }
202
203 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
204 enum ClipboardWriteOrder {
205 /// An SSH TUI without an exported graphical display must target the
206 /// terminal client. A native clipboard on the remote host can succeed
207 /// while writing to the wrong machine.
208 TerminalClientOnly,
209 /// A local TUI should prefer the native clipboard (including images) and
210 /// retain OSC 52 as the terminal fallback.
211 NativeHostThenTerminal,
212 }
213
214 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
215 struct TerminalClipboardContext {
216 endpoint: ClipboardEndpoint,
217 in_tmux: bool,
218 }
219
220 impl TerminalClipboardContext {
221 fn detect() -> Self {
222 let ssh_client = std::env::var_os("SSH_CLIENT");
223 let ssh_connection = std::env::var_os("SSH_CONNECTION");
224 let ssh_tty = std::env::var_os("SSH_TTY");
225 let display = std::env::var_os("DISPLAY");
226 let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
227 let ssh_clipboard = std::env::var_os("CODEWHALE_SSH_CLIPBOARD");
228 let tmux = std::env::var_os("TMUX");
229 Self::from_env_values(
230 ssh_client.as_deref(),
231 ssh_connection.as_deref(),
232 ssh_tty.as_deref(),
233 display.as_deref(),
234 wayland_display.as_deref(),
235 ssh_clipboard.as_deref(),
236 tmux.as_deref(),
237 )
238 }
239
240 fn from_env_values(
241 ssh_client: Option<&OsStr>,
242 ssh_connection: Option<&OsStr>,
243 ssh_tty: Option<&OsStr>,
244 display: Option<&OsStr>,
245 wayland_display: Option<&OsStr>,
246 ssh_clipboard: Option<&OsStr>,
247 tmux: Option<&OsStr>,
248 ) -> Self {
249 let in_ssh_session = [ssh_client, ssh_connection, ssh_tty]
250 .into_iter()
251 .flatten()
252 .any(|value| !value.is_empty());
253 let has_graphical_display = [display, wayland_display]
254 .into_iter()
255 .flatten()
256 .any(|value| !value.is_empty());
257 let forwarded_x11 = display.and_then(OsStr::to_str).is_some_and(|value| {
258 ["localhost:", "127.0.0.1:", "[::1]:", "::1:"]
259 .iter()
260 .any(|prefix| value.starts_with(prefix))
261 });
262 let use_graphical_display = match ssh_clipboard.and_then(OsStr::to_str) {
263 Some("graphical") => has_graphical_display,
264 Some("terminal") => false,
265 _ => forwarded_x11,
266 };
267
268 Self {
269 // OpenSSH normally exports SSH_CLIENT and SSH_CONNECTION.
270 // SSH_TTY is an additional PTY-only marker and is independently
271 // sufficient when wrappers preserve it without the other two.
272 endpoint: match (in_ssh_session, use_graphical_display) {
273 (false, _) => ClipboardEndpoint::NativeHost,
274 (true, true) => ClipboardEndpoint::ForwardedDisplay,
275 (true, false) => ClipboardEndpoint::TerminalClient,
276 },
277 in_tmux: tmux.is_some_and(|value| !value.is_empty()),
278 }
279 }
280
281 fn write_order(self) -> ClipboardWriteOrder {
282 if self.endpoint == ClipboardEndpoint::TerminalClient {
283 ClipboardWriteOrder::TerminalClientOnly
284 } else {
285 ClipboardWriteOrder::NativeHostThenTerminal
286 }
287 }
288
289 fn permits_native_read(self) -> bool {
290 self.endpoint != ClipboardEndpoint::TerminalClient
291 }
292
293 fn requires_terminal_paste(self) -> bool {
294 self.endpoint == ClipboardEndpoint::TerminalClient
295 }
296 }
297
298 // === Types ===
299
300 /// Metadata captured for a pasted clipboard image. Used by the composer to
301 /// render a status hint like `Pasted 1024x768 image (235KB) → <path>`.
302 #[derive(Clone, Debug)]
303 pub struct PastedImage {
304 pub path: PathBuf,
305 pub width: u32,
306 pub height: u32,
307 pub byte_len: usize,
308 }
309
310 impl PastedImage {
311 /// Short human-readable summary, e.g. `1024x768 PNG`.
312 pub fn short_label(&self) -> String {
313 format!("{}x{} PNG", self.width, self.height)
314 }
315
316 /// Approximate file size suffix, e.g. `235KB`.
317 pub fn size_label(&self) -> String {
318 let kb = (self.byte_len as f64 / 1024.0).round() as u64;
319 format!("{kb}KB")
320 }
321 }
322
323 /// Clipboard payloads supported by the TUI.
324 #[cfg_attr(
325 all(
326 not(test),
327 not(any(
328 target_os = "macos",
329 target_os = "windows",
330 all(target_os = "linux", not(target_env = "ohos"))
331 ))
332 ),
333 allow(dead_code)
334 )]
335 #[derive(Clone)]
336 pub enum ClipboardContent {
337 Text(String),
338 Image(PastedImage),
339 }
340
341 /// A clipboard read: answered at once (a test double, or no readable
342 /// endpoint) or still running on the reader thread.
343 pub(crate) enum ClipboardRead {
344 Ready(Option<ClipboardContent>),
345 Pending(std::sync::mpsc::Receiver<Option<ClipboardContent>>),
346 }
347
348 struct TerminalClipboardWriteRequest {
349 text: String,
350 in_tmux: bool,
351 }
352
353 type TerminalClipboardWriteCompletion = std::result::Result<(), String>;
354
355 /// Serializes terminal-client clipboard writes on a bounded background lane.
356 ///
357 /// OSC 52 ultimately writes to the terminal output stream, which can block
358 /// indefinitely under backpressure. tmux transport can likewise wait on a
359 /// stalled server. Keeping both operations on this worker means copy actions
360 /// never park the TUI input/render loop, while the single request slot bounds
361 /// memory and preserves copy order.
362 struct TerminalClipboardWriter {
363 request_tx: std::sync::mpsc::SyncSender<TerminalClipboardWriteRequest>,
364 completion_rx: std::sync::mpsc::Receiver<TerminalClipboardWriteCompletion>,
365 }
366
367 impl TerminalClipboardWriter {
368 #[cfg(not(test))]
369 fn spawn() -> Result<Self> {
370 Self::spawn_with(|request| write_text_to_terminal_client(&request.text, request.in_tmux))
371 }
372
373 fn spawn_with<F>(write: F) -> Result<Self>
374 where
375 F: Fn(TerminalClipboardWriteRequest) -> Result<()> + Send + 'static,
376 {
377 let (request_tx, request_rx) = std::sync::mpsc::sync_channel(1);
378 let (completion_tx, completion_rx) = std::sync::mpsc::channel();
379 std::thread::Builder::new()
380 .name("terminal-clipboard-writer".to_string())
381 .spawn(move || {
382 while let Ok(request) = request_rx.recv() {
383 let completion = write(request).map_err(|err| format!("{err:#}"));
384 if completion_tx.send(completion).is_err() {
385 break;
386 }
387 }
388 })
389 .context("spawn terminal clipboard writer")?;
390 Ok(Self {
391 request_tx,
392 completion_rx,
393 })
394 }
395
396 fn enqueue(&self, text: &str, in_tmux: bool) -> Result<()> {
397 let request = TerminalClipboardWriteRequest {
398 text: text.to_string(),
399 in_tmux,
400 };
401 self.request_tx.try_send(request).map_err(|err| match err {
402 std::sync::mpsc::TrySendError::Full(_) => {
403 anyhow::anyhow!("another terminal clipboard write is still queued")
404 }
405 std::sync::mpsc::TrySendError::Disconnected(_) => {
406 anyhow::anyhow!("terminal clipboard writer stopped")
407 }
408 })
409 }
410
411 fn poll_completion(&self) -> Option<TerminalClipboardWriteCompletion> {
412 self.completion_rx.try_recv().ok()
413 }
414 }
415
416 /// Which transport took a clipboard write.
417 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
418 pub enum CopyTransport {
419 /// A native clipboard accepted the text before the write returned.
420 /// Targets with no native clipboard (e.g. OpenHarmony) never build it.
421 #[cfg_attr(
422 all(
423 not(test),
424 not(any(
425 target_os = "macos",
426 target_os = "windows",
427 all(target_os = "linux", not(target_env = "ohos"))
428 ))
429 ),
430 allow(dead_code)
431 )]
432 Native,
433 /// Handed to the terminal (OSC 52, or tmux's buffer). Terminals never
434 /// acknowledge these, so success cannot be confirmed; a failure surfaces
435 /// later through `poll_write_completion`.
436 Terminal,
437 }
438
439 /// Clipboard reader/writer helper.
440 pub struct ClipboardHandler {
441 terminal_context: TerminalClipboardContext,
442 terminal_writer: Option<TerminalClipboardWriter>,
443 #[cfg(all(target_os = "linux", not(target_env = "ohos"), not(test)))]
444 primary: Option<primary::PrimarySelection>,
445 #[cfg(test)]
446 primary_enabled: bool,
447 #[cfg(test)]
448 primary_text: Option<String>,
449 #[cfg(all(
450 not(test),
451 any(
452 target_os = "macos",
453 target_os = "windows",
454 all(target_os = "linux", not(target_env = "ohos"))
455 )
456 ))]
457 clipboard: Option<Clipboard>,
458 #[cfg(all(
459 not(test),
460 any(
461 target_os = "macos",
462 target_os = "windows",
463 all(target_os = "linux", not(target_env = "ohos"))
464 )
465 ))]
466 clipboard_init_attempted: bool,
467 #[cfg(all(
468 not(test),
469 any(
470 target_os = "macos",
471 target_os = "windows",
472 all(target_os = "linux", not(target_env = "ohos"))
473 )
474 ))]
475 clipboard_init_pending: Option<std::sync::mpsc::Receiver<Option<Clipboard>>>,
476 #[cfg(test)]
477 written_text: Vec<String>,
478 #[cfg(test)]
479 fail_text_writes: bool,
480 /// A deterministic clipboard answer for tests; `None` means the host
481 /// clipboard answers, which tests must never touch.
482 #[cfg(test)]
483 clipboard_content: Option<ClipboardContent>,
484 /// A read that answers when the test sends on the paired sender.
485 #[cfg(test)]
486 pending_read: Option<std::sync::mpsc::Receiver<Option<ClipboardContent>>>,
487 }
488
489 impl ClipboardHandler {
490 /// Create a new clipboard handler without connecting.
491 ///
492 /// The actual clipboard connection is deferred to first use
493 /// (`ensure_clipboard`) so that startup on hosts without an X11/Wayland
494 /// server (headless, WSL2) never blocks the TUI event loop.
495 pub fn new() -> Self {
496 Self::with_terminal_context(TerminalClipboardContext::detect())
497 }
498
499 fn with_terminal_context(terminal_context: TerminalClipboardContext) -> Self {
500 Self {
501 terminal_context,
502 terminal_writer: None,
503 #[cfg(all(target_os = "linux", not(target_env = "ohos"), not(test)))]
504 primary: None,
505 #[cfg(test)]
506 primary_enabled: false,
507 #[cfg(test)]
508 primary_text: None,
509 #[cfg(all(
510 not(test),
511 any(
512 target_os = "macos",
513 target_os = "windows",
514 all(target_os = "linux", not(target_env = "ohos"))
515 )
516 ))]
517 clipboard: None,
518 #[cfg(all(
519 not(test),
520 any(
521 target_os = "macos",
522 target_os = "windows",
523 all(target_os = "linux", not(target_env = "ohos"))
524 )
525 ))]
526 clipboard_init_attempted: false,
527 #[cfg(all(
528 not(test),
529 any(
530 target_os = "macos",
531 target_os = "windows",
532 all(target_os = "linux", not(target_env = "ohos"))
533 )
534 ))]
535 clipboard_init_pending: None,
536 #[cfg(test)]
537 written_text: Vec::new(),
538 #[cfg(test)]
539 fail_text_writes: false,
540 #[cfg(test)]
541 clipboard_content: None,
542 #[cfg(test)]
543 pending_read: None,
544 }
545 }
546
547 #[cfg(test)]
548 pub(crate) fn for_test(in_ssh_session: bool, in_tmux: bool) -> Self {
549 Self::with_terminal_context(TerminalClipboardContext {
550 endpoint: if in_ssh_session {
551 ClipboardEndpoint::TerminalClient
552 } else {
553 ClipboardEndpoint::NativeHost
554 },
555 in_tmux,
556 })
557 }
558
559 /// A clipboard whose writes go to the terminal (OSC 52) and always
560 /// succeed, for receipt tests.
561 #[cfg(test)]
562 pub(crate) fn terminal_only_for_test() -> Self {
563 let mut handler = Self::for_test(true, false);
564 handler.terminal_writer =
565 Some(TerminalClipboardWriter::spawn_with(|_| Ok(())).expect("terminal writer"));
566 handler
567 }
568
569 /// Construct a deterministic unavailable clipboard for command tests.
570 /// A clipboard whose read answers `content` exactly, for tests that must
571 /// not touch the host clipboard.
572 #[cfg(test)]
573 pub(crate) fn with_content_for_test(content: ClipboardContent) -> Self {
574 let mut handler = Self::for_test(false, false);
575 handler.clipboard_content = Some(content);
576 handler
577 }
578
579 /// A clipboard whose next read is still running until the returned
580 /// sender answers it.
581 #[cfg(test)]
582 pub(crate) fn with_pending_read_for_test()
583 -> (Self, std::sync::mpsc::Sender<Option<ClipboardContent>>) {
584 let mut handler = Self::for_test(false, false);
585 let (tx, rx) = std::sync::mpsc::channel();
586 handler.pending_read = Some(rx);
587 (handler, tx)
588 }
589
590 #[cfg(test)]
591 pub(crate) fn unavailable_for_test(in_ssh_session: bool) -> Self {
592 let mut handler = Self::for_test(in_ssh_session, false);
593 handler.fail_text_writes = true;
594 handler
595 }
596
597 /// SSH without a forwarded graphical display cannot synchronously read
598 /// the terminal client's clipboard. Paste must be initiated by the local
599 /// terminal so it arrives as bracketed paste (or a raw paste burst on
600 /// older terminals).
601 pub(crate) fn requires_terminal_paste(&self) -> bool {
602 self.terminal_context.requires_terminal_paste()
603 }
604
605 pub(crate) fn uses_primary_selection(&self) -> bool {
606 #[cfg(test)]
607 {
608 self.primary_enabled
609 }
610 #[cfg(not(test))]
611 {
612 cfg!(all(target_os = "linux", not(target_env = "ohos")))
613 }
614 }
615
616 /// Automatic selection never writes CLIPBOARD or sends OSC 52. A remote
617 /// terminal without a forwarded display owns its own selection and paste.
618 pub(crate) fn write_primary_text(&mut self, text: &str) -> Result<()> {
619 if !self.uses_primary_selection()
620 || !self.terminal_context.permits_native_read()
621 || text.is_empty()
622 || text.len() > PRIMARY_MAX_BYTES
623 {
624 bail!("PRIMARY selection unavailable");
625 }
626 #[cfg(test)]
627 {
628 if self.fail_text_writes {
629 bail!("test PRIMARY unavailable");
630 }
631 self.primary_text = Some(text.to_string());
632 Ok(())
633 }
634 #[cfg(all(target_os = "linux", not(target_env = "ohos"), not(test)))]
635 {
636 self.primary_selection()?.write(text)
637 }
638 #[cfg(all(not(test), not(all(target_os = "linux", not(target_env = "ohos")))))]
639 {
640 bail!("PRIMARY selection unavailable")
641 }
642 }
643
644 pub(crate) fn read_primary_text(&mut self) -> Option<String> {
645 if !self.uses_primary_selection() || !self.terminal_context.permits_native_read() {
646 return None;
647 }
648 #[cfg(test)]
649 {
650 if self.fail_text_writes {
651 None
652 } else {
653 self.primary_text.clone()
654 }
655 }
656 #[cfg(all(target_os = "linux", not(target_env = "ohos"), not(test)))]
657 {
658 self.primary_selection().ok()?.read()
659 }
660 #[cfg(all(not(test), not(all(target_os = "linux", not(target_env = "ohos")))))]
661 {
662 None
663 }
664 }
665
666 #[cfg(all(target_os = "linux", not(target_env = "ohos"), not(test)))]
667 fn primary_selection(&mut self) -> Result<&primary::PrimarySelection> {
668 if self.primary.is_none() {
669 self.primary = Some(primary::PrimarySelection::spawn()?);
670 }
671 Ok(self.primary.as_ref().expect("PRIMARY worker initialized"))
672 }
673
674 #[cfg(test)]
675 pub(crate) fn enable_primary_for_test(&mut self) {
676 self.primary_enabled = true;
677 }
678
679 /// Try to connect to the system clipboard, bounded by a short timeout.
680 ///
681 /// On Linux, `arboard::Clipboard::new()` opens a blocking X11 connection.
682 /// When no X server is running (headless, WSL2 without WSLg), the connect
683 /// call can hang indefinitely. We spawn the connection attempt on a
684 /// temporary thread and give it 500 ms; if it doesn't return in time the
685 /// handler stays in fallback/no-op mode and `read`/`write_text` fall
686 /// through to their OSC 52 and pbcopy/powershell fallbacks.
687 #[cfg(all(
688 not(test),
689 any(
690 target_os = "macos",
691 target_os = "windows",
692 all(target_os = "linux", not(target_env = "ohos"))
693 )
694 ))]
695 fn ensure_clipboard(&mut self) {
696 // `clipboard_init_attempted` means the backend answered for good:
697 // either it opened, or it refused. A timeout does not set it, so the
698 // next paste retries instead of staying dead for the session.
699 if self.clipboard.is_some() || self.clipboard_init_attempted {
700 return;
701 }
702
703 let rx = self.clipboard_init_pending.take().unwrap_or_else(|| {
704 let (tx, rx) = std::sync::mpsc::channel();
705 std::thread::spawn(move || {
706 let _ = tx.send(Clipboard::new().ok());
707 });
708 rx
709 });
710 // A timeout is not proof that the clipboard is unusable: a capture tool
711 // holding the clipboard open can delay the open past the budget, and
712 // the old code latched that into "never try again" for the rest of the
713 // session, so the next paste silently read nothing. Retry on timeout;
714 // a real failure (the backend said no) is still remembered.
715 match rx.recv_timeout(std::time::Duration::from_secs(2)) {
716 Ok(Some(clipboard)) => {
717 self.clipboard = Some(clipboard);
718 self.clipboard_init_attempted = true;
719 }
720 Ok(None) => self.clipboard_init_attempted = true,
721 Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
722 self.clipboard_init_pending = Some(rx);
723 tracing::warn!(
724 target: "codewhale_tui::clipboard",
725 "clipboard open timed out; will retry on the next paste"
726 );
727 }
728 Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
729 self.clipboard_init_attempted = true;
730 }
731 }
732 }
733
734 /// Start a clipboard read without waiting on it.
735 ///
736 /// `wl-paste`, the native backend's first open and Windows' PowerShell
737 /// image fallback can each take seconds, so the read runs on its own
738 /// thread with its own backend handle and the caller polls the receiver.
739 /// `prefer_markdown` turns rich HTML into Markdown for the composer;
740 /// credentials and configuration fields read literal text.
741 ///
742 /// `workspace` is used as a fallback location when `~/.codewhale/` cannot
743 /// be resolved (e.g. running with a stripped HOME in CI sandboxes).
744 pub(crate) fn read(&mut self, workspace: &Path, prefer_markdown: bool) -> ClipboardRead {
745 // Tests never touch the host clipboard.
746 #[cfg(test)]
747 {
748 let _ = (workspace, prefer_markdown);
749 match self.pending_read.take() {
750 Some(rx) => ClipboardRead::Pending(rx),
751 None => ClipboardRead::Ready(self.clipboard_content.clone()),
752 }
753 }
754 #[cfg(not(test))]
755 {
756 // With no display exported over SSH there is no readable clipboard
757 // endpoint. A forwarded X11/Wayland display is explicit and remains
758 // readable, including its image clipboard.
759 if !self.terminal_context.permits_native_read() {
760 return ClipboardRead::Ready(None);
761 }
762 let workspace = workspace.to_path_buf();
763 let (tx, rx) = std::sync::mpsc::channel();
764 let spawned = std::thread::Builder::new()
765 .name("clipboard-read".to_string())
766 .spawn(move || {
767 // The image writer creates `clipboard-images` but not a
768 // missing state root (e.g. CODEWHALE_HOME points elsewhere).
769 let images = codewhale_runtime::config::clipboard_images_dir(&workspace);
770 if let Some(root) = images.parent() {
771 let _ = std::fs::create_dir_all(root);
772 }
773 let _ = tx.send(read_native_clipboard(&workspace, prefer_markdown));
774 });
775 match spawned {
776 Ok(_) => ClipboardRead::Pending(rx),
777 Err(error) => {
778 tracing::warn!(
779 target: "codewhale_tui::clipboard",
780 "read: could not start the clipboard reader: {error}"
781 );
782 ClipboardRead::Ready(None)
783 }
784 }
785 }
786 }
787
788 /// Write text to the clipboard.
789 ///
790 /// Native clipboard transports complete before this method returns. OSC 52
791 /// and tmux terminal-client writes are validated and admitted to a bounded
792 /// background worker; asynchronous transport failures are exposed through
793 /// [`Self::poll_write_completion`].
794 pub fn write_text(&mut self, text: &str) -> Result<()> {
795 self.write_text_status(text).map(|_| ())
796 }
797
798 /// [`Self::write_text`], reporting which transport took the text, so a
799 /// receipt can say "copied" only when a native clipboard confirmed it.
800 /// The transport is only known here: native is tried first and OSC 52 or
801 /// tmux is the fallback.
802 pub fn write_text_status(&mut self, text: &str) -> Result<CopyTransport> {
803 #[cfg(test)]
804 {
805 if let Some(writer) = self.terminal_writer.as_ref() {
806 return writer
807 .enqueue(text, self.terminal_context.in_tmux)
808 .map(|()| CopyTransport::Terminal);
809 }
810 if self.fail_text_writes {
811 bail!("test clipboard unavailable");
812 }
813 self.written_text.push(text.to_string());
814 Ok(CopyTransport::Native)
815 }
816
817 #[cfg(not(test))]
818 {
819 if self.terminal_context.write_order() == ClipboardWriteOrder::TerminalClientOnly {
820 return self
821 .enqueue_terminal_write(text)
822 .map(|()| CopyTransport::Terminal)
823 .map_err(|err| anyhow::anyhow!("Clipboard unavailable: {err}"));
824 }
825
826 #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
827 if write_text_with_wlcopy(text).is_ok() {
828 return Ok(CopyTransport::Native);
829 }
830
831 #[cfg(any(
832 target_os = "macos",
833 target_os = "windows",
834 all(target_os = "linux", not(target_env = "ohos"))
835 ))]
836 {
837 self.ensure_clipboard();
838 if let Some(clipboard) = self.clipboard.as_mut()
839 && clipboard.set_text(text.to_string()).is_ok()
840 {
841 return Ok(CopyTransport::Native);
842 }
843 }
844
845 #[cfg(target_os = "macos")]
846 if write_text_with_pbcopy(text).is_ok() {
847 return Ok(CopyTransport::Native);
848 }
849
850 #[cfg(target_os = "windows")]
851 if write_text_with_set_clipboard(text).is_ok() {
852 return Ok(CopyTransport::Native);
853 }
854
855 self.enqueue_terminal_write(text)
856 .map(|()| CopyTransport::Terminal)
857 .map_err(|err| anyhow::anyhow!("Clipboard unavailable: {err}"))
858 }
859 }
860
861 #[cfg(not(test))]
862 fn enqueue_terminal_write(&mut self, text: &str) -> Result<()> {
863 if !self.terminal_context.in_tmux {
864 if text.len() > OSC52_MAX_BYTES {
865 bail!("selection is too large for OSC 52 clipboard fallback");
866 }
867 if !io::stdout().is_terminal() {
868 bail!("OSC 52 clipboard fallback requires a terminal");
869 }
870 }
871
872 if self.terminal_writer.is_none() {
873 self.terminal_writer = Some(TerminalClipboardWriter::spawn()?);
874 }
875 self.terminal_writer
876 .as_ref()
877 .expect("terminal clipboard writer initialized")
878 .enqueue(text, self.terminal_context.in_tmux)
879 }
880
881 /// Return one completed background terminal clipboard write, if available.
882 ///
883 /// Successes are intentionally quiet because callers already show their
884 /// normal copy receipt. Failures are drained by the event loop and replace
885 /// that optimistic receipt with an actionable error.
886 pub(crate) fn poll_write_completion(&self) -> Option<TerminalClipboardWriteCompletion> {
887 self.terminal_writer
888 .as_ref()
889 .and_then(TerminalClipboardWriter::poll_completion)
890 }
891
892 #[cfg(test)]
893 pub fn last_written_text(&self) -> Option<&str> {
894 self.written_text.last().map(String::as_str)
895 }
896 }
897
898 /// Blocking clipboard read; runs only on the `clipboard-read` thread.
899 #[cfg(not(test))]
900 fn read_native_clipboard(workspace: &Path, prefer_markdown: bool) -> Option<ClipboardContent> {
901 #[cfg(all(target_os = "linux", not(target_env = "ohos"), not(test)))]
902 if !prefer_markdown && let Ok(text) = read_text_with_wlpaste() {
903 return Some(ClipboardContent::Text(text));
904 }
905
906 #[cfg(any(
907 target_os = "macos",
908 target_os = "windows",
909 all(target_os = "linux", not(target_env = "ohos"))
910 ))]
911 {
912 if let Ok(mut clipboard) = Clipboard::new() {
913 match resolve_native_clipboard_read(
914 &mut clipboard,
915 prefer_markdown,
916 |clipboard| clipboard.get().html().ok(),
917 |clipboard| clipboard.get_text().ok(),
918 |clipboard| clipboard.get_image().map_err(|error| error.to_string()),
919 |image| save_image_as_png(workspace, image),
920 ) {
921 NativeClipboardOutcome::Content(content) => return Some(content),
922 NativeClipboardOutcome::Rejected => return None,
923 NativeClipboardOutcome::NoImage => {}
924 }
925 // arboard reads the Win32 clipboard through CF_DIB/CF_DIBV5.
926 // Some capture tools publish the bitmap under a format that
927 // path misses, or leave it delay-rendered in a way that only
928 // resolves once another application asks: QQ's screenshot is
929 // the reported case, where the picture becomes readable only
930 // after it has been pasted somewhere else first. .NET's
931 // Clipboard.GetImage() handles those, so ask it before
932 // deciding the clipboard holds no image.
933 #[cfg(all(target_os = "windows", not(test)))]
934 if let Some(pasted) = read_image_via_powershell(workspace) {
935 return Some(ClipboardContent::Image(pasted));
936 }
937 }
938 }
939
940 #[cfg(all(target_os = "linux", not(target_env = "ohos"), not(test)))]
941 if prefer_markdown && let Ok(text) = read_text_with_wlpaste() {
942 return Some(ClipboardContent::Text(text));
943 }
944
945 let _ = (workspace, prefer_markdown);
946 None
947 }
948
949 #[cfg(all(target_os = "macos", not(test)))]
950 fn write_text_with_pbcopy(text: &str) -> Result<()> {
951 write_text_with_stdin_command("pbcopy", &[], text, "pbcopy")
952 }
953
954 #[cfg(all(target_os = "windows", not(test)))]
955 fn write_text_with_set_clipboard(text: &str) -> Result<()> {
956 write_text_with_stdin_command(
957 "powershell.exe",
958 &["-NoProfile", "-Command", "Set-Clipboard -Value $input"],
959 text,
960 "Set-Clipboard",
961 )
962 }
963
964 #[cfg(all(any(target_os = "macos", target_os = "windows"), not(test)))]
965 fn write_text_with_stdin_command(
966 program: &str,
967 args: &[&str],
968 text: &str,
969 label: &str,
970 ) -> Result<()> {
971 let mut child = Command::new(program)
972 .args(args)
973 .stdin(Stdio::piped())
974 .stdout(Stdio::null())
975 .stderr(Stdio::null())
976 .spawn()
977 .map_err(|e| anyhow::anyhow!("Failed to run {label}: {e}"))?;
978 if let Some(mut stdin) = child.stdin.take()
979 && let Err(e) = stdin.write_all(text.as_bytes())
980 {
981 drop(stdin);
982 let _ = child.kill();
983 let _ = child.wait();
984 return Err(anyhow::anyhow!("Failed to write to {label}: {e}"));
985 }
986 let _ = std::thread::Builder::new()
987 .name("clipboard-wait".to_string())
988 .spawn(move || {
989 let _ = child.wait();
990 });
991 Ok(())
992 }
993
994 #[cfg(all(target_os = "linux", not(target_env = "ohos"), not(test)))]
995 fn write_text_with_wlcopy(text: &str) -> Result<()> {
996 write_text_with_wlcopy_using_argv("wl-copy", text)
997 }
998
999 #[cfg(all(target_os = "linux", not(target_env = "ohos"), not(test)))]
1000 fn read_text_with_wlpaste() -> Result<String> {
1001 read_text_with_wlpaste_using_argv("wl-paste")
1002 }
1003
1004 #[cfg(any(not(test), all(test, unix)))]
1005 fn wait_bounded_clipboard_child(
1006 mut child: std::process::Child,
1007 program: &str,
1008 timeout: std::time::Duration,
1009 ) -> Result<std::process::ExitStatus> {
1010 use wait_timeout::ChildExt;
1011 let waited = child.wait_timeout(timeout);
1012 if let Ok(Some(status)) = waited {
1013 return Ok(status);
1014 }
1015 let _ = child.kill();
1016 let _ = std::thread::Builder::new()
1017 .name("clipboard-wait".to_string())
1018 .spawn(move || {
1019 let _ = child.wait();
1020 });
1021 match waited {
1022 Err(e) => bail!("Failed to wait on {program}: {e}"),
1023 _ if timeout.subsec_nanos() == 0 => {
1024 bail!("{program} timed out after {}s", timeout.as_secs())
1025 }
1026 _ => bail!("{program} timed out after {}ms", timeout.as_millis()),
1027 }
1028 }
1029
1030 #[cfg(any(all(test, unix), all(target_os = "linux", not(target_env = "ohos"))))]
1031 fn wait_wayland_clipboard_child(
1032 child: std::process::Child,
1033 program: &str,
1034 ) -> Result<std::process::ExitStatus> {
1035 wait_bounded_clipboard_child(child, program, WAYLAND_CLIPBOARD_TIMEOUT)
1036 }
1037
1038 #[cfg(any(all(test, unix), all(target_os = "linux", not(target_env = "ohos"))))]
1039 fn read_text_with_wlpaste_using_argv(program: &str) -> Result<String> {
1040 use std::io::Read;
1041 let mut child = Command::new(program)
1042 .arg("--no-newline")
1043 .arg("--type")
1044 .arg("text/plain")
1045 .stdin(Stdio::null())
1046 .stdout(Stdio::piped())
1047 .stderr(Stdio::null())
1048 .spawn()
1049 .map_err(|e| anyhow::anyhow!("Failed to run {program}: {e}"))?;
1050 let stdout = child.stdout.take();
1051 let (tx, rx) = std::sync::mpsc::sync_channel(1);
1052 if let Err(error) = std::thread::Builder::new()
1053 .name("wl-paste-output".to_string())
1054 .spawn(move || {
1055 let mut bytes = Vec::new();
1056 let read = match stdout {
1057 Some(stdout) => stdout.take(WL_PASTE_MAX_BYTES + 1).read_to_end(&mut bytes),
1058 None => Ok(0),
1059 };
1060 let _ = tx.send(read.map(|_| bytes));
1061 })
1062 {
1063 let _ = child.kill();
1064 let _ = child.wait();
1065 bail!("Failed to spawn {program} output reader thread: {error}");
1066 }
1067 let status = wait_wayland_clipboard_child(child, program)?;
1068 let bytes = rx
1069 .recv_timeout(WAYLAND_CLIPBOARD_TIMEOUT)
1070 .map_err(|_| anyhow::anyhow!("{program} output did not close"))?
1071 .map_err(|e| anyhow::anyhow!("Failed to read {program} output: {e}"))?;
1072 if bytes.len() as u64 > WL_PASTE_MAX_BYTES {
1073 bail!("{program} returned more than {WL_PASTE_MAX_BYTES} bytes");
1074 }
1075 if !status.success() {
1076 bail!("{program} exited with {status}");
1077 }
1078 String::from_utf8(bytes).context("wl-paste returned non-UTF-8 text")
1079 }
1080
1081 #[cfg(all(target_os = "linux", not(target_env = "ohos"), not(test)))]
1082 fn write_text_with_wlcopy_using_argv(program: &str, text: &str) -> Result<()> {
1083 let mut child = Command::new(program)
1084 .stdin(Stdio::piped())
1085 .stdout(Stdio::null())
1086 .stderr(Stdio::null())
1087 .spawn()
1088 .map_err(|e| anyhow::anyhow!("Failed to run {program}: {e}"))?;
1089 let stdin = child.stdin.take();
1090 let text = text.to_owned();
1091 let (tx, rx) = std::sync::mpsc::sync_channel(1);
1092 if let Err(error) = std::thread::Builder::new()
1093 .name("wl-copy-input".to_string())
1094 .spawn(move || {
1095 let written = match stdin {
1096 Some(mut stdin) => stdin.write_all(text.as_bytes()),
1097 None => Ok(()),
1098 };
1099 let _ = tx.send(written);
1100 })
1101 {
1102 let _ = child.kill();
1103 let _ = child.wait();
1104 bail!("Failed to spawn {program} input writer thread: {error}");
1105 }
1106 let status = wait_wayland_clipboard_child(child, program)?;
1107 rx.recv_timeout(WAYLAND_CLIPBOARD_TIMEOUT)
1108 .map_err(|_| anyhow::anyhow!("{program} input did not close"))?
1109 .map_err(|e| anyhow::anyhow!("Failed to write to {program}: {e}"))?;
1110 if !status.success() {
1111 bail!("{program} exited with {status}");
1112 }
1113 Ok(())
1114 }
1115
1116 #[cfg(not(test))]
1117 fn write_text_to_terminal_client(text: &str, in_tmux: bool) -> Result<()> {
1118 if in_tmux {
1119 return write_text_with_tmux(text);
1120 }
1121 write_text_with_osc52(text)
1122 }
1123
1124 #[cfg(not(test))]
1125 fn write_text_with_tmux(text: &str) -> Result<()> {
1126 write_text_with_tmux_using_argv("tmux", &[], text)
1127 }
1128
1129 /// Ask tmux to set both its paste buffer and the attached client's clipboard.
1130 /// Unlike DCS passthrough, `load-buffer -w` works with tmux's default
1131 /// `allow-passthrough off` policy and returns a non-zero status when tmux
1132 /// cannot honor the command.
1133 #[cfg(any(not(test), all(test, unix)))]
1134 fn write_text_with_tmux_using_argv(program: &str, prefix_args: &[&str], text: &str) -> Result<()> {
1135 write_text_with_tmux_using_argv_with_timeout(program, prefix_args, text, TMUX_CLIPBOARD_TIMEOUT)
1136 }
1137
1138 #[cfg(any(not(test), all(test, unix)))]
1139 fn write_text_with_tmux_using_argv_with_timeout(
1140 program: &str,
1141 prefix_args: &[&str],
1142 text: &str,
1143 timeout: std::time::Duration,
1144 ) -> Result<()> {
1145 use std::io::Read as _;
1146
1147 let mut child = Command::new(program)
1148 .args(prefix_args)
1149 .args(["load-buffer", "-w", "-"])
1150 .stdin(Stdio::piped())
1151 .stdout(Stdio::null())
1152 .stderr(Stdio::piped())
1153 .spawn()
1154 .map_err(|e| anyhow::anyhow!("Failed to run tmux load-buffer -w: {e}"))?;
1155
1156 let stdin = child.stdin.take();
1157 let stderr = child.stderr.take();
1158 let payload = text.as_bytes().to_vec();
1159 let (write_tx, write_rx) = std::sync::mpsc::sync_channel(1);
1160 if let Err(error) = std::thread::Builder::new()
1161 .name("tmux-clipboard-input".to_string())
1162 .spawn(move || {
1163 let written = match stdin {
1164 Some(mut stdin) => stdin
1165 .write_all(&payload)
1166 .context("write tmux clipboard input"),
1167 None => Err(anyhow::anyhow!("open tmux clipboard input")),
1168 };
1169 let _ = write_tx.send(written);
1170 })
1171 {
1172 let _ = child.kill();
1173 let _ = child.wait();
1174 return Err(anyhow::anyhow!(
1175 "spawn tmux clipboard input writer: {error}"
1176 ));
1177 }
1178
1179 let (stderr_tx, stderr_rx) = std::sync::mpsc::sync_channel(1);
1180 if let Err(error) = std::thread::Builder::new()
1181 .name("tmux-clipboard-stderr".to_string())
1182 .spawn(move || {
1183 let mut bytes = Vec::new();
1184 if let Some(stderr) = stderr {
1185 let _ = stderr.take(TMUX_STDERR_MAX_BYTES).read_to_end(&mut bytes);
1186 }
1187 let _ = stderr_tx.send(bytes);
1188 })
1189 {
1190 let _ = child.kill();
1191 let _ = child.wait();
1192 return Err(anyhow::anyhow!(
1193 "spawn tmux clipboard stderr reader: {error}"
1194 ));
1195 }
1196
1197 let status = wait_bounded_clipboard_child(child, "tmux load-buffer -w", timeout)?;
1198 let stderr = stderr_rx.recv_timeout(timeout).unwrap_or_default();
1199 if !status.success() {
1200 let detail = String::from_utf8_lossy(&stderr);
1201 let detail = detail.trim();
1202 if detail.is_empty() {
1203 bail!("tmux load-buffer -w exited with {status}");
1204 }
1205 bail!("tmux load-buffer -w exited with {status}: {detail}");
1206 }
1207 write_rx
1208 .recv_timeout(timeout)
1209 .map_err(|_| anyhow::anyhow!("tmux load-buffer -w input did not close"))??;
1210 Ok(())
1211 }
1212
1213 #[cfg(not(test))]
1214 fn write_text_with_osc52(text: &str) -> Result<()> {
1215 let mut stdout = io::stdout();
1216 if !stdout.is_terminal() {
1217 bail!("OSC 52 clipboard fallback requires a terminal");
1218 }
1219
1220 let sequence = osc52_sequence(text)?;
1221 stdout
1222 .write_all(sequence.as_bytes())
1223 .context("write OSC 52 clipboard sequence")?;
1224 stdout.flush().context("flush OSC 52 clipboard sequence")
1225 }
1226
1227 fn osc52_sequence(text: &str) -> Result<String> {
1228 if text.len() > OSC52_MAX_BYTES {
1229 bail!("selection is too large for OSC 52 clipboard fallback");
1230 }
1231
1232 let encoded = base64::engine::general_purpose::STANDARD.encode(text.as_bytes());
1233 Ok(format!("\x1b]52;c;{encoded}\x07"))
1234 }
1235
1236 /// Pinned, no-follow writer for `dir`, which is `<root>/<name>`: `root` may be a
1237 /// user-selected link (a relocated `~/.codewhale`), but nothing below it may be.
1238 #[cfg(any(
1239 target_os = "macos",
1240 target_os = "windows",
1241 all(target_os = "linux", not(target_env = "ohos"))
1242 ))]
1243 fn clipboard_image_target(
1244 dir: &Path,
1245 file_name: &str,
1246 ) -> Result<codewhale_util::files::WorkspaceFile> {
1247 let root = dir.parent().context("clipboard-images dir has no parent")?;
1248 let name = dir
1249 .file_name()
1250 .context("clipboard-images dir has no name")?;
1251 let relative = Path::new(name).join(file_name);
1252 // `dir` sits under the user's own state root unless no home was available
1253 // and it fell back to the workspace (`clipboard_images_dir_for_home`). Only
1254 // the state root may be a link the user made to relocate `~/.codewhale`; a
1255 // caller-supplied workspace root keeps the strict rule.
1256 let state_root = codewhale_paths::user_home()
1257 .is_some_and(|home| root == home.join(codewhale_paths::CODEWHALE_APP_DIR));
1258 let open = if state_root {
1259 codewhale_util::files::WorkspaceFile::open_resolved_root
1260 } else {
1261 codewhale_util::files::WorkspaceFile::open
1262 };
1263 open(root, &relative, true)
1264 .context("open clipboard-images destination (links are not followed)")
1265 }
1266
1267 /// Encode an RGBA `ImageData` from arboard as PNG and persist it. Returns
1268 /// the resulting path along with metadata used to render the paste hint.
1269 #[cfg(all(
1270 not(test),
1271 any(
1272 target_os = "macos",
1273 target_os = "windows",
1274 all(target_os = "linux", not(target_env = "ohos"))
1275 )
1276 ))]
1277 fn save_image_as_png(workspace: &Path, image: &ImageData) -> Result<PastedImage> {
1278 save_image_as_png_in(
1279 &codewhale_runtime::config::clipboard_images_dir(workspace),
1280 image,
1281 )
1282 }
1283
1284 #[cfg(any(
1285 target_os = "macos",
1286 target_os = "windows",
1287 all(target_os = "linux", not(target_env = "ohos"))
1288 ))]
1289 const MAX_CLIPBOARD_PIXELS: u64 = codewhale_engine::image_attach::MAX_IMAGE_PIXELS;
1290
1291 #[cfg(any(
1292 target_os = "macos",
1293 target_os = "windows",
1294 all(target_os = "linux", not(target_env = "ohos"))
1295 ))]
1296 const MAX_CLIPBOARD_RGBA_BYTES: usize = (MAX_CLIPBOARD_PIXELS as usize) * 4;
1297
1298 /// Lower-level variant that writes into an explicit directory. Exposed so the
1299 /// unit tests don't have to scribble inside the user's real home directory.
1300 #[cfg(any(
1301 target_os = "macos",
1302 target_os = "windows",
1303 all(target_os = "linux", not(target_env = "ohos"))
1304 ))]
1305 fn save_image_as_png_in(dir: &Path, image: &ImageData) -> Result<PastedImage> {
1306 let timestamp = SystemTime::now()
1307 .duration_since(UNIX_EPOCH)
1308 .unwrap_or_default()
1309 .as_nanos();
1310 let width = u32::try_from(image.width).context("clipboard image width too large")?;
1311 let height = u32::try_from(image.height).context("clipboard image height too large")?;
1312 if width == 0 || height == 0 {
1313 bail!("clipboard image has empty dimensions: {width}x{height}");
1314 }
1315 // Bound the copy and the encode before they allocate: a capture tool can
1316 // publish a huge bitmap, and the RGBA copy plus the PNG encoder peak at
1317 // several times that size. The same ceiling `read_media` enforces.
1318 if u64::from(width) * u64::from(height) > MAX_CLIPBOARD_PIXELS {
1319 bail!("clipboard image is too large: {width}x{height} pixels");
1320 }
1321 if image.bytes.len() > MAX_CLIPBOARD_RGBA_BYTES {
1322 bail!(
1323 "clipboard image buffer is {} bytes, over the {MAX_CLIPBOARD_RGBA_BYTES}-byte limit",
1324 image.bytes.len()
1325 );
1326 }
1327
1328 // arboard hands us RGBA8 row-major. Copy into an ImageBuffer so we can
1329 // run it through the `image` crate's PNG encoder. We pad / truncate any
1330 // mismatched trailing bytes — defensive only, arboard already validates
1331 // the buffer length on every supported backend.
1332 let expected = (width as usize) * (height as usize) * 4;
1333 let prefix_len = image.bytes.len().min(expected);
1334 let mut rgba = Vec::with_capacity(expected);
1335 rgba.extend_from_slice(&image.bytes[..prefix_len]);
1336 if rgba.len() < expected {
1337 rgba.resize(expected, 0);
1338 }
1339
1340 let buffer: ImageBuffer<Rgba<u8>, _> = ImageBuffer::from_raw(width, height, rgba)
1341 .context("clipboard image dimensions did not match buffer length")?;
1342 // Encode in memory and publish through the pinned no-follow writer: the
1343 // destination is created exclusively and owner-only, and a linked
1344 // directory or file name is refused rather than written through.
1345 let mut encoded = Vec::new();
1346 buffer
1347 .write_to(
1348 &mut std::io::Cursor::new(&mut encoded),
1349 image::ImageFormat::Png,
1350 )
1351 .context("encode clipboard PNG")?;
1352 if encoded.len() > codewhale_engine::tools::read_media::MAX_SOURCE_IMAGE_BYTES {
1353 bail!(
1354 "encoded clipboard PNG is {} bytes, over the {}-byte limit",
1355 encoded.len(),
1356 codewhale_engine::tools::read_media::MAX_SOURCE_IMAGE_BYTES
1357 );
1358 }
1359 let file_name = format!("clipboard-{timestamp}.png");
1360 let path = dir.join(&file_name);
1361 clipboard_image_target(dir, &file_name)?
1362 .publish(&encoded)
1363 .context("write clipboard PNG")?;
1364
1365 let byte_len = encoded.len();
1366 Ok(PastedImage {
1367 path,
1368 width,
1369 height,
1370 byte_len,
1371 })
1372 }
1373
1374 /// Read the clipboard image through .NET instead of the Win32 clipboard API.
1375 ///
1376 /// Windows only, where arboard's `CF_DIB`/`CF_DIBV5` path misses pictures some
1377 /// capture tools publish under another format or leave delay-rendered. QQ's
1378 /// screenshot is the reported case: the image only becomes readable after it
1379 /// has been pasted into another application first, which is exactly what a
1380 /// second reader that asks .NET for the bitmap can bridge.
1381 ///
1382 /// Known costs: one PowerShell start, paid only after arboard already failed,
1383 /// and the PNG crosses the child's stdout as base64, so a multi-megabyte
1384 /// screenshot moves a few megabytes through the pipe.
1385 ///
1386 /// Bounds: the child is killed after [`POWERSHELL_TIMEOUT`], its stdout is cut
1387 /// at [`MAX_ENCODED_BYTES`], and reads happen on a helper thread so a child
1388 /// that fills the pipe cannot deadlock the wait. The UI thread can still block
1389 /// for that timeout; a clipboard owner that never renders the format is the
1390 /// case this guards against, and failing closed after ten seconds beats
1391 /// freezing the TUI.
1392 #[cfg(all(target_os = "windows", not(test)))]
1393 fn powershell_path() -> std::path::PathBuf {
1394 std::env::var_os("SystemRoot")
1395 .map(|root| {
1396 std::path::PathBuf::from(root)
1397 .join("System32")
1398 .join("WindowsPowerShell")
1399 .join("v1.0")
1400 .join("powershell.exe")
1401 })
1402 .unwrap_or_else(|| std::path::PathBuf::from("powershell.exe"))
1403 }
1404
1405 #[cfg(all(target_os = "windows", not(test)))]
1406 fn read_image_via_powershell(workspace: &Path) -> Option<PastedImage> {
1407 use base64::Engine as _;
1408 use std::io::Read as _;
1409 use std::time::Duration;
1410 use wait_timeout::ChildExt as _;
1411
1412 /// The script prints the PNG as base64; anything past this is beyond the
1413 /// attach limit anyway, so the read stops instead of buffering an
1414 /// unbounded stream.
1415 const MAX_ENCODED_BYTES: u64 = 16 * 1024 * 1024;
1416 /// A clipboard owner that never renders the format must not hold the UI.
1417 const POWERSHELL_TIMEOUT: Duration = Duration::from_secs(10);
1418
1419 const SCRIPT: &str = concat!(
1420 "Add-Type -AssemblyName System.Windows.Forms; ",
1421 "Add-Type -AssemblyName System.Drawing; ",
1422 "$img = [System.Windows.Forms.Clipboard]::GetImage(); ",
1423 "if ($img -ne $null) { ",
1424 "$ms = New-Object System.IO.MemoryStream; ",
1425 "$img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png); ",
1426 "[Console]::Out.Write([Convert]::ToBase64String($ms.ToArray())) }"
1427 );
1428
1429 let mut child = Command::new(powershell_path())
1430 .args(["-NoProfile", "-STA", "-Command", SCRIPT])
1431 .stdin(Stdio::null())
1432 .stdout(Stdio::piped())
1433 .stderr(Stdio::null())
1434 .spawn()
1435 .ok()?;
1436
1437 // Read on a helper thread: a child that fills the pipe would otherwise
1438 // block forever while the main thread waits for it to exit.
1439 let stdout = child.stdout.take()?;
1440 let reader = std::thread::Builder::new()
1441 .name("clipboard-powershell".to_string())
1442 .spawn(move || {
1443 let mut buffer = String::new();
1444 let _ = stdout.take(MAX_ENCODED_BYTES).read_to_string(&mut buffer);
1445 buffer
1446 })
1447 .ok()?;
1448
1449 let status = match child.wait_timeout(POWERSHELL_TIMEOUT) {
1450 Ok(Some(status)) => status,
1451 _ => {
1452 let _ = child.kill();
1453 let _ = child.wait();
1454 let _ = reader.join();
1455 return None;
1456 }
1457 };
1458 let encoded = reader.join().ok()?;
1459 if !status.success() || encoded.trim().is_empty() {
1460 return None;
1461 }
1462 let bytes = base64::engine::general_purpose::STANDARD
1463 .decode(encoded.trim())
1464 .ok()?;
1465 if bytes.is_empty() {
1466 return None;
1467 }
1468 let (width, height) = image::ImageReader::new(std::io::Cursor::new(&bytes))
1469 .with_guessed_format()
1470 .ok()?
1471 .into_dimensions()
1472 .ok()?;
1473 if width == 0
1474 || height == 0
1475 || u64::from(width) * u64::from(height) > MAX_CLIPBOARD_PIXELS
1476 || bytes.len() > codewhale_engine::tools::read_media::MAX_SOURCE_IMAGE_BYTES
1477 {
1478 return None;
1479 }
1480 let dir = codewhale_runtime::config::clipboard_images_dir(workspace);
1481 let timestamp = SystemTime::now()
1482 .duration_since(UNIX_EPOCH)
1483 .unwrap_or_default()
1484 .as_nanos();
1485 let file_name = format!("clipboard-{timestamp}.png");
1486 clipboard_image_target(&dir, &file_name)
1487 .ok()?
1488 .publish(&bytes)
1489 .ok()?;
1490 Some(PastedImage {
1491 path: dir.join(file_name),
1492 width,
1493 height,
1494 byte_len: bytes.len(),
1495 })
1496 }
1497
1498 #[cfg(test)]
1499 mod tests {
1500 use super::*;
1501
1502 #[test]
1503 fn primary_transport_is_distinct_bounded_and_never_uses_ssh_host_clipboard() {
1504 let mut clipboard = ClipboardHandler::for_test(false, false);
1505 clipboard.enable_primary_for_test();
1506 clipboard.write_text("regular").unwrap();
1507 clipboard.write_primary_text("selected").unwrap();
1508 assert_eq!(clipboard.last_written_text(), Some("regular"));
1509 assert_eq!(clipboard.read_primary_text().as_deref(), Some("selected"));
1510 assert!(clipboard.write_primary_text("").is_err());
1511 assert!(
1512 clipboard
1513 .write_primary_text(&"x".repeat(PRIMARY_MAX_BYTES + 1))
1514 .is_err()
1515 );
1516 assert_eq!(clipboard.read_primary_text().as_deref(), Some("selected"));
1517 let mut remote = ClipboardHandler::for_test(true, false);
1518 remote.enable_primary_for_test();
1519 assert!(remote.write_primary_text("private").is_err());
1520 assert!(remote.read_primary_text().is_none());
1521 assert!(remote.last_written_text().is_none());
1522 let mut forwarded = ClipboardHandler::with_terminal_context(TerminalClipboardContext {
1523 endpoint: ClipboardEndpoint::ForwardedDisplay,
1524 in_tmux: false,
1525 });
1526 forwarded.enable_primary_for_test();
1527 forwarded.write_primary_text("forwarded").unwrap();
1528 assert_eq!(forwarded.read_primary_text().as_deref(), Some("forwarded"));
1529 }
1530
1531 #[test]
1532 fn clipboard_markdown_preserves_rich_structure_and_code() {
1533 let html = r#"<h1>Release plan</h1><p>Keep <strong>authorship</strong> and
1534 <a href="https://example.com/review">review</a>.</p>
1535 <ul><li>Run gates</li><li>Dogfood</li></ul>
1536 <pre><code>fn main() {
1537 println!("&lt;ready&gt;");
1538 }</code></pre>
1539 <table><tr><th>Gate</th><th>Result</th></tr><tr><td>Tests</td><td>Pass</td></tr></table>"#;
1540 let markdown = clipboard_markdown(html).expect("rich text converts");
1541 assert!(markdown.contains("# Release plan"), "{markdown}");
1542 assert!(markdown.contains("**authorship**"), "{markdown}");
1543 assert!(
1544 markdown.contains("[review](https://example.com/review)"),
1545 "{markdown}"
1546 );
1547 assert!(markdown.contains("Run gates") && markdown.contains("Dogfood"));
1548 assert!(markdown.contains("```"), "{markdown}");
1549 assert!(markdown.contains("println!(\"<ready>\");"), "{markdown}");
1550 assert!(
1551 markdown
1552 .lines()
1553 .any(|line| line.split('|').map(str::trim).collect::<Vec<_>>()
1554 == ["", "Gate", "Result", ""]),
1555 "{markdown}"
1556 );
1557 }
1558
1559 #[test]
1560 fn clipboard_markdown_omits_executable_markup_and_falls_back_losslessly() {
1561 assert_eq!(
1562 clipboard_markdown("<script>secret()</script><style>secret</style>"),
1563 None
1564 );
1565 assert_eq!(
1566 clipboard_markdown(&"x".repeat(MAX_CLIPBOARD_HTML_BYTES + 1)),
1567 None
1568 );
1569 let markdown = clipboard_markdown("<h1>Release plan</h1>").unwrap();
1570 assert_eq!(markdown.trim(), "Release plan\n===");
1571 assert!(markdown.trim().contains('\n'), "not a memory quick-add");
1572 }
1573 // ImageData from arboard is only available on these platforms.
1574 #[cfg(any(
1575 target_os = "macos",
1576 target_os = "windows",
1577 all(target_os = "linux", not(target_env = "ohos"))
1578 ))]
1579 use std::borrow::Cow;
1580 #[cfg(unix)]
1581 use std::os::unix::fs::PermissionsExt;
1582
1583 #[test]
1584 fn terminal_clipboard_write_does_not_wait_for_slow_transport() {
1585 let (transport_started_tx, transport_started_rx) = std::sync::mpsc::channel();
1586 let (release_transport_tx, release_transport_rx) = std::sync::mpsc::channel();
1587 let writer = TerminalClipboardWriter::spawn_with(move |request| {
1588 assert_eq!(request.text, "copied");
1589 assert!(!request.in_tmux);
1590 transport_started_tx
1591 .send(())
1592 .expect("announce transport start");
1593 release_transport_rx.recv().expect("release slow transport");
1594 Ok(())
1595 })
1596 .expect("spawn clipboard writer");
1597 let mut clipboard = ClipboardHandler::for_test(true, false);
1598 clipboard.terminal_writer = Some(writer);
1599
1600 let (caller_returned_tx, caller_returned_rx) = std::sync::mpsc::channel();
1601 let caller = std::thread::spawn(move || {
1602 let result = clipboard.write_text("copied");
1603 caller_returned_tx
1604 .send((clipboard, result))
1605 .expect("report caller completion");
1606 });
1607
1608 let (clipboard, result) =
1609 match caller_returned_rx.recv_timeout(std::time::Duration::from_millis(250)) {
1610 Ok(value) => value,
1611 Err(err) => {
1612 let _ = release_transport_tx.send(());
1613 caller.join().expect("join clipboard caller");
1614 panic!("clipboard caller waited for slow transport: {err}");
1615 }
1616 };
1617 result.expect("queue clipboard write");
1618 transport_started_rx
1619 .recv_timeout(std::time::Duration::from_millis(250))
1620 .expect("worker started transport");
1621 assert!(
1622 clipboard.poll_write_completion().is_none(),
1623 "transport must remain pending until explicitly released"
1624 );
1625
1626 release_transport_tx.send(()).expect("release transport");
1627 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
1628 loop {
1629 if let Some(completion) = clipboard.poll_write_completion() {
1630 completion.expect("background clipboard completion");
1631 break;
1632 }
1633 assert!(
1634 std::time::Instant::now() < deadline,
1635 "background clipboard completion timed out"
1636 );
1637 std::thread::sleep(std::time::Duration::from_millis(10));
1638 }
1639 caller.join().expect("join clipboard caller");
1640 }
1641
1642 #[test]
1643 fn terminal_clipboard_write_reports_background_failure() {
1644 let writer =
1645 TerminalClipboardWriter::spawn_with(|_| bail!("terminal clipboard transport denied"))
1646 .expect("spawn clipboard writer");
1647 writer
1648 .enqueue("copied", false)
1649 .expect("queue clipboard write");
1650
1651 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
1652 loop {
1653 if let Some(completion) = writer.poll_completion() {
1654 let err = completion.expect_err("transport should fail");
1655 assert!(err.contains("transport denied"), "{err}");
1656 break;
1657 }
1658 assert!(
1659 std::time::Instant::now() < deadline,
1660 "background clipboard failure timed out"
1661 );
1662 std::thread::sleep(std::time::Duration::from_millis(10));
1663 }
1664 }
1665
1666 #[cfg(any(
1667 target_os = "macos",
1668 target_os = "windows",
1669 all(target_os = "linux", not(target_env = "ohos"))
1670 ))]
1671 fn solid_rgba(width: u16, height: u16, rgba: [u8; 4]) -> ImageData<'static> {
1672 let mut bytes = Vec::with_capacity((width as usize) * (height as usize) * 4);
1673 for _ in 0..(width as usize * height as usize) {
1674 bytes.extend_from_slice(&rgba);
1675 }
1676 ImageData {
1677 width: width as usize,
1678 height: height as usize,
1679 bytes: Cow::Owned(bytes),
1680 }
1681 }
1682
1683 #[test]
1684 #[cfg(any(
1685 target_os = "macos",
1686 target_os = "windows",
1687 all(target_os = "linux", not(target_env = "ohos"))
1688 ))]
1689 fn save_image_as_png_writes_valid_png() {
1690 let dir = tempfile::tempdir().unwrap();
1691 let img = solid_rgba(8, 4, [255, 0, 0, 255]);
1692 let pasted = save_image_as_png_in(dir.path(), &img).expect("encode png");
1693
1694 assert_eq!(pasted.width, 8);
1695 assert_eq!(pasted.height, 4);
1696 assert!(pasted.byte_len > 0);
1697 assert_eq!(
1698 pasted.path.extension().and_then(|s| s.to_str()),
1699 Some("png")
1700 );
1701
1702 // The first eight bytes of any PNG file are the magic signature; if
1703 // we ever regress to PPM or another format this will catch it.
1704 let header = std::fs::read(&pasted.path).unwrap();
1705 assert_eq!(&header[..8], b"\x89PNG\r\n\x1a\n");
1706 }
1707
1708 #[test]
1709 fn admit_clipboard_text_enforces_byte_limit() {
1710 let at_limit = "a".repeat(MAX_CLIPBOARD_TEXT_BYTES);
1711 assert_eq!(
1712 admit_clipboard_text(at_limit).unwrap().len(),
1713 MAX_CLIPBOARD_TEXT_BYTES
1714 );
1715
1716 let over_limit = "a".repeat(MAX_CLIPBOARD_TEXT_BYTES + 1);
1717 assert!(admit_clipboard_text(over_limit).is_err());
1718 }
1719
1720 #[test]
1721 #[cfg(any(
1722 target_os = "macos",
1723 target_os = "windows",
1724 all(target_os = "linux", not(target_env = "ohos"))
1725 ))]
1726 fn native_clipboard_read_bounds_text_and_image_payloads() {
1727 let image_called = std::cell::Cell::new(false);
1728 let outcome = resolve_native_clipboard_read(
1729 &mut (),
1730 true,
1731 |()| Some("<b>".to_string() + &"x".repeat(MAX_CLIPBOARD_HTML_BYTES + 1) + "</b>"),
1732 |()| Some("a".repeat(MAX_CLIPBOARD_TEXT_BYTES + 1)),
1733 |()| {
1734 image_called.set(true);
1735 Err("unexpected".to_string())
1736 },
1737 |_| unreachable!("image save must not run after oversized text"),
1738 );
1739 assert!(matches!(outcome, NativeClipboardOutcome::Rejected));
1740 assert!(!image_called.get());
1741
1742 let fallback = resolve_native_clipboard_read(
1743 &mut (),
1744 true,
1745 |()| Some("<b>".to_string() + &"x".repeat(MAX_CLIPBOARD_HTML_BYTES + 1) + "</b>"),
1746 |()| Some("bounded plain fallback".to_string()),
1747 |()| Err("unused".to_string()),
1748 |_| unreachable!(),
1749 );
1750 assert!(matches!(
1751 fallback,
1752 NativeClipboardOutcome::Content(ClipboardContent::Text(ref text))
1753 if text == "bounded plain fallback"
1754 ));
1755
1756 let dir = tempfile::tempdir().unwrap();
1757 let empty_dims = ImageData {
1758 width: 0,
1759 height: 4,
1760 bytes: Cow::Borrowed(&[]),
1761 };
1762 assert!(save_image_as_png_in(dir.path(), &empty_dims).is_err());
1763
1764 let too_many_pixels = ImageData {
1765 width: 8192,
1766 height: 4097,
1767 bytes: Cow::Borrowed(&[]),
1768 };
1769 assert!(save_image_as_png_in(dir.path(), &too_many_pixels).is_err());
1770
1771 let oversized_buffer = ImageData {
1772 width: 1,
1773 height: 1,
1774 bytes: Cow::Owned(vec![0u8; MAX_CLIPBOARD_RGBA_BYTES + 1]),
1775 };
1776 let image_outcome = resolve_native_clipboard_read(
1777 &mut (),
1778 false,
1779 |()| None,
1780 |()| None,
1781 |()| Ok(oversized_buffer),
1782 |img| save_image_as_png_in(dir.path(), img),
1783 );
1784 assert!(matches!(image_outcome, NativeClipboardOutcome::Rejected));
1785 assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
1786 }
1787
1788 #[test]
1789 #[cfg(all(
1790 unix,
1791 any(
1792 target_os = "macos",
1793 all(target_os = "linux", not(target_env = "ohos"))
1794 )
1795 ))]
1796 fn pasted_images_are_private_and_never_written_through_a_link() {
1797 use std::os::unix::fs::{PermissionsExt, symlink};
1798 let root = tempfile::tempdir().unwrap();
1799 let outside = tempfile::tempdir().unwrap();
1800 let img = solid_rgba(2, 2, [0, 255, 0, 255]);
1801
1802 let real = root.path().join("clipboard-images");
1803 let pasted = save_image_as_png_in(&real, &img).expect("a plain directory works");
1804 let mode = std::fs::metadata(&pasted.path)
1805 .unwrap()
1806 .permissions()
1807 .mode();
1808 assert_eq!(mode & 0o777, 0o600, "pasted images are owner-only");
1809
1810 // A linked destination directory is refused and nothing lands behind it.
1811 let linked = root.path().join("linked-images");
1812 symlink(outside.path(), &linked).unwrap();
1813 assert!(save_image_as_png_in(&linked, &img).is_err());
1814 assert_eq!(std::fs::read_dir(outside.path()).unwrap().count(), 0);
1815 }
1816
1817 #[test]
1818 fn clipboard_images_dir_uses_codewhale_home_directory() {
1819 let home = tempfile::tempdir().unwrap();
1820 let workspace = tempfile::tempdir().unwrap();
1821
1822 assert_eq!(
1823 codewhale_runtime::config::clipboard_images_dir_for_home(
1824 workspace.path(),
1825 Some(home.path())
1826 ),
1827 home.path().join(".codewhale").join("clipboard-images")
1828 );
1829 }
1830
1831 #[test]
1832 fn clipboard_images_dir_falls_back_to_workspace_without_home() {
1833 let workspace = tempfile::tempdir().unwrap();
1834
1835 assert_eq!(
1836 codewhale_runtime::config::clipboard_images_dir_for_home(workspace.path(), None),
1837 workspace.path().join("clipboard-images")
1838 );
1839 }
1840
1841 #[test]
1842 fn pasted_image_labels_format_correctly() {
1843 let p = PastedImage {
1844 path: PathBuf::from("/tmp/x.png"),
1845 width: 1024,
1846 height: 768,
1847 byte_len: 235 * 1024,
1848 };
1849 assert_eq!(p.short_label(), "1024x768 PNG");
1850 assert_eq!(p.size_label(), "235KB");
1851 }
1852
1853 #[test]
1854 fn ssh_detection_covers_openssh_markers_and_ignores_empty_values() {
1855 let client = TerminalClipboardContext::from_env_values(
1856 Some(OsStr::new("192.0.2.10 51234 22")),
1857 None,
1858 None,
1859 None,
1860 None,
1861 None,
1862 None,
1863 );
1864 let connection = TerminalClipboardContext::from_env_values(
1865 None,
1866 Some(OsStr::new("192.0.2.10 51234 192.0.2.20 22")),
1867 None,
1868 None,
1869 None,
1870 None,
1871 None,
1872 );
1873 let tty = TerminalClipboardContext::from_env_values(
1874 None,
1875 None,
1876 Some(OsStr::new("/dev/pts/4")),
1877 None,
1878 None,
1879 None,
1880 None,
1881 );
1882 let empty = TerminalClipboardContext::from_env_values(
1883 Some(OsStr::new("")),
1884 Some(OsStr::new("")),
1885 Some(OsStr::new("")),
1886 Some(OsStr::new("")),
1887 Some(OsStr::new("")),
1888 Some(OsStr::new("")),
1889 Some(OsStr::new("")),
1890 );
1891
1892 assert_eq!(client.endpoint, ClipboardEndpoint::TerminalClient);
1893 assert_eq!(connection.endpoint, ClipboardEndpoint::TerminalClient);
1894 assert_eq!(tty.endpoint, ClipboardEndpoint::TerminalClient);
1895 assert_eq!(empty.endpoint, ClipboardEndpoint::NativeHost);
1896 assert!(!empty.in_tmux);
1897 }
1898
1899 #[test]
1900 fn ssh_without_display_targets_terminal_client() {
1901 let remote_tmux = TerminalClipboardContext::from_env_values(
1902 Some(OsStr::new("192.0.2.10 51234 22")),
1903 None,
1904 None,
1905 None,
1906 None,
1907 None,
1908 Some(OsStr::new("/tmp/tmux-1000/default,1,0")),
1909 );
1910 let local =
1911 TerminalClipboardContext::from_env_values(None, None, None, None, None, None, None);
1912
1913 assert_eq!(
1914 remote_tmux.write_order(),
1915 ClipboardWriteOrder::TerminalClientOnly
1916 );
1917 assert!(!remote_tmux.permits_native_read());
1918 assert!(remote_tmux.requires_terminal_paste());
1919 assert!(remote_tmux.in_tmux);
1920 assert_eq!(
1921 local.write_order(),
1922 ClipboardWriteOrder::NativeHostThenTerminal
1923 );
1924 assert!(local.permits_native_read());
1925 assert!(!local.requires_terminal_paste());
1926 }
1927
1928 #[test]
1929 fn ssh_uses_forwarded_x11_or_explicit_graphical_clipboard_endpoint() {
1930 let x11 = TerminalClipboardContext::from_env_values(
1931 None,
1932 Some(OsStr::new("192.0.2.10 51234 192.0.2.20 22")),
1933 None,
1934 Some(OsStr::new("localhost:10.0")),
1935 None,
1936 None,
1937 None,
1938 );
1939 let wayland = TerminalClipboardContext::from_env_values(
1940 Some(OsStr::new("192.0.2.10 51234 22")),
1941 None,
1942 None,
1943 None,
1944 Some(OsStr::new("wayland-1")),
1945 Some(OsStr::new("graphical")),
1946 None,
1947 );
1948
1949 for context in [x11, wayland] {
1950 assert_eq!(context.endpoint, ClipboardEndpoint::ForwardedDisplay);
1951 assert_eq!(
1952 context.write_order(),
1953 ClipboardWriteOrder::NativeHostThenTerminal
1954 );
1955 assert!(context.permits_native_read());
1956 assert!(!context.requires_terminal_paste());
1957 }
1958
1959 let ambient_remote = TerminalClipboardContext::from_env_values(
1960 Some(OsStr::new("192.0.2.10 51234 22")),
1961 None,
1962 None,
1963 Some(OsStr::new(":0")),
1964 Some(OsStr::new("wayland-0")),
1965 None,
1966 None,
1967 );
1968 assert_eq!(ambient_remote.endpoint, ClipboardEndpoint::TerminalClient);
1969
1970 let forced_terminal = TerminalClipboardContext::from_env_values(
1971 Some(OsStr::new("192.0.2.10 51234 22")),
1972 None,
1973 None,
1974 Some(OsStr::new("localhost:10.0")),
1975 None,
1976 Some(OsStr::new("terminal")),
1977 None,
1978 );
1979 assert_eq!(forced_terminal.endpoint, ClipboardEndpoint::TerminalClient);
1980 }
1981
1982 #[test]
1983 fn osc52_sequence_encodes_text_clipboard_write() {
1984 let sequence = osc52_sequence("hello").expect("sequence");
1985 assert_eq!(sequence, "\x1b]52;c;aGVsbG8=\x07");
1986 }
1987
1988 #[test]
1989 fn osc52_sequence_rejects_oversized_selection() {
1990 let text = "x".repeat(OSC52_MAX_BYTES + 1);
1991 let err = osc52_sequence(&text).expect_err("oversized should fail");
1992 assert!(
1993 err.to_string().contains("too large"),
1994 "unexpected error: {err}"
1995 );
1996 }
1997
1998 #[cfg(unix)]
1999 #[test]
2000 fn tmux_helper_reports_command_failure() {
2001 let dir = tempfile::tempdir().unwrap();
2002 let script = dir.path().join("tmux");
2003 std::fs::write(
2004 &script,
2005 r#"#!/bin/sh
2006 cat >/dev/null
2007 echo 'clipboard denied' >&2
2008 exit 42
2009 "#,
2010 )
2011 .unwrap();
2012 let mut perms = std::fs::metadata(&script).unwrap().permissions();
2013 perms.set_mode(0o755);
2014 std::fs::set_permissions(&script, perms).unwrap();
2015
2016 // Another test thread may fork while this one still had the script
2017 // open for writing; the child keeps that descriptor until it execs,
2018 // and running the script meanwhile fails with "Text file busy". That
2019 // is the test's own race, not the behavior under test, so wait it out.
2020 let mut attempts = 0;
2021 let err = loop {
2022 let err = write_text_with_tmux_using_argv(script.to_str().unwrap(), &[], "copy")
2023 .expect_err("non-zero tmux status should fail");
2024 attempts += 1;
2025 if attempts >= 100 || !err.to_string().contains("Text file busy") {
2026 break err;
2027 }
2028 std::thread::sleep(std::time::Duration::from_millis(20));
2029 };
2030
2031 assert!(err.to_string().contains("exited with"), "{err}");
2032 assert!(err.to_string().contains("clipboard denied"));
2033 }
2034
2035 #[cfg(unix)]
2036 #[test]
2037 fn tmux_helper_times_out_stalled_child_and_unblocks_worker() {
2038 let dir = tempfile::tempdir().unwrap();
2039 let hang_script = dir.path().join("tmux-hang");
2040 std::fs::write(
2041 &hang_script,
2042 r#"#!/bin/sh
2043 cat >/dev/null
2044 exec sleep 30
2045 "#,
2046 )
2047 .unwrap();
2048 let mut perms = std::fs::metadata(&hang_script).unwrap().permissions();
2049 perms.set_mode(0o755);
2050 std::fs::set_permissions(&hang_script, perms).unwrap();
2051
2052 let ok_script = dir.path().join("tmux-ok");
2053 std::fs::write(
2054 &ok_script,
2055 r#"#!/bin/sh
2056 cat >/dev/null
2057 exit 0
2058 "#,
2059 )
2060 .unwrap();
2061 let mut perms = std::fs::metadata(&ok_script).unwrap().permissions();
2062 perms.set_mode(0o755);
2063 std::fs::set_permissions(&ok_script, perms).unwrap();
2064
2065 let timeout = std::time::Duration::from_millis(150);
2066 let run_with_retry = |program: &Path, text: &str| {
2067 let mut attempts = 0;
2068 loop {
2069 let result = write_text_with_tmux_using_argv_with_timeout(
2070 program.to_str().unwrap(),
2071 &[],
2072 text,
2073 timeout,
2074 );
2075 attempts += 1;
2076 let busy = result
2077 .as_ref()
2078 .err()
2079 .is_some_and(|err| err.to_string().contains("Text file busy"));
2080 if !busy || attempts >= 100 {
2081 return result;
2082 }
2083 std::thread::sleep(std::time::Duration::from_millis(20));
2084 }
2085 };
2086
2087 let started = std::time::Instant::now();
2088 let err =
2089 run_with_retry(&hang_script, "stuck").expect_err("stalled tmux child must time out");
2090 assert!(err.to_string().contains("timed out"), "{err}");
2091 assert!(
2092 started.elapsed() < std::time::Duration::from_secs(3),
2093 "stalled tmux child took too long: {:?}",
2094 started.elapsed()
2095 );
2096
2097 let hang_path = hang_script.clone();
2098 let ok_path = ok_script.clone();
2099 let writer = TerminalClipboardWriter::spawn_with(move |request| {
2100 let (script, call_timeout) = if request.text == "stuck" {
2101 (&hang_path, timeout)
2102 } else {
2103 (&ok_path, std::time::Duration::from_secs(2))
2104 };
2105 let mut attempts = 0;
2106 loop {
2107 let result = write_text_with_tmux_using_argv_with_timeout(
2108 script.to_str().unwrap(),
2109 &[],
2110 &request.text,
2111 call_timeout,
2112 );
2113 attempts += 1;
2114 let busy = result
2115 .as_ref()
2116 .err()
2117 .is_some_and(|err| err.to_string().contains("Text file busy"));
2118 if !busy || attempts >= 100 {
2119 return result;
2120 }
2121 std::thread::sleep(std::time::Duration::from_millis(20));
2122 }
2123 })
2124 .expect("spawn clipboard writer");
2125
2126 writer
2127 .enqueue("stuck", true)
2128 .expect("enqueue stalled write");
2129 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
2130 let first_err = loop {
2131 if let Some(completion) = writer.poll_completion() {
2132 break completion.expect_err("stalled write should fail with timeout");
2133 }
2134 assert!(
2135 std::time::Instant::now() < deadline,
2136 "stalled tmux worker never reported timeout completion"
2137 );
2138 std::thread::sleep(std::time::Duration::from_millis(10));
2139 };
2140 assert!(first_err.contains("timed out"), "{first_err}");
2141
2142 writer
2143 .enqueue("recovered", true)
2144 .expect("worker must accept a subsequent write after timeout");
2145 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
2146 loop {
2147 if let Some(completion) = writer.poll_completion() {
2148 completion.expect("subsequent write should succeed after worker recovers");
2149 break;
2150 }
2151 assert!(
2152 std::time::Instant::now() < deadline,
2153 "subsequent tmux write never completed"
2154 );
2155 std::thread::sleep(std::time::Duration::from_millis(10));
2156 }
2157 }
2158
2159 #[cfg(all(unix, not(target_env = "ohos")))]
2160 #[test]
2161 fn tmux_load_buffer_w_reaches_attached_client_with_default_passthrough_disabled() {
2162 use std::io::Read as _;
2163
2164 // Every subprocess must inherit the same terminal environment, not
2165 // another fixture's transient PATH/TERM/multiplexer overrides.
2166 let _env = crate::test_support::lock_test_env();
2167
2168 let version = match Command::new("tmux").arg("-V").output() {
2169 Ok(output) if output.status.success() => output,
2170 _ => return,
2171 };
2172 assert!(
2173 String::from_utf8_lossy(&version.stdout).starts_with("tmux "),
2174 "unexpected tmux version output"
2175 );
2176
2177 let nonce = std::time::SystemTime::now()
2178 .duration_since(std::time::UNIX_EPOCH)
2179 .expect("clock after epoch")
2180 .as_nanos();
2181 let socket = format!("codewhale-clipboard-{}-{nonce}", std::process::id());
2182
2183 struct TmuxServer(String);
2184 impl Drop for TmuxServer {
2185 fn drop(&mut self) {
2186 let _ = Command::new("tmux")
2187 .args(["-L", self.0.as_str(), "kill-server"])
2188 .status();
2189 }
2190 }
2191 let server = TmuxServer(socket);
2192 let started = Command::new("tmux")
2193 .args([
2194 "-L",
2195 server.0.as_str(),
2196 "-f",
2197 "/dev/null",
2198 "new-session",
2199 "-d",
2200 ])
2201 .status()
2202 .expect("start isolated tmux server");
2203 assert!(started.success(), "isolated tmux server should start");
2204
2205 let option = |name: &str| {
2206 let output = Command::new("tmux")
2207 .args(["-L", server.0.as_str(), "show-options", "-gv", name])
2208 .output()
2209 .expect("read tmux option");
2210 assert!(output.status.success(), "read tmux option {name}");
2211 String::from_utf8(output.stdout)
2212 .expect("tmux option should be utf-8")
2213 .trim()
2214 .to_string()
2215 };
2216 assert_eq!(option("allow-passthrough"), "off");
2217 assert_eq!(option("set-clipboard"), "external");
2218
2219 let pty_system = portable_pty::native_pty_system();
2220 let pair = pty_system
2221 .openpty(portable_pty::PtySize {
2222 rows: 24,
2223 cols: 80,
2224 pixel_width: 0,
2225 pixel_height: 0,
2226 })
2227 .expect("open attached-client PTY");
2228 let mut attach = portable_pty::CommandBuilder::new("tmux");
2229 for arg in ["-L", server.0.as_str(), "attach-session", "-t", "0"] {
2230 attach.arg(arg);
2231 }
2232 attach.env("TERM", "xterm-256color");
2233 let mut attached_client = pair
2234 .slave
2235 .spawn_command(attach)
2236 .expect("attach tmux client to PTY");
2237 drop(pair.slave);
2238
2239 let mut reader = pair
2240 .master
2241 .try_clone_reader()
2242 .expect("clone attached-client PTY reader");
2243 let (output_tx, output_rx) = std::sync::mpsc::channel();
2244 let reader_thread = std::thread::spawn(move || {
2245 let mut chunk = [0_u8; 4096];
2246 loop {
2247 match reader.read(&mut chunk) {
2248 Ok(0) | Err(_) => break,
2249 Ok(len) => {
2250 if output_tx.send(chunk[..len].to_vec()).is_err() {
2251 break;
2252 }
2253 }
2254 }
2255 }
2256 });
2257
2258 // Load-tolerant bounds, not the contract under test: on a machine
2259 // running a full parallel suite, tmux server startup and OSC 52
2260 // forwarding can both exceed a tight 3s wall clock (#5929). The test
2261 // still verifies the *content* of what reaches the attached client;
2262 // only how long it is willing to wait for a loaded machine changed.
2263 let attach_deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
2264 loop {
2265 let clients = Command::new("tmux")
2266 .args(["-L", server.0.as_str(), "list-clients"])
2267 .output()
2268 .expect("list attached tmux clients");
2269 if clients.status.success() && !clients.stdout.is_empty() {
2270 break;
2271 }
2272 assert!(
2273 std::time::Instant::now() < attach_deadline,
2274 "tmux client did not attach to the test PTY"
2275 );
2276 std::thread::sleep(std::time::Duration::from_millis(25));
2277 }
2278 // A listed client can precede its terminal startup. tmux discards
2279 // clipboard requests before TTY_STARTED; actual PTY output establishes
2280 // that startup reached the terminal before the one request we verify.
2281 output_rx
2282 .recv_timeout(attach_deadline.saturating_duration_since(std::time::Instant::now()))
2283 .expect("attached tmux client should produce terminal startup output");
2284 while output_rx.try_recv().is_ok() {}
2285
2286 let copied_text = "copy through default tmux";
2287 write_text_with_tmux_using_argv("tmux", &["-L", server.0.as_str()], copied_text)
2288 .expect("tmux-native clipboard request");
2289
2290 let encoded = base64::engine::general_purpose::STANDARD.encode(copied_text.as_bytes());
2291 let expected_receipts = [
2292 format!("\x1b]52;;{encoded}\x07").into_bytes(),
2293 format!("\x1b]52;c;{encoded}\x07").into_bytes(),
2294 format!("\x1b]52;;{encoded}\x1b\\").into_bytes(),
2295 format!("\x1b]52;c;{encoded}\x1b\\").into_bytes(),
2296 ];
2297 let receipt_deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
2298 let mut attached_output = Vec::new();
2299 let receipt_received = loop {
2300 if expected_receipts.iter().any(|receipt| {
2301 attached_output
2302 .windows(receipt.len())
2303 .any(|window| window == receipt)
2304 }) {
2305 break true;
2306 }
2307 if std::time::Instant::now() >= receipt_deadline {
2308 break false;
2309 }
2310 match output_rx.recv_timeout(std::time::Duration::from_millis(50)) {
2311 Ok(bytes) => attached_output.extend_from_slice(&bytes),
2312 Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
2313 Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break false,
2314 }
2315 };
2316
2317 let buffer = Command::new("tmux")
2318 .args(["-L", server.0.as_str(), "show-buffer"])
2319 .output()
2320 .expect("read tmux buffer");
2321 assert!(buffer.status.success(), "tmux buffer should be readable");
2322 assert_eq!(buffer.stdout, copied_text.as_bytes());
2323
2324 let _ = attached_client.kill();
2325 let _ = attached_client.wait();
2326 drop(pair.master);
2327 drop(output_rx);
2328 let _ = reader_thread.join();
2329
2330 assert!(
2331 receipt_received,
2332 "attached tmux client did not receive the OSC 52 clipboard request: {attached_output:?}"
2333 );
2334 }
2335
2336 #[cfg(unix)]
2337 #[test]
2338 fn wl_paste_helper_reads_text_from_stdout() {
2339 let dir = tempfile::tempdir().unwrap();
2340 let script = dir.path().join("wl-paste");
2341 std::fs::write(
2342 &script,
2343 r#"#!/bin/sh
2344 seen_no_newline=0
2345 seen_text_plain=0
2346 while [ "$#" -gt 0 ]; do
2347 case "$1" in
2348 --no-newline) seen_no_newline=1 ;;
2349 --type)
2350 shift
2351 [ "${1:-}" = "text/plain" ] && seen_text_plain=1
2352 ;;
2353 esac
2354 shift
2355 done
2356 [ "$seen_text_plain" -eq 1 ] || exit 40
2357 if [ "$seen_no_newline" -eq 1 ]; then
2358 printf 'from-wayland'
2359 else
2360 printf 'from-wayland\n'
2361 fi
2362 "#,
2363 )
2364 .unwrap();
2365 let mut perms = std::fs::metadata(&script).unwrap().permissions();
2366 perms.set_mode(0o755);
2367 std::fs::set_permissions(&script, perms).unwrap();
2368
2369 // A freshly written helper script can transiently report ETXTBSY
2370 // ("Text file busy") when a concurrent test in this parallel suite
2371 // forks while the write descriptor is still inherited. Retry the
2372 // exec briefly so this assertion exercises the helper contract
2373 // rather than the fork/exec window; the bound is load tolerance,
2374 // not the behavior under test (same class as #5929).
2375 let mut attempts = 0;
2376 let text = loop {
2377 match read_text_with_wlpaste_using_argv(script.to_str().unwrap()) {
2378 Ok(text) => break text,
2379 Err(error) => {
2380 attempts += 1;
2381 let busy = error.to_string().contains("Text file busy");
2382 assert!(
2383 busy && attempts < 100,
2384 "read text through wl-paste helper: {error:#}"
2385 );
2386 std::thread::sleep(std::time::Duration::from_millis(10));
2387 }
2388 }
2389 };
2390
2391 assert_eq!(text, "from-wayland");
2392 }
2393 }
2394
2394 lines RUST