codewhale-tui 0.9.5

Terminal UI for open-source and open-weight coding models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
//! Clipboard handling for paste support in TUI
//!
//! Supports text and image paste operations. Images on the clipboard are
//! encoded as PNG and persisted under `~/.codewhale/clipboard-images/` so the
//! model can reach them via the existing `@`-mention / file tools (DeepSeek
//! V4 does not currently accept inline image input on its Chat Completions
//! endpoint, so we materialize the bytes to disk instead of base64-embedding
//! them in the request).
//!
//! OpenHarmony deliberately excludes native desktop/Wayland clipboard APIs.
//! Copy falls back to OSC 52 (or tmux `load-buffer -w`), paste arrives through
//! terminal input, and image clipboard reads are unavailable.

use std::ffi::OsStr;
#[cfg(any(not(test), all(test, unix)))]
use std::io::Write;
#[cfg(not(test))]
use std::io::{self, IsTerminal};
use std::path::{Path, PathBuf};
#[cfg(any(not(test), all(test, unix)))]
use std::process::{Command, Stdio};
#[cfg(any(
    target_os = "macos",
    target_os = "windows",
    all(target_os = "linux", not(target_env = "ohos"))
))]
use std::time::{SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result, bail};
#[cfg(any(
    target_os = "macos",
    target_os = "windows",
    all(target_os = "linux", not(target_env = "ohos"))
))]
use arboard::{Clipboard, ImageData};
use base64::Engine as _;
#[cfg(any(
    target_os = "macos",
    target_os = "windows",
    all(target_os = "linux", not(target_env = "ohos"))
))]
use image::{ImageBuffer, Rgba};

const OSC52_MAX_BYTES: usize = 100 * 1024;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ClipboardEndpoint {
    /// The TUI and desktop clipboard live on the same host.
    NativeHost,
    /// SSH exported a graphical display (X11 or Wayland), so the native
    /// clipboard intentionally addresses that forwarded display.
    ForwardedDisplay,
    /// No graphical endpoint is available over SSH. Clipboard transfer must
    /// be requested from the terminal client instead.
    TerminalClient,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ClipboardWriteOrder {
    /// An SSH TUI without an exported graphical display must target the
    /// terminal client. A native clipboard on the remote host can succeed
    /// while writing to the wrong machine.
    TerminalClientOnly,
    /// A local TUI should prefer the native clipboard (including images) and
    /// retain OSC 52 as the terminal fallback.
    NativeHostThenTerminal,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct TerminalClipboardContext {
    endpoint: ClipboardEndpoint,
    in_tmux: bool,
}

impl TerminalClipboardContext {
    fn detect() -> Self {
        let ssh_client = std::env::var_os("SSH_CLIENT");
        let ssh_connection = std::env::var_os("SSH_CONNECTION");
        let ssh_tty = std::env::var_os("SSH_TTY");
        let display = std::env::var_os("DISPLAY");
        let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
        let ssh_clipboard = std::env::var_os("CODEWHALE_SSH_CLIPBOARD");
        let tmux = std::env::var_os("TMUX");
        Self::from_env_values(
            ssh_client.as_deref(),
            ssh_connection.as_deref(),
            ssh_tty.as_deref(),
            display.as_deref(),
            wayland_display.as_deref(),
            ssh_clipboard.as_deref(),
            tmux.as_deref(),
        )
    }

    fn from_env_values(
        ssh_client: Option<&OsStr>,
        ssh_connection: Option<&OsStr>,
        ssh_tty: Option<&OsStr>,
        display: Option<&OsStr>,
        wayland_display: Option<&OsStr>,
        ssh_clipboard: Option<&OsStr>,
        tmux: Option<&OsStr>,
    ) -> Self {
        let in_ssh_session = [ssh_client, ssh_connection, ssh_tty]
            .into_iter()
            .flatten()
            .any(|value| !value.is_empty());
        let has_graphical_display = [display, wayland_display]
            .into_iter()
            .flatten()
            .any(|value| !value.is_empty());
        let forwarded_x11 = display.and_then(OsStr::to_str).is_some_and(|value| {
            ["localhost:", "127.0.0.1:", "[::1]:", "::1:"]
                .iter()
                .any(|prefix| value.starts_with(prefix))
        });
        let use_graphical_display = match ssh_clipboard.and_then(OsStr::to_str) {
            Some("graphical") => has_graphical_display,
            Some("terminal") => false,
            _ => forwarded_x11,
        };

        Self {
            // OpenSSH normally exports SSH_CLIENT and SSH_CONNECTION.
            // SSH_TTY is an additional PTY-only marker and is independently
            // sufficient when wrappers preserve it without the other two.
            endpoint: match (in_ssh_session, use_graphical_display) {
                (false, _) => ClipboardEndpoint::NativeHost,
                (true, true) => ClipboardEndpoint::ForwardedDisplay,
                (true, false) => ClipboardEndpoint::TerminalClient,
            },
            in_tmux: tmux.is_some_and(|value| !value.is_empty()),
        }
    }

    fn write_order(self) -> ClipboardWriteOrder {
        if self.endpoint == ClipboardEndpoint::TerminalClient {
            ClipboardWriteOrder::TerminalClientOnly
        } else {
            ClipboardWriteOrder::NativeHostThenTerminal
        }
    }

    fn permits_native_read(self) -> bool {
        self.endpoint != ClipboardEndpoint::TerminalClient
    }

    fn requires_terminal_paste(self) -> bool {
        self.endpoint == ClipboardEndpoint::TerminalClient
    }
}

// === Types ===

/// Metadata captured for a pasted clipboard image. Used by the composer to
/// render a status hint like `Pasted 1024x768 image (235KB) → <path>`.
#[derive(Clone)]
pub struct PastedImage {
    pub path: PathBuf,
    pub width: u32,
    pub height: u32,
    pub byte_len: usize,
}

impl PastedImage {
    /// Short human-readable summary, e.g. `1024x768 PNG`.
    pub fn short_label(&self) -> String {
        format!("{}x{} PNG", self.width, self.height)
    }

    /// Approximate file size suffix, e.g. `235KB`.
    pub fn size_label(&self) -> String {
        let kb = (self.byte_len as f64 / 1024.0).round() as u64;
        format!("{kb}KB")
    }
}

/// Clipboard payloads supported by the TUI.
#[cfg_attr(
    all(
        any(target_env = "ohos", target_os = "android", target_os = "netbsd"),
        not(test)
    ),
    allow(dead_code)
)]
pub enum ClipboardContent {
    Text(String),
    Image(PastedImage),
}

