croft-software 0.2.132

VSCode-style TUI written in Rust
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
use std::time::Instant;

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Widget},
};

use crate::remote_connect::PromptKind;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DialogPhase {
    Connecting,
    AwaitingPassword,
    AwaitingPassphrase,
    AwaitingVerificationCode,
    AwaitingHostKeyConfirmation,
    AwaitingGeneric,
    /// The fast cross-build path is unavailable; the user chooses between
    /// the slow compile-on-remote fallback and aborting to run
    /// `croft setup-cross` locally first.
    AwaitingFallbackConfirmation,
    Installing,
    Authenticated,
    Failed,
}

impl DialogPhase {
    pub fn awaits_input(&self) -> bool {
        matches!(
            self,
            DialogPhase::AwaitingPassword
                | DialogPhase::AwaitingPassphrase
                | DialogPhase::AwaitingVerificationCode
                | DialogPhase::AwaitingHostKeyConfirmation
                | DialogPhase::AwaitingGeneric
                | DialogPhase::AwaitingFallbackConfirmation
        )
    }

    pub fn is_terminal(&self) -> bool {
        matches!(self, DialogPhase::Authenticated | DialogPhase::Failed)
    }
}

pub struct ConnectDialog {
    pub host: String,
    pub phase: DialogPhase,
    pub prompt_text: String,
    pub input: String,
    pub status_line: String,
    pub error: Option<String>,
    pub show_logs: bool,
    pub logs: Vec<String>,
    pub last_area: Rect,
    pub last_inner: Rect,
    pub toggle_logs_btn: Rect,
    pub cancel_btn: Rect,
    pub submit_btn: Rect,
    pub field_rect: Rect,
    pub caret_pos: Option<(u16, u16)>,
    pub submitted: bool,
    pub install_started_at: Option<Instant>,
    /// What a yes to the slow remote compile also installs (#950), drawn
    /// in the dialog itself above the answer box while it is asked, so it
    /// is seen before the answer at any terminal size: the log panel that
    /// could hold it is the first thing a short terminal drops.
    pub notes: Vec<String>,
    /// Whether the last frame drew every row of `notes` and the answer box
    /// under them. A yes is only taken once it has (#950 review): on a
    /// window too short to show it all, the question is not yet asked.
    pub notes_shown: bool,
    /// The active theme: drives the gradient border on Black and every
    /// chrome color. Set by the app before render.
    pub theme: crate::theme::Theme,
}

const SPINNER_FRAMES: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];

const MAX_LOG_LINES: usize = 1000;
const ACCENT: Color = Color::Rgb(0x4e, 0x9a, 0xff);
const TEAL: Color = Color::Rgb(0x3e, 0xd8, 0xc4);
const RED: Color = Color::Rgb(0xff, 0x6b, 0x6b);
const PANEL_BG: Color = Color::Rgb(0x14, 0x1a, 0x24);
const FIELD_BG: Color = Color::Rgb(0x0b, 0x12, 0x1c);

impl ConnectDialog {
    pub fn new(host: String) -> Self {
        Self {
            host,
            phase: DialogPhase::Connecting,
            prompt_text: String::from("Establishing SSH connection"),
            input: String::new(),
            status_line: String::from("Negotiating with the remote host"),
            error: None,
            show_logs: false,
            logs: Vec::new(),
            last_area: Rect::default(),
            last_inner: Rect::default(),
            toggle_logs_btn: Rect::default(),
            cancel_btn: Rect::default(),
            submit_btn: Rect::default(),
            field_rect: Rect::default(),
            caret_pos: None,
            submitted: false,
            install_started_at: None,
            notes: Vec::new(),
            notes_shown: false,
            theme: crate::theme::Theme::default(),
        }
    }

    pub fn cursor_screen_pos(&self) -> Option<(u16, u16)> {
        self.caret_pos
    }

