tastty-core 0.1.0

Sans-IO core of the tastty terminal session library: VT parser, screen buffer, and byte encoders.
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
use crate::ColorTarget;
use crate::color::u8_to_x11;
use crate::host_profile::HostProfile;
use crate::screen::{ScreenEvent, XtGetTcapEntry, XtWinOpsReport};

/// Typed reply to a host query from the child process.
///
/// Each variant mirrors a query-type [`crate::ScreenEvent`] variant, providing
/// a symmetric API: receive a query event, send back a typed reply.
///
/// Use `HostReply` for supported terminal replies. For sequences this enum
/// does not cover, send raw bytes through the session.
///
/// # Example
///
/// ```no_run
/// use tastty_core::{HostReply, ScreenEvent};
///
/// fn reply_for(event: ScreenEvent) -> Option<HostReply> {
///     match event {
///         ScreenEvent::Xtversion => Some(HostReply::Xtversion("myterm(1.0)".into())),
///         ScreenEvent::DsrCursorPosition { row, col } => {
///             Some(HostReply::DsrCursorPosition { row, col })
///         }
///         _ => None,
///     }
/// }
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum HostReply {
    /// Primary Device Attributes response. Takes the complete CSI response
    /// bytes (e.g., `b"\x1b[?62;22c"`). Use [`crate::HostProfile::da1`] as
    /// a starting point or pass a custom sequence.
    Da1(Vec<u8>),
    /// Secondary Device Attributes response. Takes the complete CSI response
    /// bytes (e.g., `b"\x1b[>0;0;0c"`).
    Da2(Vec<u8>),
    /// Tertiary Device Attributes response. Takes the complete DCS response
    /// bytes (e.g., `b"\x1bP!|746173747479\x1b\\"`).
    Da3(Vec<u8>),
    /// XTVERSION response. The name is wrapped in `DCS >| ... ST`.
    Xtversion(String),
    /// DSR operating status (replies CSI 0 n = "OK").
    DsrStatus,
    /// DSR cursor position report. Row and column are 1-based.
    DsrCursorPosition {
        /// One-based cursor row.
        row: u16,
        /// One-based cursor column.
        col: u16,
    },
    /// DEC private mode report ([DECRPM/DECRQM][xterm-ctlseqs]).
    ///
    /// [xterm-ctlseqs]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
    #[doc(alias = "DECRPM")]
    #[doc(alias = "DECRQM")]
    Decrqm {
        /// DEC private mode number.
        mode: u16,
        /// Reported mode status.
        value: ModeStatus,
    },
    /// ANSI mode report.
    AnsiModeReport {
        /// ANSI mode number.
        mode: u16,
        /// Reported mode status.
        value: ModeStatus,
    },
    /// DECRQSS response. If `valid`, `response` (e.g., `b"0m"` for default
    /// SGR, `b"2 q"` for cursor style) is wrapped in `DCS 1 $ r ... ST`.
    /// Otherwise `DCS 0 $ r ST` is sent.
    ///
    /// `response` is forwarded byte-for-byte; the wire format is ASCII per
    /// [ECMA-48], but tastty-core does not assume the child obeys it.
    ///
    /// [ECMA-48]: https://ecma-international.org/publications-and-standards/standards/ecma-48/
    Decrqss {
        /// Whether the queried setting is recognized.
        valid: bool,
        /// Raw DECRQSS response payload, without DCS framing.
        response: Vec<u8>,
    },
    /// [XTGETTCAP][xterm-ctlseqs] response. One DCS frame is emitted per
    /// entry, mirroring the multi-key shape of
    /// [`ScreenEvent::XtGetTcap`].
    ///
    /// [xterm-ctlseqs]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
    #[doc(alias = "XTGETTCAP")]
    XtGetTcap {
        /// Per-key results. Encodes as one `DCS 1 + r key=value ST` frame
        /// per recognized entry and `DCS 0 + r key ST` per unknown entry.
        entries: Vec<XtGetTcapEntry>,
    },
    /// Color query response ([OSC 4/10/11/12][xterm-osc]). The carried
    /// color is expected to be [`Color::Rgb`]; its 8-bit channels are
    /// scaled to the 16-bit X11 components on encode. Non-RGB variants
    /// encode as black (`rgb:0000/0000/0000`).
    ///
    /// [`Color::Rgb`]: crate::Color::Rgb
    /// [xterm-osc]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
    ColorQuery {
        /// Color slot being reported.
        target: ColorTarget,
        /// Color to report; expected to be [`Color::Rgb`].
        ///
        /// [`Color::Rgb`]: crate::Color::Rgb
        color: crate::Color,
    },
    /// [Kitty keyboard][kitty-kbd] flags report (`CSI ? <flags> u`).
    ///
    /// [kitty-kbd]: https://sw.kovidgoyal.net/kitty/keyboard-protocol/
    #[doc(alias = "kitty keyboard")]
    KittyKeyboardFlags(u8),
    /// XTWINOPS pixel/cell-size reply (CSI 4/6/8 ; ... t).
    XtWinOpsReport(XtWinOpsReport),
}