struct TerminalClipboardWriteRequest {
    text: String,
    in_tmux: bool,
}

type TerminalClipboardWriteCompletion = std::result::Result<(), String>;

/// Serializes terminal-client clipboard writes on a bounded background lane.
///
/// OSC 52 ultimately writes to the terminal output stream, which can block
/// indefinitely under backpressure. tmux transport can likewise wait on a
/// stalled server. Keeping both operations on this worker means copy actions
/// never park the TUI input/render loop, while the single request slot bounds
/// memory and preserves copy order.
struct TerminalClipboardWriter {
    request_tx: std::sync::mpsc::SyncSender<TerminalClipboardWriteRequest>,
    completion_rx: std::sync::mpsc::Receiver<TerminalClipboardWriteCompletion>,
}

impl TerminalClipboardWriter {
    #[cfg(not(test))]
    fn spawn() -> Result<Self> {
        Self::spawn_with(|request| write_text_to_terminal_client(&request.text, request.in_tmux))
    }

    fn spawn_with<F>(write: F) -> Result<Self>
    where
        F: Fn(TerminalClipboardWriteRequest) -> Result<()> + Send + 'static,
    {
        let (request_tx, request_rx) = std::sync::mpsc::sync_channel(1);
        let (completion_tx, completion_rx) = std::sync::mpsc::channel();
        std::thread::Builder::new()
            .name("terminal-clipboard-writer".to_string())
            .spawn(move || {
                while let Ok(request) = request_rx.recv() {
                    let completion = write(request).map_err(|err| format!("{err:#}"));
                    if completion_tx.send(completion).is_err() {
                        break;
                    }
                }
            })
            .context("spawn terminal clipboard writer")?;
        Ok(Self {
            request_tx,
            completion_rx,
        })
    }

    fn enqueue(&self, text: &str, in_tmux: bool) -> Result<()> {
        let request = TerminalClipboardWriteRequest {
            text: text.to_string(),
            in_tmux,
        };
        self.request_tx.try_send(request).map_err(|err| match err {
            std::sync::mpsc::TrySendError::Full(_) => {
                anyhow::anyhow!("another terminal clipboard write is still queued")
            }
            std::sync::mpsc::TrySendError::Disconnected(_) => {
                anyhow::anyhow!("terminal clipboard writer stopped")
            }
        })
    }

    fn poll_completion(&self) -> Option<TerminalClipboardWriteCompletion> {
        self.completion_rx.try_recv().ok()
    }
}

/// Clipboard reader/writer helper.
pub struct ClipboardHandler {
    terminal_context: TerminalClipboardContext,
    terminal_writer: Option<TerminalClipboardWriter>,
    #[cfg(any(
        target_os = "macos",
        target_os = "windows",
        all(target_os = "linux", not(target_env = "ohos"))
    ))]
    clipboard: Option<Clipboard>,
    #[cfg(any(
        target_os = "macos",
        target_os = "windows",
        all(target_os = "linux", not(target_env = "ohos"))
    ))]
    clipboard_init_attempted: bool,
    #[cfg(test)]
    written_text: Vec<String>,
    #[cfg(test)]
    fail_text_writes: bool,
}

impl ClipboardHandler {
    /// Create a new clipboard handler without connecting.
    ///
    /// The actual clipboard connection is deferred to first use
    /// (`ensure_clipboard`) so that startup on hosts without an X11/Wayland
    /// server (headless, WSL2) never blocks the TUI event loop.
    pub fn new() -> Self {
        Self::with_terminal_context(TerminalClipboardContext::detect())
    }