    fn spinner_glyph(&self) -> char {
        let frames = SPINNER_FRAMES.len() as u128;
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis())
            .unwrap_or(0);
        let idx = ((now / 90) % frames) as usize;
        SPINNER_FRAMES[idx]
    }

    pub fn push_log(&mut self, chunk: &str) {
        for line in chunk.split('\n') {
            if line.is_empty() {
                continue;
            }
            self.logs.push(line.to_string());
        }
        if self.logs.len() > MAX_LOG_LINES {
            let drop = self.logs.len() - MAX_LOG_LINES;
            self.logs.drain(..drop);
        }
    }

    pub fn set_prompt(&mut self, kind: PromptKind, line: String) {
        let trimmed = line.trim().to_string();
        let new_phase = match kind {
            PromptKind::Password => DialogPhase::AwaitingPassword,
            PromptKind::Passphrase => DialogPhase::AwaitingPassphrase,
            PromptKind::VerificationCode => DialogPhase::AwaitingVerificationCode,
            PromptKind::HostKeyConfirmation => DialogPhase::AwaitingHostKeyConfirmation,
            PromptKind::Generic => DialogPhase::AwaitingGeneric,
        };
        let same_prompt = self.phase == new_phase && self.prompt_text == trimmed;
        self.prompt_text = trimmed;
        self.phase = new_phase;
        if !same_prompt {
            self.input.clear();
            self.status_line = default_status_for(&self.phase, &self.host);
            self.submitted = false;
        } else if self.submitted {
            self.input.clear();
            self.status_line = match self.phase {
                DialogPhase::AwaitingPassword => {
                    String::from("Authentication failed, type the password again")
                }
                DialogPhase::AwaitingPassphrase => String::from("Passphrase rejected, try again"),
                DialogPhase::AwaitingVerificationCode => String::from("Code rejected, try again"),
                _ => default_status_for(&self.phase, &self.host),
            };
            self.submitted = false;
        }
    }

    pub fn set_authenticated(&mut self) {
        self.phase = DialogPhase::Authenticated;
        self.status_line = format!("Authenticated to {}", self.host);
        self.input.clear();
    }

    /// The installer cannot use the fast cross-build path and asks whether
    /// to compile on the remote box instead (slow) or abort so the user can
    /// run `croft setup-cross` and reconnect for the fast install. `notes`
    /// says what else a yes installs; the dialog shows it above the answer.
    pub fn set_fallback_prompt(&mut self, reason: &str, notes: &[&str]) {
        self.phase = DialogPhase::AwaitingFallbackConfirmation;
        self.prompt_text = format!("Fast install unavailable: {reason}");
        self.notes = notes.iter().map(|n| n.to_string()).collect();
        self.notes_shown = false;
        self.status_line = default_status_for(&self.phase, &self.host);
        self.input.clear();
        self.submitted = false;
        self.show_logs = true;
    }

    /// Switch to the installing phase: reveal the log panel and start the
    /// elapsed-time clock. Entered once credentials are accepted, or when
    /// the user consents to the slow compile-on-remote fallback.
    pub fn set_installing(&mut self) {
        self.phase = DialogPhase::Installing;
        self.status_line = format!("Preparing remote croft on {}", self.host);
        self.input.clear();
        self.show_logs = true;
        self.submitted = false;
        self.install_started_at = Some(Instant::now());
    }

    pub fn set_failed(&mut self, detail: String) {
        self.phase = DialogPhase::Failed;
        self.status_line = format!("Connection to {} failed", self.host);
        self.error = Some(detail);
        self.input.clear();
    }

    pub fn toggle_logs(&mut self) {
        self.show_logs = !self.show_logs;
    }

    pub fn push_input_char(&mut self, c: char) {
        if !self.phase.awaits_input() {
            return;
        }
        self.input.push(c);
    }

    pub fn pop_input_char(&mut self) {
        if !self.phase.awaits_input() {
            return;
        }
        self.input.pop();
    }

    pub fn clear_input(&mut self) {
        self.input.clear();
    }

    pub fn input_for_submit(&self) -> String {
        if matches!(self.phase, DialogPhase::AwaitingHostKeyConfirmation) && self.input.is_empty() {
            String::from("yes")
        } else {
            self.input.clone()
        }
    }

    /// True when the active prompt hides what the user types (passwords,
    /// passphrases). 2FA codes and host-key confirmations are visible.
    pub fn input_is_secret(&self) -> bool {
        matches!(
            self.phase,
            DialogPhase::AwaitingPassword | DialogPhase::AwaitingPassphrase
        )
    }
}

fn log_line_color(line: &str, theme: crate::theme::Theme) -> Color {
    let lower = line.to_ascii_lowercase();
    if lower.contains("error") || lower.contains("failed") || lower.contains("permission denied") {
        return theme.ui(RED);
    }
    if lower.contains("warning") || lower.contains("warn:") {
        return theme.ui(Color::Rgb(0xf9, 0xc8, 0x5b));
    }
    if lower.starts_with("installed ")
        || lower.contains("install complete")
        || lower.contains("up to date")
        || lower.contains("authenticated")
    {
        return theme.ui(TEAL);
    }
    if lower.starts_with("compiling ")
        || lower.starts_with("downloading ")
        || lower.starts_with("downloaded ")
        || lower.starts_with("updating ")
        || lower.starts_with("running ")
        || lower.starts_with("installing ")
        || lower.starts_with("syncing ")
        || lower.starts_with("rsyncing ")
        || lower.starts_with("cross-compiling ")
        || lower.starts_with("hashing ")
        || lower.starts_with("checking ")
        || lower.starts_with("adopting ")
        || lower.starts_with("local source stamp")
    {
        return theme.ui(ACCENT);
    }
    theme.ui(Color::Rgb(0xb4, 0xbe, 0xc8))
}