/// Mode status for DECRPM / ANSI mode reports.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ModeStatus {
    /// Mode is not recognized by the terminal (value 0).
    NotRecognized,
    /// Mode is set/enabled (value 1).
    Set,
    /// Mode is reset/disabled (value 2).
    Reset,
    /// Mode is permanently set (value 3).
    PermanentlySet,
    /// Mode is permanently reset (value 4).
    PermanentlyReset,
}

impl ModeStatus {
    fn as_u8(self) -> u8 {
        match self {
            Self::NotRecognized => 0,
            Self::Set => 1,
            Self::Reset => 2,
            Self::PermanentlySet => 3,
            Self::PermanentlyReset => 4,
        }
    }
}

impl HostReply {
    /// Encode this reply into the raw escape sequence bytes that should be
    /// written to the PTY.
    pub fn encode(&self) -> Vec<u8> {
        match self {
            Self::Da1(bytes) | Self::Da2(bytes) | Self::Da3(bytes) => bytes.clone(),
            Self::Xtversion(name) => format!("\x1bP>|{name}\x1b\\").into_bytes(),
            Self::DsrStatus => b"\x1b[0n".to_vec(),
            Self::DsrCursorPosition { row, col } => format!("\x1b[{row};{col}R").into_bytes(),
            Self::Decrqm { mode, value } => {
                format!("\x1b[?{mode};{}$y", value.as_u8()).into_bytes()
            }
            Self::AnsiModeReport { mode, value } => {
                format!("\x1b[{mode};{}$y", value.as_u8()).into_bytes()
            }
            Self::Decrqss { valid, response } => {
                let flag: u8 = if *valid { b'1' } else { b'0' };
                let mut out = Vec::with_capacity(5 + response.len());
                out.extend_from_slice(b"\x1bP");
                out.push(flag);
                out.extend_from_slice(b"$r");
                out.extend_from_slice(response);
                out.extend_from_slice(b"\x1b\\");
                out
            }
            Self::XtGetTcap { entries } => {
                let mut out = Vec::new();
                for entry in entries {
                    let frame = match &entry.value_hex {
                        Some(val) => {
                            format!("\x1bP1+r{key}={val}\x1b\\", key = entry.key_hex).into_bytes()
                        }
                        None => format!("\x1bP0+r{key}\x1b\\", key = entry.key_hex).into_bytes(),
                    };
                    out.extend_from_slice(&frame);
                }
                out
            }
            Self::ColorQuery { target, color } => {
                let (r, g, b) = color.as_rgb().unwrap_or((0, 0, 0));
                let (r16, g16, b16) = (u8_to_x11(r), u8_to_x11(g), u8_to_x11(b));
                let osc = match target {
                    ColorTarget::Palette(idx) => {
                        format!("\x1b]4;{idx};rgb:{r16:04x}/{g16:04x}/{b16:04x}\x1b\\")
                    }
                    ColorTarget::Foreground => {
                        format!("\x1b]10;rgb:{r16:04x}/{g16:04x}/{b16:04x}\x1b\\")
                    }
                    ColorTarget::Background => {
                        format!("\x1b]11;rgb:{r16:04x}/{g16:04x}/{b16:04x}\x1b\\")
                    }
                    ColorTarget::CursorColor => {
                        format!("\x1b]12;rgb:{r16:04x}/{g16:04x}/{b16:04x}\x1b\\")
                    }
                };
                osc.into_bytes()
            }
            Self::KittyKeyboardFlags(flags) => format!("\x1b[?{flags}u").into_bytes(),
            Self::XtWinOpsReport(report) => encode_xtwinops(*report),
        }
    }
}