    fn with_terminal_context(terminal_context: TerminalClipboardContext) -> Self {
        Self {
            terminal_context,
            terminal_writer: None,
            #[cfg(any(
                target_os = "macos",
                target_os = "windows",
                all(target_os = "linux", not(target_env = "ohos"))
            ))]
            clipboard: None,
            #[cfg(any(
                target_os = "macos",
                target_os = "windows",
                all(target_os = "linux", not(target_env = "ohos"))
            ))]
            clipboard_init_attempted: false,
            #[cfg(test)]
            written_text: Vec::new(),
            #[cfg(test)]
            fail_text_writes: false,
        }
    }

    #[cfg(test)]
    pub(crate) fn for_test(in_ssh_session: bool, in_tmux: bool) -> Self {
        Self::with_terminal_context(TerminalClipboardContext {
            endpoint: if in_ssh_session {
                ClipboardEndpoint::TerminalClient
            } else {
                ClipboardEndpoint::NativeHost
            },
            in_tmux,
        })
    }

    /// Construct a deterministic unavailable clipboard for command tests.
    #[cfg(test)]
    pub(crate) fn unavailable_for_test(in_ssh_session: bool) -> Self {
        let mut handler = Self::for_test(in_ssh_session, false);
        handler.fail_text_writes = true;
        handler
    }

    /// SSH without a forwarded graphical display cannot synchronously read
    /// the terminal client's clipboard. Paste must be initiated by the local
    /// terminal so it arrives as bracketed paste (or a raw paste burst on
    /// older terminals).
    pub(crate) fn requires_terminal_paste(&self) -> bool {
        self.terminal_context.requires_terminal_paste()
    }

    /// Try to connect to the system clipboard, bounded by a short timeout.
    ///
    /// On Linux, `arboard::Clipboard::new()` opens a blocking X11 connection.
    /// When no X server is running (headless, WSL2 without WSLg), the connect
    /// call can hang indefinitely. We spawn the connection attempt on a
    /// temporary thread and give it 500 ms; if it doesn't return in time the
    /// handler stays in fallback/no-op mode and `read`/`write_text` fall
    /// through to their OSC 52 and pbcopy/powershell fallbacks.
    #[cfg(any(
        target_os = "macos",
        target_os = "windows",
        all(target_os = "linux", not(target_env = "ohos"))
    ))]
    fn ensure_clipboard(&mut self) {
        if self.clipboard_init_attempted {
            return;
        }
        self.clipboard_init_attempted = true;

        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let _ = tx.send(Clipboard::new().ok());
        });
        self.clipboard = rx
            .recv_timeout(std::time::Duration::from_millis(500))
            .ok()
            .flatten();
    }

    /// Read the clipboard and return the parsed content.
    ///
    /// `workspace` is used as a fallback location when `~/.codewhale/` cannot
    /// be resolved (e.g. running with a stripped HOME in CI sandboxes).
    pub fn read(&mut self, workspace: &Path) -> Option<ClipboardContent> {
        // With no display exported over SSH there is no synchronously readable
        // clipboard endpoint. A forwarded X11/Wayland display is explicit and
        // remains readable, including its image clipboard.
        if !self.terminal_context.permits_native_read() {
            return None;
        }

        #[cfg(all(target_os = "linux", not(target_env = "ohos"), not(test)))]
        if let Ok(text) = read_text_with_wlpaste() {
            return Some(ClipboardContent::Text(text));
        }

        #[cfg(any(
            target_os = "macos",
            target_os = "windows",
            all(target_os = "linux", not(target_env = "ohos"))
        ))]
        {
            self.ensure_clipboard();
            let clipboard = self.clipboard.as_mut()?;
            if let Ok(text) = clipboard.get_text() {
                return Some(ClipboardContent::Text(text));
            }

            if let Ok(image) = clipboard.get_image()
                && let Ok(pasted) = save_image_as_png(workspace, &image)
            {
                return Some(ClipboardContent::Image(pasted));
            }
        }

        let _ = workspace;
        None
    }

    /// Write text to the clipboard.
    ///
    /// Native clipboard transports complete before this method returns. OSC 52
    /// and tmux terminal-client writes are validated and admitted to a bounded
    /// background worker; asynchronous transport failures are exposed through
    /// [`Self::poll_write_completion`].
    pub fn write_text(&mut self, text: &str) -> Result<()> {
        #[cfg(test)]
        {
            if let Some(writer) = self.terminal_writer.as_ref() {
                return writer.enqueue(text, self.terminal_context.in_tmux);
            }
            if self.fail_text_writes {
                bail!("test clipboard unavailable");
            }
            self.written_text.push(text.to_string());
            Ok(())
        }

        #[cfg(not(test))]
        {
            if self.terminal_context.write_order() == ClipboardWriteOrder::TerminalClientOnly {
                return self
                    .enqueue_terminal_write(text)
                    .map_err(|err| anyhow::anyhow!("Clipboard unavailable: {err}"));
            }

            #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
            if write_text_with_wlcopy(text).is_ok() {
                return Ok(());
            }

            #[cfg(any(
                target_os = "macos",
                target_os = "windows",
                all(target_os = "linux", not(target_env = "ohos"))
            ))]
            {
                self.ensure_clipboard();
                if let Some(clipboard) = self.clipboard.as_mut()
                    && clipboard.set_text(text.to_string()).is_ok()
                {
                    return Ok(());
                }
            }

            #[cfg(target_os = "macos")]
            if write_text_with_pbcopy(text).is_ok() {
                return Ok(());
            }

            #[cfg(target_os = "windows")]
            if write_text_with_set_clipboard(text).is_ok() {
                return Ok(());
            }

            self.enqueue_terminal_write(text)
                .map_err(|err| anyhow::anyhow!("Clipboard unavailable: {err}"))
        }
    }

    #[cfg(not(test))]
    fn enqueue_terminal_write(&mut self, text: &str) -> Result<()> {
        if !self.terminal_context.in_tmux {
            if text.len() > OSC52_MAX_BYTES {
                bail!("selection is too large for OSC 52 clipboard fallback");
            }
            if !io::stdout().is_terminal() {
                bail!("OSC 52 clipboard fallback requires a terminal");
            }
        }

        if self.terminal_writer.is_none() {
            self.terminal_writer = Some(TerminalClipboardWriter::spawn()?);
        }
        self.terminal_writer
            .as_ref()
            .expect("terminal clipboard writer initialized")
            .enqueue(text, self.terminal_context.in_tmux)
    }

    /// Return one completed background terminal clipboard write, if available.
    ///
    /// Successes are intentionally quiet because callers already show their
    /// normal copy receipt. Failures are drained by the event loop and replace
    /// that optimistic receipt with an actionable error.
    pub(crate) fn poll_write_completion(&self) -> Option<TerminalClipboardWriteCompletion> {
        self.terminal_writer
            .as_ref()
            .and_then(TerminalClipboardWriter::poll_completion)
    }

    #[cfg(test)]
    pub fn last_written_text(&self) -> Option<&str> {
        self.written_text.last().map(String::as_str)
    }
}