fn default_status_for(phase: &DialogPhase, host: &str) -> String {
    match phase {
        DialogPhase::AwaitingPassword => format!("{} wants your password", host),
        DialogPhase::AwaitingPassphrase => String::from("Enter the key passphrase"),
        DialogPhase::AwaitingVerificationCode => String::from("Enter the 2FA code"),
        DialogPhase::AwaitingHostKeyConfirmation => {
            String::from("First-time host key, type yes to continue")
        }
        DialogPhase::AwaitingGeneric => String::from("Server prompt"),
        DialogPhase::AwaitingFallbackConfirmation => format!(
            "Compile on {} instead? Slow — quitting to run `croft setup-cross` once is much faster",
            host
        ),
        _ => String::new(),
    }
}

/// The top row of a fallback prompt too tall for the window (#950 review):
/// a yes is held until the whole question has been on screen.
const TOO_SHORT_FOR_FALLBACK: &str = "Make the window taller to read the whole question";

/// The fallback prompt's notes as the rows they take at `width` columns:
/// a heading, then each note word-wrapped behind a `- ` lead (#950).
fn note_rows(notes: &[String], width: usize) -> Vec<String> {
    if notes.is_empty() {
        return Vec::new();
    }
    let room = width.saturating_sub(2).max(1);
    let mut rows = vec![String::from("A remote compile may also:")];
    for note in notes {
        let mut line = String::new();
        let mut first = true;
        for word in note.split_whitespace() {
            let len = line.chars().count();
            if len > 0 && len + 1 + word.chars().count() > room {
                let lead = if first { "- " } else { "  " };
                rows.push(format!("{lead}{}", std::mem::take(&mut line)));
                first = false;
            }
            if !line.is_empty() {
                line.push(' ');
            }
            line.push_str(word);
        }
        if !line.is_empty() {
            let lead = if first { "- " } else { "  " };
            rows.push(format!("{lead}{line}"));
        }
    }
    rows
}

impl Widget for &mut ConnectDialog {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let installing = matches!(self.phase, DialogPhase::Installing);
        let target_width: u16 = if installing { 100 } else { 72 };
        let width = area.width.min(target_width).max(48);
        let notes = if matches!(self.phase, DialogPhase::AwaitingFallbackConfirmation) {
            note_rows(&self.notes, width.saturating_sub(2) as usize)
        } else {
            Vec::new()
        };
        // The notes sit between the prompt line and the answer box, one
        // blank row below them, and the dialog grows to hold them.
        let notes_h = if notes.is_empty() {
            0
        } else {
            notes.len() as u16 + 1
        };
        let (base_h, logs_h): (u16, u16) = if installing {
            (5, 24)
        } else if self.show_logs {
            (12 + notes_h, 12)
        } else {
            (12 + notes_h, 0)
        };
        let height = (base_h + logs_h).min(area.height.saturating_sub(2));
        let x = area.x + area.width.saturating_sub(width) / 2;
        let y = area.y + area.height.saturating_sub(height) / 2;
        let rect = Rect {
            x,
            y,
            width,
            height,
        };
        Clear.render(rect, buf);
        for dy in 0..rect.height {
            for dx in 0..rect.width {
                let cell = &mut buf[(rect.x + dx, rect.y + dy)];
                cell.set_char(' ');
                cell.set_style(Style::default().bg(self.theme.ui(PANEL_BG)));
            }
        }
        let title_style = Style::default()
            .fg(self.theme.ui(Color::White))
            .bg(self.theme.ui(PANEL_BG))
            .add_modifier(Modifier::BOLD);
        let title = Span::styled(format!(" Connect — {} ", self.host), title_style);
        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(
                Style::default()
                    .fg(self.theme.ui(ACCENT))
                    .bg(self.theme.ui(PANEL_BG)),
            )
            .title(title.clone());
        let inner = block.inner(rect);
        block.render(rect, buf);
        // Black theme: overpaint the solid border with the gradient, then
        // re-stamp the title the gradient top edge just covered.
        if self.theme.framed_overlays() {
            crate::widgets::surface::paint_overlay_frame(buf, rect, self.theme);
            buf.set_span(rect.x + 1, rect.y, &title, title.width() as u16);
        }
        self.last_area = rect;
        self.last_inner = inner;

        if inner.width == 0 || inner.height == 0 {
            return;
        }

        self.caret_pos = None;
        self.field_rect = Rect::default();