/// A host query that warrants a wire reply, with the per-variant payload the
/// parser computed when emitting the underlying [`ScreenEvent`].
///
/// Subset of the query-class [`ScreenEvent`] variants. Embedders receive a
/// `&HostQuery` through the `on_host_query` callback (set via
/// `SessionOptions::on_host_query`) and return a [`ReplyAction`] to send the
/// canonical reply, substitute a typed reply, or drop the response.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum HostQuery {
    /// Primary Device Attributes query (CSI c).
    Da1,
    /// Secondary Device Attributes query (CSI > c).
    Da2,
    /// Tertiary Device Attributes query (CSI = c).
    Da3,
    /// XTVERSION query (CSI > q).
    Xtversion,
    /// DSR operating status query (CSI 5 n).
    DsrStatus,
    /// DSR cursor position query (CSI 6 n). One-based row/column at parse
    /// time.
    DsrCursorPosition {
        /// One-based cursor row.
        row: u16,
        /// One-based cursor column.
        col: u16,
    },
    /// DEC private mode query (CSI ? Ps $ p), with the status the parser
    /// computed against its own mode bits.
    Decrqm {
        /// DEC private mode number.
        mode: u16,
        /// Reported mode status.
        status: ModeStatus,
    },
    /// ANSI mode query (CSI Ps $ p), with the status the parser computed.
    AnsiModeReport {
        /// ANSI mode number.
        mode: u16,
        /// Reported mode status.
        status: ModeStatus,
    },
    /// DECRQSS setting query (DCS $ q ... ST).
    Decrqss {
        /// Raw queried setting bytes (e.g. `b"m"` for SGR, `b" q"` for
        /// cursor style).
        query: Vec<u8>,
        /// DCS payload (without framing) the terminal would reply with.
        /// `None` when the query is not recognized.
        response: Option<Vec<u8>>,
    },
    /// XTGETTCAP termcap query (DCS + q ... ST). One query may carry
    /// multiple capability keys; the canonical reply emits one DCS frame
    /// per entry.
    XtGetTcap {
        /// Resolved per-key results.
        entries: Vec<XtGetTcapEntry>,
    },
    /// Color query (OSC 4/10/11/12 with `?`). The carried color is the
    /// live value the terminal would report.
    ColorQuery {
        /// Color slot being queried.
        target: ColorTarget,
        /// Color the terminal would report. Always [`Color::Rgb`] when
        /// emitted by the parser.
        ///
        /// [`Color::Rgb`]: crate::Color::Rgb
        color: crate::Color,
    },
    /// Kitty keyboard flags query (CSI ? u). `flags` is the current
    /// Kitty keyboard stack top at parse time.
    KittyKeyboardQuery {
        /// Current Kitty keyboard flag byte.
        flags: u8,
    },
    /// XTWINOPS pixel/cell-size query reply payload (CSI 14 / 16 / 18 t).
    XtWinOpsReport(XtWinOpsReport),
}

impl HostQuery {
    /// Project a [`ScreenEvent`] to its [`HostQuery`] counterpart, if any.
    ///
    /// Returns `None` for non-query events (clipboard, state changes,
    /// shell integration marks, and so on).
    #[doc(hidden)]
    #[must_use]
    pub fn from_event(event: &ScreenEvent) -> Option<Self> {
        Some(match event {
            ScreenEvent::Da1 => Self::Da1,
            ScreenEvent::Da2 => Self::Da2,
            ScreenEvent::Da3 => Self::Da3,
            ScreenEvent::Xtversion => Self::Xtversion,
            ScreenEvent::DsrStatus => Self::DsrStatus,
            ScreenEvent::DsrCursorPosition { row, col } => Self::DsrCursorPosition {
                row: *row,
                col: *col,
            },
            ScreenEvent::Decrqm { mode, status } => Self::Decrqm {
                mode: *mode,
                status: *status,
            },
            ScreenEvent::AnsiModeReport { mode, status } => Self::AnsiModeReport {
                mode: *mode,
                status: *status,
            },
            ScreenEvent::Decrqss { query, response } => Self::Decrqss {
                query: query.clone(),
                response: response.clone(),
            },
            ScreenEvent::XtGetTcap { entries } => Self::XtGetTcap {
                entries: entries.clone(),
            },
            ScreenEvent::ColorQuery { target, color } => Self::ColorQuery {
                target: *target,
                color: *color,
            },
            ScreenEvent::KittyKeyboardQuery { flags } => Self::KittyKeyboardQuery { flags: *flags },
            ScreenEvent::XtWinOpsReport(report) => Self::XtWinOpsReport(*report),
            _ => return None,
        })
    }
}