#[cfg(all(target_os = "macos", not(test)))]
fn write_text_with_pbcopy(text: &str) -> Result<()> {
    write_text_with_stdin_command("pbcopy", &[], text, "pbcopy")
}

#[cfg(all(target_os = "windows", not(test)))]
fn write_text_with_set_clipboard(text: &str) -> Result<()> {
    write_text_with_stdin_command(
        "powershell.exe",
        &["-NoProfile", "-Command", "Set-Clipboard -Value $input"],
        text,
        "Set-Clipboard",
    )
}

#[cfg(all(any(target_os = "macos", target_os = "windows"), not(test)))]
fn write_text_with_stdin_command(
    program: &str,
    args: &[&str],
    text: &str,
    label: &str,
) -> Result<()> {
    let mut child = Command::new(program)
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .map_err(|e| anyhow::anyhow!("Failed to run {label}: {e}"))?;
    if let Some(mut stdin) = child.stdin.take() {
        stdin
            .write_all(text.as_bytes())
            .map_err(|e| anyhow::anyhow!("Failed to write to {label}: {e}"))?;
    }
    let _ = std::thread::Builder::new()
        .name("clipboard-wait".to_string())
        .spawn(move || {
            let _ = child.wait();
        });
    Ok(())
}

#[cfg(all(target_os = "linux", not(target_env = "ohos"), not(test)))]
fn write_text_with_wlcopy(text: &str) -> Result<()> {
    write_text_with_wlcopy_using_argv("wl-copy", text)
}

#[cfg(all(target_os = "linux", not(target_env = "ohos"), not(test)))]
fn read_text_with_wlpaste() -> Result<String> {
    read_text_with_wlpaste_using_argv("wl-paste")
}

#[cfg(any(all(test, unix), all(target_os = "linux", not(target_env = "ohos"))))]
fn read_text_with_wlpaste_using_argv(program: &str) -> Result<String> {
    let output = Command::new(program)
        .arg("--no-newline")
        .arg("--type")
        .arg("text/plain")
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .output()
        .map_err(|e| anyhow::anyhow!("Failed to run {program}: {e}"))?;
    if !output.status.success() {
        bail!("{program} exited with {}", output.status);
    }
    String::from_utf8(output.stdout).context("wl-paste returned non-UTF-8 text")
}

#[cfg(all(target_os = "linux", not(target_env = "ohos"), not(test)))]
fn write_text_with_wlcopy_using_argv(program: &str, text: &str) -> Result<()> {
    let mut child = Command::new(program)
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .map_err(|e| anyhow::anyhow!("Failed to run {program}: {e}"))?;
    if let Some(mut stdin) = child.stdin.take() {
        stdin
            .write_all(text.as_bytes())
            .map_err(|e| anyhow::anyhow!("Failed to write to {program}: {e}"))?;
    }
    // stdin is dropped here, closing the pipe so wl-copy flushes.
    let status = child
        .wait()
        .map_err(|e| anyhow::anyhow!("Failed to wait on {program}: {e}"))?;
    if !status.success() {
        bail!("{program} exited with {status}");
    }
    Ok(())
}

#[cfg(not(test))]
fn write_text_to_terminal_client(text: &str, in_tmux: bool) -> Result<()> {
    if in_tmux {
        return write_text_with_tmux(text);
    }
    write_text_with_osc52(text)
}

#[cfg(not(test))]
fn write_text_with_tmux(text: &str) -> Result<()> {
    write_text_with_tmux_using_argv("tmux", &[], text)
}