        let mut cy = inner.y;
        let phase_label = match self.phase {
            DialogPhase::Connecting => "Connecting",
            DialogPhase::AwaitingPassword => "Password",
            DialogPhase::AwaitingPassphrase => "Passphrase",
            DialogPhase::AwaitingVerificationCode => "2FA",
            DialogPhase::AwaitingHostKeyConfirmation => "Host key",
            DialogPhase::AwaitingGeneric => "Prompt",
            DialogPhase::AwaitingFallbackConfirmation => "Slow install?",
            DialogPhase::Installing => "Installing",
            DialogPhase::Authenticated => "Done",
            DialogPhase::Failed => "Failed",
        };
        let phase_color = match self.phase {
            DialogPhase::Authenticated => self.theme.ui(TEAL),
            DialogPhase::Failed => self.theme.ui(RED),
            _ => self.theme.ui(ACCENT),
        };
        let indicator = if self.phase.is_terminal() {
            '●'
        } else {
            self.spinner_glyph()
        };
        let mut header_spans: Vec<Span<'_>> = vec![
            Span::styled(
                format!(" {indicator} "),
                Style::default().fg(phase_color).bg(self.theme.ui(PANEL_BG)),
            ),
            Span::styled(
                phase_label,
                Style::default()
                    .fg(self.theme.ui(Color::White))
                    .bg(self.theme.ui(PANEL_BG))
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                format!("  {}", self.status_line),
                Style::default()
                    .fg(self.theme.ui(Color::Rgb(0xb4, 0xbe, 0xc8)))
                    .bg(self.theme.ui(PANEL_BG)),
            ),
        ];
        if installing && let Some(started) = self.install_started_at {
            let secs = started.elapsed().as_secs();
            let label = format!("  {:02}:{:02}", secs / 60, secs % 60);
            header_spans.push(Span::styled(
                label,
                Style::default()
                    .fg(self.theme.ui(TEAL))
                    .bg(self.theme.ui(PANEL_BG))
                    .add_modifier(Modifier::BOLD),
            ));
        }
        buf.set_line(inner.x, cy, &Line::from(header_spans), inner.width);
        cy = cy.saturating_add(2);

        if !installing && cy < inner.y + inner.height {
            buf.set_line(
                inner.x,
                cy,
                &Line::from(vec![Span::styled(
                    truncate(&self.prompt_text, inner.width as usize),
                    Style::default()
                        .fg(self.theme.ui(Color::Rgb(0xe6, 0xed, 0xf5)))
                        .bg(self.theme.ui(PANEL_BG)),
                )]),
                inner.width,
            );
            cy = cy.saturating_add(2);
        }

        // What a yes installs, above the answer box: drawn before it, so
        // whenever the box is on screen the notes above it are too.
        let mut notes_drawn = 0;
        if !notes.is_empty() {
            let style = Style::default()
                .fg(self.theme.ui(Color::Rgb(0xe6, 0xed, 0xf5)))
                .bg(self.theme.ui(PANEL_BG));
            for row in &notes {
                if cy >= inner.y + inner.height {
                    break;
                }
                buf.set_stringn(inner.x, cy, row, inner.width as usize, style);
                cy = cy.saturating_add(1);
                notes_drawn += 1;
            }
            cy = cy.saturating_add(1);
        }

        if self.phase.awaits_input() && cy + 1 < inner.y + inner.height {
            let field_w = inner.width.saturating_sub(2);
            let field_rect = Rect {
                x: inner.x + 1,
                y: cy,
                width: field_w,
                height: 1,
            };
            for dx in 0..field_rect.width {
                let cell = &mut buf[(field_rect.x + dx, field_rect.y)];
                cell.set_char(' ');
                cell.set_style(Style::default().bg(self.theme.ui(FIELD_BG)));
            }
            let shown_text: String = if self.input_is_secret() {
                "•".repeat(self.input.chars().count())
            } else {
                self.input.clone()
            };
            let cursor_glyph = '▌';
            let shown = truncate(&shown_text, field_w.saturating_sub(1) as usize);
            buf.set_string(
                field_rect.x,
                field_rect.y,
                &shown,
                Style::default()
                    .fg(self.theme.ui(Color::White))
                    .bg(self.theme.ui(FIELD_BG)),
            );
            let caret_col = field_rect
                .x
                .saturating_add(shown.chars().count() as u16)
                .min(field_rect.x + field_rect.width.saturating_sub(1));
            if self.input.is_empty() {
                let placeholder = match self.phase {
                    DialogPhase::AwaitingPassword => "  type your password and press Enter",
                    DialogPhase::AwaitingPassphrase => "  type your key passphrase and press Enter",
                    DialogPhase::AwaitingVerificationCode => "  type the 2FA code and press Enter",
                    DialogPhase::AwaitingHostKeyConfirmation => {
                        "  type yes and press Enter to trust this host"
                    }
                    DialogPhase::AwaitingGeneric => "  type a response and press Enter",
                    DialogPhase::AwaitingFallbackConfirmation => {
                        "  y + Enter compiles on the remote; Enter alone cancels"
                    }
                    _ => "",
                };
                if !placeholder.is_empty() {
                    let truncated =
                        truncate(placeholder, field_rect.width.saturating_sub(2) as usize);
                    buf.set_string(
                        caret_col + 1,
                        field_rect.y,
                        &truncated,
                        Style::default()
                            .fg(self.theme.ui(Color::Rgb(0x6b, 0x74, 0x82)))
                            .bg(self.theme.ui(FIELD_BG))
                            .add_modifier(Modifier::ITALIC),
                    );
                }
            }
            buf.set_string(
                caret_col,
                field_rect.y,
                cursor_glyph.to_string(),
                Style::default()
                    .fg(self.theme.ui(ACCENT))
                    .bg(self.theme.ui(FIELD_BG))
                    .add_modifier(Modifier::BOLD),
            );
            self.field_rect = field_rect;
            self.caret_pos = Some((caret_col, field_rect.y));
            cy = cy.saturating_add(2);
        }

        if let Some(err) = &self.error
            && cy < inner.y + inner.height
        {
            buf.set_line(
                inner.x,
                cy,
                &Line::from(vec![Span::styled(
                    truncate(err, inner.width as usize),
                    Style::default()
                        .fg(self.theme.ui(RED))
                        .bg(self.theme.ui(PANEL_BG)),
                )]),
                inner.width,
            );
            cy = cy.saturating_add(2);
        }

        self.notes_shown = notes_drawn == notes.len() && self.field_rect.height > 0;
        if !notes.is_empty() && !self.notes_shown {
            // The question doesn't fit, and a yes is held until it does: say
            // so on the top row, the one row a short window always shows.
            let style = Style::default()
                .fg(self.theme.ui(RED))
                .bg(self.theme.ui(PANEL_BG))
                .add_modifier(Modifier::BOLD);
            for dx in 0..inner.width {
                let cell = &mut buf[(inner.x + dx, inner.y)];
                cell.set_char(' ');
                cell.set_style(Style::default().bg(self.theme.ui(PANEL_BG)));
            }
            buf.set_stringn(
                inner.x + 1,
                inner.y,
                TOO_SHORT_FOR_FALLBACK,
                inner.width.saturating_sub(1) as usize,
                style,
            );
        }
        let body_end = cy;
        let footer_y = inner.y + inner.height.saturating_sub(2);
        if footer_y >= cy {
            cy = footer_y;
        }
        let toggle_label = if self.show_logs {
            "[L] Hide logs"
        } else {
            "[L] Show logs"
        };
        let cancel_label = "[Esc] Cancel";
        let submit_label = if self.phase.is_terminal() {
            ""
        } else if matches!(self.phase, DialogPhase::AwaitingHostKeyConfirmation) {
            "[Enter] Continue"
        } else if matches!(self.phase, DialogPhase::AwaitingFallbackConfirmation) {
            "[y+Enter] Slow compile   [Enter] Cancel"
        } else {
            "[Enter] Submit"
        };
        buf.set_line(
            inner.x,
            cy,
            &Line::from(vec![
                Span::styled(
                    toggle_label,
                    Style::default()
                        .fg(self.theme.ui(TEAL))
                        .bg(self.theme.ui(PANEL_BG))
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled("    ", Style::default().bg(self.theme.ui(PANEL_BG))),
                Span::styled(
                    cancel_label,
                    Style::default()
                        .fg(self.theme.ui(Color::Rgb(0xb4, 0xbe, 0xc8)))
                        .bg(self.theme.ui(PANEL_BG)),
                ),
                Span::styled("    ", Style::default().bg(self.theme.ui(PANEL_BG))),
                Span::styled(
                    submit_label,
                    Style::default()
                        .fg(self.theme.ui(ACCENT))
                        .bg(self.theme.ui(PANEL_BG))
                        .add_modifier(Modifier::BOLD),
                ),
            ]),
            inner.width,
        );
        self.toggle_logs_btn = Rect {
            x: inner.x,
            y: cy,
            width: toggle_label.chars().count() as u16,
            height: 1,
        };
        let cancel_x = inner.x + (toggle_label.chars().count() as u16) + 4;
        self.cancel_btn = Rect {
            x: cancel_x,
            y: cy,
            width: cancel_label.chars().count() as u16,
            height: 1,
        };
        let submit_x = cancel_x + (cancel_label.chars().count() as u16) + 4;
        self.submit_btn = Rect {
            x: submit_x,
            y: cy,
            width: submit_label.chars().count() as u16,
            height: 1,
        };

        if self.show_logs && cy > inner.y + 1 {
            // Never over the prompt, the notes or the answer box.
            let log_top = cy.saturating_sub(logs_h).max(body_end);
            if log_top > inner.y && log_top < cy {
                let log_rect = Rect {
                    x: inner.x,
                    y: log_top,
                    width: inner.width,
                    height: cy.saturating_sub(log_top).saturating_sub(1),
                };
                if log_rect.height > 0 {
                    let block = Block::default()
                        .borders(Borders::TOP)
                        .border_style(
                            Style::default()
                                .fg(Color::DarkGray)
                                .bg(self.theme.ui(PANEL_BG)),
                        )
                        .title(Span::styled(
                            " ssh transcript ",
                            Style::default()
                                .fg(self.theme.ui(Color::Rgb(0x9d, 0xa5, 0xb4)))
                                .bg(self.theme.ui(PANEL_BG)),
                        ));
                    let inner_log = block.inner(log_rect);
                    block.render(log_rect, buf);
                    let lines: Vec<&String> = self
                        .logs
                        .iter()
                        .rev()
                        .take(inner_log.height as usize)
                        .collect();
                    for (i, line) in lines.iter().rev().enumerate() {
                        let y = inner_log.y + i as u16;
                        if y >= inner_log.y + inner_log.height {
                            break;
                        }
                        let txt = truncate(line, inner_log.width as usize);
                        for dx in 0..inner_log.width {
                            let cell = &mut buf[(inner_log.x + dx, y)];
                            cell.set_char(' ');
                            cell.set_style(Style::default().bg(self.theme.ui(PANEL_BG)));
                        }
                        let fg = log_line_color(line, self.theme);
                        buf.set_string(
                            inner_log.x,
                            y,
                            txt,
                            Style::default().fg(fg).bg(self.theme.ui(PANEL_BG)),
                        );
                    }
                }
            }
        }
    }
}