/// Decision returned by the `on_host_query` callback for one [`HostQuery`].
#[derive(Debug)]
#[non_exhaustive]
pub enum ReplyAction {
    /// Send the canonical reply
    /// ([`auto_reply_bytes`] against the session's [`HostProfile`]).
    Send,
    /// Send this typed reply instead of the canonical one.
    Replace(HostReply),
    /// Send no bytes for this query.
    Drop,
}

/// Encode the canonical wire reply for a [`HostQuery`] against a
/// [`HostProfile`].
///
/// Every [`HostQuery`] variant has a defined wire reply; this is the
/// canonical producer used by `ReplyAction::Send` and by the bare-`Parser`
/// dispatcher inside [`auto_reply_bytes`].
#[doc(hidden)]
#[must_use]
pub fn auto_reply_bytes_for_query(query: &HostQuery, host: &HostProfile) -> Vec<u8> {
    match query {
        HostQuery::Da1 => HostReply::Da1(host.da1.clone()).encode(),
        HostQuery::Da2 => HostReply::Da2(host.da2.clone()).encode(),
        HostQuery::Da3 => HostReply::Da3(host.da3.clone()).encode(),
        HostQuery::Xtversion => HostReply::Xtversion(host.xtversion_name.clone()).encode(),
        HostQuery::DsrStatus => HostReply::DsrStatus.encode(),
        HostQuery::DsrCursorPosition { row, col } => HostReply::DsrCursorPosition {
            row: *row,
            col: *col,
        }
        .encode(),
        HostQuery::Decrqm { mode, status } => HostReply::Decrqm {
            mode: *mode,
            value: *status,
        }
        .encode(),
        HostQuery::AnsiModeReport { mode, status } => HostReply::AnsiModeReport {
            mode: *mode,
            value: *status,
        }
        .encode(),
        HostQuery::Decrqss { response, .. } => match response {
            Some(payload) => HostReply::Decrqss {
                valid: true,
                response: payload.clone(),
            }
            .encode(),
            None => HostReply::Decrqss {
                valid: false,
                response: Vec::new(),
            }
            .encode(),
        },
        HostQuery::XtGetTcap { entries } => HostReply::XtGetTcap {
            entries: entries.clone(),
        }
        .encode(),
        HostQuery::ColorQuery { target, color } => HostReply::ColorQuery {
            target: *target,
            color: *color,
        }
        .encode(),
        HostQuery::KittyKeyboardQuery { flags } => HostReply::KittyKeyboardFlags(*flags).encode(),
        HostQuery::XtWinOpsReport(report) => HostReply::XtWinOpsReport(*report).encode(),
    }
}