/// Ask tmux to set both its paste buffer and the attached client's clipboard.
/// Unlike DCS passthrough, `load-buffer -w` works with tmux's default
/// `allow-passthrough off` policy and returns a non-zero status when tmux
/// cannot honor the command.
#[cfg(any(not(test), all(test, unix)))]
fn write_text_with_tmux_using_argv(program: &str, prefix_args: &[&str], text: &str) -> Result<()> {
    let mut child = Command::new(program)
        .args(prefix_args)
        .args(["load-buffer", "-w", "-"])
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| anyhow::anyhow!("Failed to run tmux load-buffer -w: {e}"))?;

    let write_result = child
        .stdin
        .take()
        .context("open tmux clipboard input")
        .and_then(|mut stdin| {
            stdin
                .write_all(text.as_bytes())
                .context("write tmux clipboard input")
        });
    let output = child
        .wait_with_output()
        .context("wait for tmux load-buffer -w")?;
    write_result?;
    if !output.status.success() {
        let detail = String::from_utf8_lossy(&output.stderr);
        let detail = detail.trim();
        if detail.is_empty() {
            bail!("tmux load-buffer -w exited with {}", output.status);
        }
        bail!(
            "tmux load-buffer -w exited with {}: {detail}",
            output.status
        );
    }
    Ok(())
}

#[cfg(not(test))]
fn write_text_with_osc52(text: &str) -> Result<()> {
    let mut stdout = io::stdout();
    if !stdout.is_terminal() {
        bail!("OSC 52 clipboard fallback requires a terminal");
    }

    let sequence = osc52_sequence(text)?;
    stdout
        .write_all(sequence.as_bytes())
        .context("write OSC 52 clipboard sequence")?;
    stdout.flush().context("flush OSC 52 clipboard sequence")
}

fn osc52_sequence(text: &str) -> Result<String> {
    if text.len() > OSC52_MAX_BYTES {
        bail!("selection is too large for OSC 52 clipboard fallback");
    }

    let encoded = base64::engine::general_purpose::STANDARD.encode(text.as_bytes());
    Ok(format!("\x1b]52;c;{encoded}\x07"))
}

/// Resolve the directory pasted images should land in. Prefers
/// `~/.codewhale/clipboard-images/` so the path is stable across worktrees and
/// matches the location described in user-facing docs; falls back to
/// `<workspace>/clipboard-images/` if the home dir is unavailable.
pub(crate) fn clipboard_images_dir(workspace: &Path) -> PathBuf {
    let home = crate::config::effective_home_dir();
    clipboard_images_dir_for_home(workspace, home.as_deref())
}

fn clipboard_images_dir_for_home(workspace: &Path, home: Option<&Path>) -> PathBuf {
    if let Some(home) = home {
        return home.join(".codewhale").join("clipboard-images");
    }
    workspace.join("clipboard-images")
}

/// Encode an RGBA `ImageData` from arboard as PNG and persist it. Returns
/// the resulting path along with metadata used to render the paste hint.
#[cfg(any(
    target_os = "macos",
    target_os = "windows",
    all(target_os = "linux", not(target_env = "ohos"))
))]
fn save_image_as_png(workspace: &Path, image: &ImageData) -> Result<PastedImage> {
    save_image_as_png_in(&clipboard_images_dir(workspace), image)
}