fn truncate(s: &str, max: usize) -> String {
    if max == 0 {
        return String::new();
    }
    let count = s.chars().count();
    if count <= max {
        return s.to_string();
    }
    // Cut plainly, no trailing ellipsis marker (no ellipsis anywhere in croft).
    s.chars().take(max).collect()
}

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

    #[test]
    fn new_dialog_starts_in_connecting_phase_with_no_input() {
        let d = ConnectDialog::new("genesis-cloud".to_string());
        assert_eq!(d.phase, DialogPhase::Connecting);
        assert!(d.input.is_empty());
        assert!(!d.show_logs);
    }

    #[test]
    fn set_prompt_switches_phase_per_prompt_kind() {
        let mut d = ConnectDialog::new("h".to_string());
        d.set_prompt(PromptKind::Password, "user@host's password: ".into());
        assert_eq!(d.phase, DialogPhase::AwaitingPassword);
        d.set_prompt(PromptKind::Passphrase, "Enter passphrase: ".into());
        assert_eq!(d.phase, DialogPhase::AwaitingPassphrase);
        d.set_prompt(PromptKind::VerificationCode, "Verification code: ".into());
        assert_eq!(d.phase, DialogPhase::AwaitingVerificationCode);
        d.set_prompt(
            PromptKind::HostKeyConfirmation,
            "Are you sure you want to continue connecting (yes/no/[fingerprint])? ".into(),
        );
        assert_eq!(d.phase, DialogPhase::AwaitingHostKeyConfirmation);
    }

    // The 2026-08-09 gitcgr report: the installer slid into the slow
    // compile-on-remote fallback without asking, so a missing
    // `croft setup-cross` surfaced only as a stale remote version. The
    // fallback now needs an explicit yes; an empty submit must decline.
    #[test]
    fn set_fallback_prompt_awaits_an_explicit_yes() {
        let mut d = ConnectDialog::new("gitcgr".to_string());
        d.set_fallback_prompt("`cargo-zigbuild` not found", &[]);
        assert_eq!(d.phase, DialogPhase::AwaitingFallbackConfirmation);
        assert!(d.phase.awaits_input());
        assert!(d.prompt_text.contains("cargo-zigbuild"));
        assert!(
            d.input_for_submit().is_empty(),
            "no auto-yes: an empty submit reads as a decline"
        );
        assert!(!d.input_is_secret());
        assert!(d.show_logs, "the skip reason lives in the log panel");
    }

    /// #950 review: what a yes to the slow compile installs is drawn in the
    /// dialog above the answer box, whole, even on a terminal too short to
    /// show the log panel.
    #[test]
    fn fallback_notes_are_drawn_above_the_answer_box_on_a_short_terminal() {
        let notes = [
            "If Rust is missing there, rustup installs it into ~/.rustup and ~/.cargo (about 1 GB); shell startup files are left alone.",
            "If a C compiler, pkg-config or dtach is missing, or curl and ca-certificates to fetch Rust, the system package manager installs them, through `sudo -n` when not root.",
        ];
        for (w, h) in [(80u16, 18u16), (48, 22), (200, 50)] {
            let mut d = ConnectDialog::new("devbox".to_string());
            d.set_fallback_prompt("`cargo-zigbuild` not found", &notes);
            let area = Rect::new(0, 0, w, h);
            let mut buf = Buffer::empty(area);
            Widget::render(&mut d, area, &mut buf);
            let field = d.field_rect;
            let inner = d.last_inner;
            assert!(field.height > 0, "{w}x{h}: the answer box is drawn");
            assert!(d.notes_shown, "{w}x{h}");
            let above: String = (inner.y..field.y)
                .map(|y| {
                    (inner.x..inner.right())
                        .map(|x| buf[(x, y)].symbol().to_string())
                        .collect::<String>()
                })
                .collect::<Vec<_>>()
                .join(" ");
            let shown: Vec<&str> = above.split_whitespace().collect();
            for word in notes.iter().flat_map(|n| n.split_whitespace()) {
                assert!(
                    shown.contains(&word),
                    "{w}x{h}: {word:?} is shown above the box"
                );
            }
        }
    }

    /// #950 review: a window too short for the notes and the answer box
    /// says so, so the app can hold a yes until they have been seen.
    #[test]
    fn a_window_too_short_for_the_fallback_notes_reports_them_unseen() {
        let mut d = ConnectDialog::new("devbox".to_string());
        d.set_fallback_prompt("no cross toolchain", &["one note", "another note"]);
        for (h, seen) in [(12u16, false), (24, true)] {
            let area = Rect::new(0, 0, 80, h);
            let mut buf = Buffer::empty(area);
            Widget::render(&mut d, area, &mut buf);
            assert_eq!(d.notes_shown, seen, "80x{h}");
            let screen: String = (0..h)
                .map(|y| {
                    (0..80)
                        .map(|x| buf[(x, y)].symbol().to_string())
                        .collect::<String>()
                })
                .collect();
            assert_eq!(
                screen.contains(TOO_SHORT_FOR_FALLBACK),
                !seen,
                "80x{h}: the window says when it is too short"
            );
        }
    }

    #[test]
    fn input_is_secret_only_for_password_and_passphrase_phases() {
        let mut d = ConnectDialog::new("h".to_string());
        d.set_prompt(PromptKind::Password, "p".into());
        assert!(d.input_is_secret());
        d.set_prompt(PromptKind::Passphrase, "p".into());
        assert!(d.input_is_secret());
        d.set_prompt(PromptKind::VerificationCode, "c".into());
        assert!(!d.input_is_secret(), "2FA codes are not secret to the user");
        d.set_prompt(PromptKind::HostKeyConfirmation, "yes/no".into());
        assert!(!d.input_is_secret());
    }

    #[test]
    fn host_key_confirmation_defaults_submit_to_yes_when_user_just_hits_enter() {
        let mut d = ConnectDialog::new("h".to_string());
        d.set_prompt(PromptKind::HostKeyConfirmation, "yes/no".into());
        assert_eq!(d.input_for_submit(), "yes");
    }

    #[test]
    fn push_input_only_accumulates_during_awaiting_phases() {
        let mut d = ConnectDialog::new("h".to_string());
        d.push_input_char('x');
        assert!(d.input.is_empty(), "no input in Connecting phase");
        d.set_prompt(PromptKind::Password, "p".into());
        d.push_input_char('x');
        d.push_input_char('y');
        assert_eq!(d.input, "xy");
        d.pop_input_char();
        assert_eq!(d.input, "x");
    }

    #[test]
    fn toggle_logs_is_idempotent_pair() {
        let mut d = ConnectDialog::new("h".to_string());
        assert!(!d.show_logs);
        d.toggle_logs();
        assert!(d.show_logs);
        d.toggle_logs();
        assert!(!d.show_logs);
    }

    #[test]
    fn push_log_splits_on_newlines_and_caps_buffer() {
        let mut d = ConnectDialog::new("h".to_string());
        for _ in 0..(MAX_LOG_LINES + 50) {
            d.push_log("line\n");
        }
        assert_eq!(
            d.logs.len(),
            MAX_LOG_LINES,
            "log buffer must cap so a chatty ssh transcript doesn't grow without bound"
        );
        d.push_log("first\nsecond\n");
        assert!(d.logs.last().unwrap().contains("second"));
    }

    #[test]
    fn dialog_renders_password_field_as_bullets_not_plaintext() {
        let mut d = ConnectDialog::new("h".to_string());
        d.set_prompt(PromptKind::Password, "p".into());
        for c in "hunter2".chars() {
            d.push_input_char(c);
        }
        let area = Rect {
            x: 0,
            y: 0,
            width: 60,
            height: 18,
        };
        let mut buf = Buffer::empty(area);
        (&mut d).render(area, &mut buf);
        let mut joined = String::new();
        for y in area.top()..area.bottom() {
            for x in area.left()..area.right() {
                joined.push_str(buf[(x, y)].symbol());
            }
            joined.push('\n');
        }
        assert!(
            !joined.contains("hunter2"),
            "password modal must NEVER render the typed password verbatim"
        );
        assert!(
            joined.contains('•'),
            "password modal must render typed characters as • bullets"
        );
    }

    #[test]
    fn awaiting_phase_publishes_caret_position_inside_the_field() {
        let mut d = ConnectDialog::new("h".to_string());
        d.set_prompt(PromptKind::Password, "p".into());
        let area = Rect {
            x: 0,
            y: 0,
            width: 60,
            height: 18,
        };
        let mut buf = Buffer::empty(area);
        (&mut d).render(area, &mut buf);
        let (cx, cy) =
            d.cursor_screen_pos().expect("password phase must publish the caret position so the host terminal blinks the OS caret where the user types");
        assert!(cx >= d.field_rect.x);
        assert!(cx < d.field_rect.x + d.field_rect.width);
        assert_eq!(cy, d.field_rect.y);
    }

    #[test]
    fn empty_field_still_shows_a_caret_and_a_placeholder_so_the_user_can_tell_typing_is_alive() {
        let mut d = ConnectDialog::new("h".to_string());
        d.set_prompt(PromptKind::Password, "p".into());
        let area = Rect {
            x: 0,
            y: 0,
            width: 60,
            height: 18,
        };
        let mut buf = Buffer::empty(area);
        (&mut d).render(area, &mut buf);
        let mut field_row = String::new();
        for x in d.field_rect.x..(d.field_rect.x + d.field_rect.width) {
            field_row.push_str(buf[(x, d.field_rect.y)].symbol());
        }
        assert!(
            field_row.contains('▌'),
            "an empty password field must still paint a caret glyph (▌) so the user knows the field is live (regression: blank field looked dead, user could not tell typing was registering)"
        );
        assert!(
            field_row.contains("type your password"),
            "an empty password field must show placeholder text so the user knows what to type (got row: {field_row:?})"
        );
    }

    #[test]
    fn caret_position_advances_as_the_user_types_into_the_field() {
        let mut d = ConnectDialog::new("h".to_string());
        d.set_prompt(PromptKind::Password, "p".into());
        let area = Rect {
            x: 0,
            y: 0,
            width: 60,
            height: 18,
        };
        let mut buf = Buffer::empty(area);
        (&mut d).render(area, &mut buf);
        let initial = d.cursor_screen_pos().unwrap();
        for c in "abcd".chars() {
            d.push_input_char(c);
        }
        (&mut d).render(area, &mut buf);
        let after = d.cursor_screen_pos().unwrap();
        assert!(
            after.0 > initial.0,
            "caret column must advance after typing — initial={initial:?}, after={after:?}"
        );
    }

    #[test]
    fn toggle_logs_button_registers_hit_rect_so_mouse_can_click_it() {
        let mut d = ConnectDialog::new("h".to_string());
        let area = Rect {
            x: 0,
            y: 0,
            width: 60,
            height: 18,
        };
        let mut buf = Buffer::empty(area);
        (&mut d).render(area, &mut buf);
        assert!(
            d.toggle_logs_btn.width > 0,
            "toggle-logs button must register a hit rect so clicking it flips show_logs"
        );
        assert!(d.cancel_btn.width > 0);
    }

    #[test]
    fn set_authenticated_moves_to_terminal_phase_and_clears_input() {
        let mut d = ConnectDialog::new("h".to_string());
        d.set_prompt(PromptKind::Password, "p".into());
        d.push_input_char('x');
        d.set_authenticated();
        assert_eq!(d.phase, DialogPhase::Authenticated);
        assert!(d.phase.is_terminal());
        assert!(d.input.is_empty());
    }

    #[test]
    fn set_failed_records_the_error_and_moves_to_terminal_phase() {
        let mut d = ConnectDialog::new("h".to_string());
        d.set_failed("ssh exited 255".to_string());
        assert_eq!(d.phase, DialogPhase::Failed);
        assert!(d.phase.is_terminal());
        assert_eq!(d.error.as_deref(), Some("ssh exited 255"));
    }
}