/// Compute the default wire reply for a [`ScreenEvent`] against a
/// [`HostProfile`].
///
/// Returns `Some(bytes)` for query events the terminal would auto-reply to
/// (DA1/DA2/DA3, XTVERSION, DSR status / cursor position, DECRQM,
/// AnsiModeReport, DECRQSS, XTGETTCAP, OSC 4/10/11/12 color queries, Kitty
/// keyboard query, XTWINOPS pixel/cell-size reports). Returns `None` for
/// non-query events (state changes, clipboard, etc.) and for clipboard
/// queries: the OS clipboard is the embedder's call to make.
///
/// This is the canonical reply generator. It is pure (no `&mut`, no `Result`,
/// deterministic) and safe to call concurrently. Embedders driving a bare
/// [`Parser`](crate::Parser) call this directly with their parser's
/// `HostProfile` and write the bytes to the wire themselves; embedders using
/// the higher-level `tastty::Terminal` wrapper get this called automatically
/// from the reader thread, with per-query interception via
/// `SessionOptions::on_host_query` (see the `tastty` crate).
///
/// # Override path
///
/// To override a single query (claim DA1 = xterm in a test fixture, suppress
/// XTVERSION on a hardened deployment, gate replies on policy), match on the
/// event yourself and synthesize a bespoke [`HostReply`] for the cases you
/// want to override; fall back to `auto_reply_bytes` for everything else.
///
/// # Example
///
/// ```
/// use tastty_core::{HostProfile, host_reply::auto_reply_bytes};
/// use tastty_core::screen::ScreenEvent;
///
/// let host = HostProfile::default();
/// let bytes = auto_reply_bytes(&ScreenEvent::DsrStatus, &host);
/// assert_eq!(bytes.as_deref(), Some(&b"\x1b[0n"[..]));
/// ```
#[must_use]
pub fn auto_reply_bytes(event: &ScreenEvent, host: &HostProfile) -> Option<Vec<u8>> {
    HostQuery::from_event(event).map(|q| auto_reply_bytes_for_query(&q, host))
}