/// Lower-level variant that writes into an explicit directory. Exposed so the
/// unit tests don't have to scribble inside the user's real home directory.
#[cfg(any(
    target_os = "macos",
    target_os = "windows",
    all(target_os = "linux", not(target_env = "ohos"))
))]
fn save_image_as_png_in(dir: &Path, image: &ImageData) -> Result<PastedImage> {
    std::fs::create_dir_all(dir).context("create clipboard-images dir")?;

    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let path = dir.join(format!("clipboard-{timestamp}.png"));

    let width = u32::try_from(image.width).context("clipboard image width too large")?;
    let height = u32::try_from(image.height).context("clipboard image height too large")?;

    // arboard hands us RGBA8 row-major. Copy into an ImageBuffer so we can
    // run it through the `image` crate's PNG encoder. We pad / truncate any
    // mismatched trailing bytes — defensive only, arboard already validates
    // the buffer length on every supported backend.
    let expected = (width as usize) * (height as usize) * 4;
    let mut rgba = image.bytes.as_ref().to_vec();
    if rgba.len() < expected {
        rgba.resize(expected, 0);
    } else if rgba.len() > expected {
        rgba.truncate(expected);
    }

    let buffer: ImageBuffer<Rgba<u8>, _> = ImageBuffer::from_raw(width, height, rgba)
        .context("clipboard image dimensions did not match buffer length")?;
    buffer
        .save_with_format(&path, image::ImageFormat::Png)
        .context("write clipboard PNG")?;

    let byte_len = std::fs::metadata(&path)
        .map(|m| m.len() as usize)
        .unwrap_or(0);
    Ok(PastedImage {
        path,
        width,
        height,
        byte_len,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    // ImageData from arboard is only available on these platforms.
    #[cfg(any(
        target_os = "macos",
        target_os = "windows",
        all(target_os = "linux", not(target_env = "ohos"))
    ))]
    use std::borrow::Cow;
    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;

    #[test]
    fn terminal_clipboard_write_does_not_wait_for_slow_transport() {
        let (transport_started_tx, transport_started_rx) = std::sync::mpsc::channel();
        let (release_transport_tx, release_transport_rx) = std::sync::mpsc::channel();
        let writer = TerminalClipboardWriter::spawn_with(move |request| {
            assert_eq!(request.text, "copied");
            assert!(!request.in_tmux);
            transport_started_tx
                .send(())
                .expect("announce transport start");
            release_transport_rx.recv().expect("release slow transport");
            Ok(())
        })
        .expect("spawn clipboard writer");
        let mut clipboard = ClipboardHandler::for_test(true, false);
        clipboard.terminal_writer = Some(writer);

        let (caller_returned_tx, caller_returned_rx) = std::sync::mpsc::channel();
        let caller = std::thread::spawn(move || {
            let result = clipboard.write_text("copied");
            caller_returned_tx
                .send((clipboard, result))
                .expect("report caller completion");
        });

        let (clipboard, result) =
            match caller_returned_rx.recv_timeout(std::time::Duration::from_millis(250)) {
                Ok(value) => value,
                Err(err) => {
                    let _ = release_transport_tx.send(());
                    caller.join().expect("join clipboard caller");
                    panic!("clipboard caller waited for slow transport: {err}");
                }
            };
        result.expect("queue clipboard write");
        transport_started_rx
            .recv_timeout(std::time::Duration::from_millis(250))
            .expect("worker started transport");
        assert!(
            clipboard.poll_write_completion().is_none(),
            "transport must remain pending until explicitly released"
        );

        release_transport_tx.send(()).expect("release transport");
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
        loop {
            if let Some(completion) = clipboard.poll_write_completion() {
                completion.expect("background clipboard completion");
                break;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "background clipboard completion timed out"
            );
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        caller.join().expect("join clipboard caller");
    }

    #[test]
    fn terminal_clipboard_write_reports_background_failure() {
        let writer =
            TerminalClipboardWriter::spawn_with(|_| bail!("terminal clipboard transport denied"))
                .expect("spawn clipboard writer");
        writer
            .enqueue("copied", false)
            .expect("queue clipboard write");

        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
        loop {
            if let Some(completion) = writer.poll_completion() {
                let err = completion.expect_err("transport should fail");
                assert!(err.contains("transport denied"), "{err}");
                break;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "background clipboard failure timed out"
            );
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
    }

    #[cfg(any(
        target_os = "macos",
        target_os = "windows",
        all(target_os = "linux", not(target_env = "ohos"))
    ))]
    fn solid_rgba(width: u16, height: u16, rgba: [u8; 4]) -> ImageData<'static> {
        let mut bytes = Vec::with_capacity((width as usize) * (height as usize) * 4);
        for _ in 0..(width as usize * height as usize) {
            bytes.extend_from_slice(&rgba);
        }
        ImageData {
            width: width as usize,
            height: height as usize,
            bytes: Cow::Owned(bytes),
        }
    }

    #[test]
    #[cfg(any(
        target_os = "macos",
        target_os = "windows",
        all(target_os = "linux", not(target_env = "ohos"))
    ))]
    fn save_image_as_png_writes_valid_png() {
        let dir = tempfile::tempdir().unwrap();
        let img = solid_rgba(8, 4, [255, 0, 0, 255]);
        let pasted = save_image_as_png_in(dir.path(), &img).expect("encode png");

        assert_eq!(pasted.width, 8);
        assert_eq!(pasted.height, 4);
        assert!(pasted.byte_len > 0);
        assert_eq!(
            pasted.path.extension().and_then(|s| s.to_str()),
            Some("png")
        );

        // The first eight bytes of any PNG file are the magic signature; if
        // we ever regress to PPM or another format this will catch it.
        let header = std::fs::read(&pasted.path).unwrap();
        assert_eq!(&header[..8], b"\x89PNG\r\n\x1a\n");
    }

    #[test]
    fn clipboard_images_dir_uses_codewhale_home_directory() {
        let home = tempfile::tempdir().unwrap();
        let workspace = tempfile::tempdir().unwrap();

        assert_eq!(
            clipboard_images_dir_for_home(workspace.path(), Some(home.path())),
            home.path().join(".codewhale").join("clipboard-images")
        );
    }

    #[test]
    fn clipboard_images_dir_falls_back_to_workspace_without_home() {
        let workspace = tempfile::tempdir().unwrap();

        assert_eq!(
            clipboard_images_dir_for_home(workspace.path(), None),
            workspace.path().join("clipboard-images")
        );
    }

    #[test]
    fn pasted_image_labels_format_correctly() {
        let p = PastedImage {
            path: PathBuf::from("/tmp/x.png"),
            width: 1024,
            height: 768,
            byte_len: 235 * 1024,
        };
        assert_eq!(p.short_label(), "1024x768 PNG");
        assert_eq!(p.size_label(), "235KB");
    }

    #[test]
    fn ssh_detection_covers_openssh_markers_and_ignores_empty_values() {
        let client = TerminalClipboardContext::from_env_values(
            Some(OsStr::new("192.0.2.10 51234 22")),
            None,
            None,
            None,
            None,
            None,
            None,
        );
        let connection = TerminalClipboardContext::from_env_values(
            None,
            Some(OsStr::new("192.0.2.10 51234 192.0.2.20 22")),
            None,
            None,
            None,
            None,
            None,
        );
        let tty = TerminalClipboardContext::from_env_values(
            None,
            None,
            Some(OsStr::new("/dev/pts/4")),
            None,
            None,
            None,
            None,
        );
        let empty = TerminalClipboardContext::from_env_values(
            Some(OsStr::new("")),
            Some(OsStr::new("")),
            Some(OsStr::new("")),
            Some(OsStr::new("")),
            Some(OsStr::new("")),
            Some(OsStr::new("")),
            Some(OsStr::new("")),
        );

        assert_eq!(client.endpoint, ClipboardEndpoint::TerminalClient);
        assert_eq!(connection.endpoint, ClipboardEndpoint::TerminalClient);
        assert_eq!(tty.endpoint, ClipboardEndpoint::TerminalClient);
        assert_eq!(empty.endpoint, ClipboardEndpoint::NativeHost);
        assert!(!empty.in_tmux);
    }

    #[test]
    fn ssh_without_display_targets_terminal_client() {
        let remote_tmux = TerminalClipboardContext::from_env_values(
            Some(OsStr::new("192.0.2.10 51234 22")),
            None,
            None,
            None,
            None,
            None,
            Some(OsStr::new("/tmp/tmux-1000/default,1,0")),
        );
        let local =
            TerminalClipboardContext::from_env_values(None, None, None, None, None, None, None);

        assert_eq!(
            remote_tmux.write_order(),
            ClipboardWriteOrder::TerminalClientOnly
        );
        assert!(!remote_tmux.permits_native_read());
        assert!(remote_tmux.requires_terminal_paste());
        assert!(remote_tmux.in_tmux);
        assert_eq!(
            local.write_order(),
            ClipboardWriteOrder::NativeHostThenTerminal
        );
        assert!(local.permits_native_read());
        assert!(!local.requires_terminal_paste());
    }

    #[test]
    fn ssh_uses_forwarded_x11_or_explicit_graphical_clipboard_endpoint() {
        let x11 = TerminalClipboardContext::from_env_values(
            None,
            Some(OsStr::new("192.0.2.10 51234 192.0.2.20 22")),
            None,
            Some(OsStr::new("localhost:10.0")),
            None,
            None,
            None,
        );
        let wayland = TerminalClipboardContext::from_env_values(
            Some(OsStr::new("192.0.2.10 51234 22")),
            None,
            None,
            None,
            Some(OsStr::new("wayland-1")),
            Some(OsStr::new("graphical")),
            None,
        );

        for context in [x11, wayland] {
            assert_eq!(context.endpoint, ClipboardEndpoint::ForwardedDisplay);
            assert_eq!(
                context.write_order(),
                ClipboardWriteOrder::NativeHostThenTerminal
            );
            assert!(context.permits_native_read());
            assert!(!context.requires_terminal_paste());
        }

        let ambient_remote = TerminalClipboardContext::from_env_values(
            Some(OsStr::new("192.0.2.10 51234 22")),
            None,
            None,
            Some(OsStr::new(":0")),
            Some(OsStr::new("wayland-0")),
            None,
            None,
        );
        assert_eq!(ambient_remote.endpoint, ClipboardEndpoint::TerminalClient);

        let forced_terminal = TerminalClipboardContext::from_env_values(
            Some(OsStr::new("192.0.2.10 51234 22")),
            None,
            None,
            Some(OsStr::new("localhost:10.0")),
            None,
            Some(OsStr::new("terminal")),
            None,
        );
        assert_eq!(forced_terminal.endpoint, ClipboardEndpoint::TerminalClient);
    }

    #[test]
    fn osc52_sequence_encodes_text_clipboard_write() {
        let sequence = osc52_sequence("hello").expect("sequence");
        assert_eq!(sequence, "\x1b]52;c;aGVsbG8=\x07");
    }

    #[test]
    fn osc52_sequence_rejects_oversized_selection() {
        let text = "x".repeat(OSC52_MAX_BYTES + 1);
        let err = osc52_sequence(&text).expect_err("oversized should fail");
        assert!(
            err.to_string().contains("too large"),
            "unexpected error: {err}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn tmux_helper_reports_command_failure() {
        let dir = tempfile::tempdir().unwrap();
        let script = dir.path().join("tmux");
        std::fs::write(
            &script,
            r#"#!/bin/sh
cat >/dev/null
echo 'clipboard denied' >&2
exit 42
"#,
        )
        .unwrap();
        let mut perms = std::fs::metadata(&script).unwrap().permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&script, perms).unwrap();

        let err = write_text_with_tmux_using_argv(script.to_str().unwrap(), &[], "copy")
            .expect_err("non-zero tmux status should fail");

        assert!(err.to_string().contains("exited with"));
        assert!(err.to_string().contains("clipboard denied"));
    }

    #[cfg(all(unix, not(target_env = "ohos")))]
    #[test]
    fn tmux_load_buffer_w_reaches_attached_client_with_default_passthrough_disabled() {
        use std::io::Read as _;

        let version = match Command::new("tmux").arg("-V").output() {
            Ok(output) if output.status.success() => output,
            _ => return,
        };
        assert!(
            String::from_utf8_lossy(&version.stdout).starts_with("tmux "),
            "unexpected tmux version output"
        );

        let nonce = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("clock after epoch")
            .as_nanos();
        let socket = format!("codewhale-clipboard-{}-{nonce}", std::process::id());

        struct TmuxServer(String);
        impl Drop for TmuxServer {
            fn drop(&mut self) {
                let _ = Command::new("tmux")
                    .args(["-L", self.0.as_str(), "kill-server"])
                    .status();
            }
        }
        let server = TmuxServer(socket);
        let started = Command::new("tmux")
            .args([
                "-L",
                server.0.as_str(),
                "-f",
                "/dev/null",
                "new-session",
                "-d",
            ])
            .status()
            .expect("start isolated tmux server");
        assert!(started.success(), "isolated tmux server should start");

        let option = |name: &str| {
            let output = Command::new("tmux")
                .args(["-L", server.0.as_str(), "show-options", "-gv", name])
                .output()
                .expect("read tmux option");
            assert!(output.status.success(), "read tmux option {name}");
            String::from_utf8(output.stdout)
                .expect("tmux option should be utf-8")
                .trim()
                .to_string()
        };
        assert_eq!(option("allow-passthrough"), "off");
        assert_eq!(option("set-clipboard"), "external");

        let pty_system = portable_pty::native_pty_system();
        let pair = pty_system
            .openpty(portable_pty::PtySize {
                rows: 24,
                cols: 80,
                pixel_width: 0,
                pixel_height: 0,
            })
            .expect("open attached-client PTY");
        let mut attach = portable_pty::CommandBuilder::new("tmux");
        for arg in ["-L", server.0.as_str(), "attach-session", "-t", "0"] {
            attach.arg(arg);
        }
        attach.env("TERM", "xterm-256color");
        let mut attached_client = pair
            .slave
            .spawn_command(attach)
            .expect("attach tmux client to PTY");
        drop(pair.slave);

        let mut reader = pair
            .master
            .try_clone_reader()
            .expect("clone attached-client PTY reader");
        let (output_tx, output_rx) = std::sync::mpsc::channel();
        let reader_thread = std::thread::spawn(move || {
            let mut chunk = [0_u8; 4096];
            loop {
                match reader.read(&mut chunk) {
                    Ok(0) | Err(_) => break,
                    Ok(len) => {
                        if output_tx.send(chunk[..len].to_vec()).is_err() {
                            break;
                        }
                    }
                }
            }
        });

        let attach_deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
        loop {
            let clients = Command::new("tmux")
                .args(["-L", server.0.as_str(), "list-clients"])
                .output()
                .expect("list attached tmux clients");
            if clients.status.success() && !clients.stdout.is_empty() {
                break;
            }
            assert!(
                std::time::Instant::now() < attach_deadline,
                "tmux client did not attach to the test PTY"
            );
            std::thread::sleep(std::time::Duration::from_millis(25));
        }
        while output_rx.try_recv().is_ok() {}

        let copied_text = "copy through default tmux";
        write_text_with_tmux_using_argv("tmux", &["-L", server.0.as_str()], copied_text)
            .expect("tmux-native clipboard request");

        let encoded = base64::engine::general_purpose::STANDARD.encode(copied_text.as_bytes());
        let expected_receipts = [
            format!("\x1b]52;;{encoded}\x07").into_bytes(),
            format!("\x1b]52;c;{encoded}\x07").into_bytes(),
            format!("\x1b]52;;{encoded}\x1b\\").into_bytes(),
            format!("\x1b]52;c;{encoded}\x1b\\").into_bytes(),
        ];
        let receipt_deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
        let mut attached_output = Vec::new();
        let receipt_received = loop {
            if expected_receipts.iter().any(|receipt| {
                attached_output
                    .windows(receipt.len())
                    .any(|window| window == receipt)
            }) {
                break true;
            }
            if std::time::Instant::now() >= receipt_deadline {
                break false;
            }
            match output_rx.recv_timeout(std::time::Duration::from_millis(50)) {
                Ok(bytes) => attached_output.extend_from_slice(&bytes),
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break false,
            }
        };

        let buffer = Command::new("tmux")
            .args(["-L", server.0.as_str(), "show-buffer"])
            .output()
            .expect("read tmux buffer");
        assert!(buffer.status.success(), "tmux buffer should be readable");
        assert_eq!(buffer.stdout, copied_text.as_bytes());

        let _ = attached_client.kill();
        let _ = attached_client.wait();
        drop(pair.master);
        drop(output_rx);
        let _ = reader_thread.join();

        assert!(
            receipt_received,
            "attached tmux client did not receive the OSC 52 clipboard request: {attached_output:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn wl_paste_helper_reads_text_from_stdout() {
        let dir = tempfile::tempdir().unwrap();
        let script = dir.path().join("wl-paste");
        std::fs::write(
            &script,
            r#"#!/bin/sh
seen_no_newline=0
seen_text_plain=0
while [ "$#" -gt 0 ]; do
  case "$1" in
    --no-newline) seen_no_newline=1 ;;
    --type)
      shift
      [ "${1:-}" = "text/plain" ] && seen_text_plain=1
      ;;
  esac
  shift
done
[ "$seen_text_plain" -eq 1 ] || exit 40
if [ "$seen_no_newline" -eq 1 ]; then
  printf 'from-wayland'
else
  printf 'from-wayland\n'
fi
"#,
        )
        .unwrap();
        let mut perms = std::fs::metadata(&script).unwrap().permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&script, perms).unwrap();

        let text = read_text_with_wlpaste_using_argv(script.to_str().unwrap())
            .expect("read text through wl-paste helper");

        assert_eq!(text, "from-wayland");
    }
}