fn encode_xtwinops(report: XtWinOpsReport) -> Vec<u8> {
    match report {
        XtWinOpsReport::TextAreaPixels {
            height_pixels,
            width_pixels,
        } => format!("\x1b[4;{height_pixels};{width_pixels}t").into_bytes(),
        XtWinOpsReport::CellPixels { height, width } => {
            format!("\x1b[6;{height};{width}t").into_bytes()
        }
        XtWinOpsReport::TextAreaCells { rows, cols } => {
            format!("\x1b[8;{rows};{cols}t").into_bytes()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Color;

    #[test]
    fn da1_encodes_raw_bytes() {
        let reply = HostReply::Da1(b"\x1b[?62;22c".to_vec());
        assert_eq!(reply.encode(), b"\x1b[?62;22c");
    }

    #[test]
    fn xtversion_wraps_in_dcs() {
        let reply = HostReply::Xtversion("myterm(1.0)".into());
        assert_eq!(reply.encode(), b"\x1bP>|myterm(1.0)\x1b\\");
    }

    #[test]
    fn dsr_status_is_ok() {
        assert_eq!(HostReply::DsrStatus.encode(), b"\x1b[0n");
    }

    #[test]
    fn dsr_cursor_position_is_1_based() {
        let reply = HostReply::DsrCursorPosition { row: 5, col: 10 };
        assert_eq!(reply.encode(), b"\x1b[5;10R");
    }

    #[test]
    fn decrqm_set() {
        let reply = HostReply::Decrqm {
            mode: 2004,
            value: ModeStatus::Reset,
        };
        assert_eq!(reply.encode(), b"\x1b[?2004;2$y");
    }

    #[test]
    fn decrqm_not_recognized() {
        let reply = HostReply::Decrqm {
            mode: 9999,
            value: ModeStatus::NotRecognized,
        };
        assert_eq!(reply.encode(), b"\x1b[?9999;0$y");
    }

    #[test]
    fn ansi_mode_report_no_question_mark() {
        let reply = HostReply::AnsiModeReport {
            mode: 4,
            value: ModeStatus::Set,
        };
        assert_eq!(reply.encode(), b"\x1b[4;1$y");
    }

    #[test]
    fn decrqss_valid_response() {
        let reply = HostReply::Decrqss {
            valid: true,
            response: b"0m".to_vec(),
        };
        assert_eq!(reply.encode(), b"\x1bP1$r0m\x1b\\");
    }

    #[test]
    fn decrqss_invalid_response() {
        let reply = HostReply::Decrqss {
            valid: false,
            response: Vec::new(),
        };
        assert_eq!(reply.encode(), b"\x1bP0$r\x1b\\");
    }

    #[test]
    fn decrqss_propagates_non_ascii_payload_without_replacement() {
        // Regression: auto_reply_bytes previously called from_utf8_lossy on
        // the parser-emitted payload, replacing bytes >= 0x80 with U+FFFD
        // (0xEF 0xBF 0xBD) before they reached the wire.
        let host = HostProfile::default();
        let event = ScreenEvent::Decrqss {
            query: b"m".to_vec(),
            response: Some(vec![0xC3, 0x28, 0xFF, 0x80]),
        };
        let bytes = auto_reply_bytes(&event, &host).expect("DECRQSS auto-reply");
        assert_eq!(bytes.as_slice(), b"\x1bP1$r\xC3\x28\xFF\x80\x1b\\");
    }

    #[test]
    fn xtgettcap_encodes_single_entry_found() {
        let reply = HostReply::XtGetTcap {
            entries: vec![XtGetTcapEntry {
                key_hex: "544E".into(),
                value_hex: Some("787465726D".into()),
            }],
        };
        assert_eq!(reply.encode(), b"\x1bP1+r544E=787465726D\x1b\\");
    }

    #[test]
    fn xtgettcap_encodes_single_entry_not_found() {
        let reply = HostReply::XtGetTcap {
            entries: vec![XtGetTcapEntry {
                key_hex: "544E".into(),
                value_hex: None,
            }],
        };
        assert_eq!(reply.encode(), b"\x1bP0+r544E\x1b\\");
    }

    #[test]
    fn xtgettcap_encodes_multiple_entries() {
        let reply = HostReply::XtGetTcap {
            entries: vec![
                XtGetTcapEntry {
                    key_hex: "544E".into(),
                    value_hex: Some("746173747479".into()),
                },
                XtGetTcapEntry {
                    key_hex: "ZZZZ".into(),
                    value_hex: None,
                },
            ],
        };
        assert_eq!(
            reply.encode(),
            b"\x1bP1+r544E=746173747479\x1b\\\x1bP0+rZZZZ\x1b\\"
        );
    }

    #[test]
    fn color_query_foreground() {
        let reply = HostReply::ColorQuery {
            target: ColorTarget::Foreground,
            color: Color::Rgb(255, 0, 128),
        };
        let encoded = reply.encode();
        let expected = format!(
            "\x1b]10;rgb:{:04x}/{:04x}/{:04x}\x1b\\",
            0xffff,
            0,
            128 * 257
        );
        assert_eq!(encoded, expected.as_bytes());
    }

    #[test]
    fn color_query_palette() {
        let reply = HostReply::ColorQuery {
            target: ColorTarget::Palette(42),
            color: Color::Rgb(0, 0, 0),
        };
        assert_eq!(reply.encode(), b"\x1b]4;42;rgb:0000/0000/0000\x1b\\");
    }

    #[test]
    fn color_query_background() {
        let reply = HostReply::ColorQuery {
            target: ColorTarget::Background,
            color: Color::Rgb(255, 255, 255),
        };
        assert_eq!(reply.encode(), b"\x1b]11;rgb:ffff/ffff/ffff\x1b\\");
    }

    #[test]
    fn color_query_cursor() {
        let reply = HostReply::ColorQuery {
            target: ColorTarget::CursorColor,
            color: Color::Rgb(229, 229, 229),
        };
        let expected = format!(
            "\x1b]12;rgb:{:04x}/{:04x}/{:04x}\x1b\\",
            229 * 257,
            229 * 257,
            229 * 257
        );
        assert_eq!(reply.encode(), expected.as_bytes());
    }

    #[test]
    fn kitty_keyboard_flags() {
        let reply = HostReply::KittyKeyboardFlags(3);
        assert_eq!(reply.encode(), b"\x1b[?3u");
    }

    #[test]
    fn xtwinops_text_area_pixels() {
        let reply = HostReply::XtWinOpsReport(XtWinOpsReport::TextAreaPixels {
            height_pixels: 480,
            width_pixels: 640,
        });
        assert_eq!(reply.encode(), b"\x1b[4;480;640t");
    }

    use crate::host_profile::HostProfile;
    use crate::screen::{ScreenEvent, XtGetTcapEntry, XtWinOpsReport};

    #[test]
    fn auto_reply_da1_uses_host_profile() {
        let host = HostProfile {
            da1: b"\x1b[?42c".to_vec(),
            ..HostProfile::default()
        };
        assert_eq!(
            auto_reply_bytes(&ScreenEvent::Da1, &host).as_deref(),
            Some(&b"\x1b[?42c"[..])
        );
    }

    #[test]
    fn auto_reply_da2_uses_host_profile() {
        let host = HostProfile {
            da2: b"\x1b[>1;2;3c".to_vec(),
            ..HostProfile::default()
        };
        assert_eq!(
            auto_reply_bytes(&ScreenEvent::Da2, &host).as_deref(),
            Some(&b"\x1b[>1;2;3c"[..])
        );
    }

    #[test]
    fn auto_reply_da3_uses_host_profile() {
        let host = HostProfile::default();
        assert_eq!(
            auto_reply_bytes(&ScreenEvent::Da3, &host).as_deref(),
            Some(&host.da3[..])
        );
    }

    #[test]
    fn auto_reply_xtversion_wraps_name_in_dcs() {
        let host = HostProfile {
            xtversion_name: "tastty-test(0)".into(),
            ..HostProfile::default()
        };
        assert_eq!(
            auto_reply_bytes(&ScreenEvent::Xtversion, &host).as_deref(),
            Some(&b"\x1bP>|tastty-test(0)\x1b\\"[..])
        );
    }

    #[test]
    fn auto_reply_dsr_status_is_constant() {
        let host = HostProfile::default();
        assert_eq!(
            auto_reply_bytes(&ScreenEvent::DsrStatus, &host).as_deref(),
            Some(&b"\x1b[0n"[..])
        );
    }

    #[test]
    fn auto_reply_dsr_cursor_position_uses_event_payload() {
        let host = HostProfile::default();
        let event = ScreenEvent::DsrCursorPosition { row: 5, col: 10 };
        assert_eq!(
            auto_reply_bytes(&event, &host).as_deref(),
            Some(&b"\x1b[5;10R"[..])
        );
    }

    #[test]
    fn auto_reply_decrqm_uses_event_payload() {
        let host = HostProfile::default();
        let event = ScreenEvent::Decrqm {
            mode: 2004,
            status: ModeStatus::Set,
        };
        assert_eq!(
            auto_reply_bytes(&event, &host).as_deref(),
            Some(&b"\x1b[?2004;1$y"[..])
        );
    }

    #[test]
    fn auto_reply_ansi_mode_uses_event_payload() {
        let host = HostProfile::default();
        let event = ScreenEvent::AnsiModeReport {
            mode: 4,
            status: ModeStatus::Reset,
        };
        assert_eq!(
            auto_reply_bytes(&event, &host).as_deref(),
            Some(&b"\x1b[4;2$y"[..])
        );
    }

    #[test]
    fn auto_reply_decrqss_valid_frames_payload() {
        let host = HostProfile::default();
        let event = ScreenEvent::Decrqss {
            query: b"m".to_vec(),
            response: Some(b"0m".to_vec()),
        };
        assert_eq!(
            auto_reply_bytes(&event, &host).as_deref(),
            Some(&b"\x1bP1$r0m\x1b\\"[..])
        );
    }

    #[test]
    fn auto_reply_decrqss_unknown_returns_zero_frame() {
        let host = HostProfile::default();
        let event = ScreenEvent::Decrqss {
            query: b"zzz".to_vec(),
            response: None,
        };
        assert_eq!(
            auto_reply_bytes(&event, &host).as_deref(),
            Some(&b"\x1bP0$r\x1b\\"[..])
        );
    }

    #[test]
    fn auto_reply_xtgettcap_concatenates_entries() {
        let host = HostProfile::default();
        let event = ScreenEvent::XtGetTcap {
            entries: vec![
                XtGetTcapEntry {
                    key_hex: "544E".into(),
                    value_hex: Some("746173747479".into()),
                },
                XtGetTcapEntry {
                    key_hex: "ZZZZ".into(),
                    value_hex: None,
                },
            ],
        };
        assert_eq!(
            auto_reply_bytes(&event, &host).as_deref(),
            Some(&b"\x1bP1+r544E=746173747479\x1b\\\x1bP0+rZZZZ\x1b\\"[..])
        );
    }

    #[test]
    fn auto_reply_color_query_uses_event_color() {
        let host = HostProfile::default();
        let event = ScreenEvent::ColorQuery {
            target: ColorTarget::Foreground,
            color: Color::Rgb(255, 255, 255),
        };
        assert_eq!(
            auto_reply_bytes(&event, &host).as_deref(),
            Some(&b"\x1b]10;rgb:ffff/ffff/ffff\x1b\\"[..])
        );
    }

    #[test]
    fn auto_reply_kitty_keyboard_query_uses_event_flags() {
        let host = HostProfile::default();
        let event = ScreenEvent::KittyKeyboardQuery { flags: 7 };
        assert_eq!(
            auto_reply_bytes(&event, &host).as_deref(),
            Some(&b"\x1b[?7u"[..])
        );
    }

    #[test]
    fn auto_reply_xtwinops_text_area_pixels() {
        let host = HostProfile::default();
        let event = ScreenEvent::XtWinOpsReport(XtWinOpsReport::TextAreaPixels {
            height_pixels: 480,
            width_pixels: 640,
        });
        assert_eq!(
            auto_reply_bytes(&event, &host).as_deref(),
            Some(&b"\x1b[4;480;640t"[..])
        );
    }

    #[test]
    fn auto_reply_xtwinops_cell_pixels() {
        let host = HostProfile::default();
        let event = ScreenEvent::XtWinOpsReport(XtWinOpsReport::CellPixels {
            height: 24,
            width: 12,
        });
        assert_eq!(
            auto_reply_bytes(&event, &host).as_deref(),
            Some(&b"\x1b[6;24;12t"[..])
        );
    }

    #[test]
    fn auto_reply_xtwinops_text_area_cells() {
        let host = HostProfile::default();
        let event =
            ScreenEvent::XtWinOpsReport(XtWinOpsReport::TextAreaCells { rows: 24, cols: 80 });
        assert_eq!(
            auto_reply_bytes(&event, &host).as_deref(),
            Some(&b"\x1b[8;24;80t"[..])
        );
    }

    #[test]
    fn auto_reply_clipboard_query_returns_none() {
        let host = HostProfile::default();
        let event = ScreenEvent::ClipboardQuery {
            targets: vec![crate::ClipboardTarget::Primary],
        };
        assert!(auto_reply_bytes(&event, &host).is_none());
    }

    #[test]
    fn auto_reply_state_change_returns_none() {
        let host = HostProfile::default();
        assert!(auto_reply_bytes(&ScreenEvent::Bell, &host).is_none());
        assert!(auto_reply_bytes(&ScreenEvent::TitleChanged, &host).is_none());
    }

    #[test]
    fn host_query_from_event_maps_query_variants() {
        assert!(matches!(
            HostQuery::from_event(&ScreenEvent::Da1),
            Some(HostQuery::Da1)
        ));
        assert!(matches!(
            HostQuery::from_event(&ScreenEvent::Xtversion),
            Some(HostQuery::Xtversion)
        ));
        let cpr = ScreenEvent::DsrCursorPosition { row: 7, col: 3 };
        assert_eq!(
            HostQuery::from_event(&cpr),
            Some(HostQuery::DsrCursorPosition { row: 7, col: 3 })
        );
    }

    #[test]
    fn host_query_from_event_skips_non_query_variants() {
        assert!(HostQuery::from_event(&ScreenEvent::Bell).is_none());
        assert!(HostQuery::from_event(&ScreenEvent::TitleChanged).is_none());
        let clip = ScreenEvent::ClipboardQuery {
            targets: vec![crate::ClipboardTarget::Primary],
        };
        assert!(HostQuery::from_event(&clip).is_none());
    }

    #[test]
    fn auto_reply_bytes_for_query_matches_event_path() {
        let host = HostProfile::default();
        let event = ScreenEvent::Decrqm {
            mode: 2004,
            status: ModeStatus::Set,
        };
        let via_query = HostQuery::from_event(&event)
            .map(|q| auto_reply_bytes_for_query(&q, &host))
            .expect("Decrqm is a host query");
        let via_event = auto_reply_bytes(&event, &host).expect("Decrqm event has a reply");
        assert_eq!(via_query, via_event);
    }
}