procyon 0.1.0

Terminal development harness for Stellar and Soroban smart contracts, driven by a language model
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
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Padding, Paragraph},
    Frame,
};

use crate::app::{AppState, AppStatus, AutocompleteItem, ChatMessage};
use crate::config::Theme;

// Stellar Development Foundation, Brand Guidelines 2026, p.02 / p.04.
//
// Primary: yellow, black, white. Secondary: warm grey, lavender, teal, deep navy. The guidelines'
// typography (Lora / Inter) has no equivalent here — a terminal renders in whatever font the user
// chose, so the brand has to carry entirely on colour and mark.
const STELLAR_YELLOW: Color = Color::Rgb(253, 218, 36); // #FDDA24
const STELLAR_BLACK: Color = Color::Rgb(15, 15, 15); // #0F0F0F
const STELLAR_WHITE: Color = Color::Rgb(246, 247, 248); // #F6F7F8
const STELLAR_LAVENDER: Color = Color::Rgb(183, 172, 232); // #B7ACE8
const STELLAR_TEAL: Color = Color::Rgb(0, 167, 181); // #00A7B5
const STELLAR_NAVY: Color = Color::Rgb(0, 46, 93); // #002E5D
/// The warm grey, darkened until it works as chrome against #0F0F0F rather than as body text.
const STELLAR_GREY_DARK_BG: Color = Color::Rgb(138, 134, 124);
/// ...and the same hue darkened the other way, for chrome on a light background.
const STELLAR_GREY_LIGHT_BG: Color = Color::Rgb(107, 103, 94);

/// Six roles, no more. Every colour in the TUI comes from here — a literal `Color::*` at a call
/// site is a bug, because it is a colour nobody can re-theme and nobody can name.
pub struct ColorPalette {
    /// Body text.
    pub fg: Color,
    /// Chrome: labels, sub-steps, hints, the status line.
    pub dim: Color,
    /// The Stellar accent — prompt glyph, monogram, selection, the running step.
    pub accent: Color,
    /// Network name in the status line, for any network that is not mainnet.
    pub network: Color,
    pub ok: Color,
    pub err: Color,
}

impl ColorPalette {
    pub fn from_theme(theme: &Theme) -> Self {
        match theme {
            Theme::Dark => Self {
                fg: STELLAR_WHITE,
                dim: STELLAR_GREY_DARK_BG,
                accent: STELLAR_YELLOW,
                network: STELLAR_LAVENDER,
                ok: STELLAR_TEAL,
                err: Color::Red,
            },
            // The brand yellow is a fill colour, not a text colour: on white it is illegible, and
            // the guidelines themselves only ever put it behind black strokes. Deep navy is the
            // secondary that survives the swap, so the light theme leads with it.
            Theme::Light => Self {
                fg: STELLAR_BLACK,
                dim: STELLAR_GREY_LIGHT_BG,
                accent: STELLAR_NAVY,
                network: STELLAR_TEAL,
                ok: STELLAR_TEAL,
                err: Color::Red,
            },
        }
    }
}

/// Marker for a user turn, and for the input prompt — the two places the human speaks.
const USER_GLYPH: &str = "";
/// Marker for an execution step or a system notice.
const STEP_GLYPH: &str = "";
/// Marker for a sub-step hanging off the step above it.
const SUBSTEP_GLYPH: &str = "";

const SPINNER_FRAMES: [&str; 10] = ["", "", "", "", "", "", "", "", "", ""];

/// One text row plus the two border rows around it.
const INPUT_FRAME_HEIGHT: u16 = 3;

/// The house frame. Rounded corners throughout — the Stellar mark and wordmark are built on
/// curves, and a square box next to them reads as a different system. One column of padding on
/// each side, so text has an edge to sit against rather than one to collide with.
fn frame_block(color: Color) -> Block<'static> {
    Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(color))
        .padding(Padding::horizontal(1))
}

pub fn render(frame: &mut Frame, state: &mut AppState, theme: &Theme) {
    let palette = ColorPalette::from_theme(theme);

    // The input is one line inside its frame; the suggestion popup hangs below it and has to be
    // inside the chunk, so the chunk grows by exactly the rows the popup will use.
    let input_height = if state.autocomplete_active && !state.autocomplete_matches.is_empty() {
        INPUT_FRAME_HEIGHT + autocomplete_popup_height(state.autocomplete_matches.len())
    } else {
        INPUT_FRAME_HEIGHT
    };

    // transcript / input / status line. No top bar, no sidebar: the transcript gets the screen.
    let main_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(0),
            Constraint::Length(input_height),
            Constraint::Length(1),
        ])
        .split(frame.area());

    // Two frames, and only two: the conversation and the place you type into it. Rounded, in the
    // quietest colour that still reads as a line — they are there to give the content an edge to
    // sit against, not to be looked at.
    let body = frame_block(palette.dim);
    let body_inner = body.inner(main_chunks[0]);
    frame.render_widget(body, main_chunks[0]);

    if has_conversation(state) {
        render_chat(frame, state, body_inner, &palette);
    } else {
        render_welcome(frame, state, body_inner, &palette);
    }
    render_input(frame, state, main_chunks[1], &palette);
    render_statusline(frame, state, main_chunks[2], &palette);

    if state.palette_open {
        render_palette(frame, state, &palette);
    }
}

/// True once anything has been said. Until then the welcome banner owns the transcript area; the
/// first message of any kind sends it away for good.
///
/// "Any kind" is load-bearing: slash commands answer with `System` messages and nothing else, so
/// restricting this to User/Agent left the banner covering the reply to every `/help`, `/status`
/// and `/doctor` — the commands ran and their output was drawn underneath.
fn has_conversation(state: &AppState) -> bool {
    !state.messages.is_empty()
}

/// The Stellar monogram reduced to what a terminal cell grid can hold honestly: its three slanted
/// strokes, stacked into the mark's silhouette. Drawn in the brand yellow, and the only piece of
/// ornament in the whole interface — everywhere else the glyphs stay neutral, so this reads as a
/// signature rather than as decoration.
const STELLAR_MARK: [&str; 3] = [" ╱╱ ", "╱╱╱ ", " ╱╱ "];

fn render_welcome(frame: &mut Frame, state: &AppState, area: Rect, palette: &ColorPalette) {
    let dim = Style::default().fg(palette.dim);
    let mark = Style::default().fg(palette.accent);

    // The mark sits to the left of the wordmark, so the two read as one lockup.
    let lines = vec![
        Line::from(""),
        Line::from(vec![
            Span::styled(format!("  {}  ", STELLAR_MARK[0]), mark),
            Span::styled(
                "procyon",
                Style::default().fg(palette.fg).add_modifier(Modifier::BOLD),
            ),
        ]),
        Line::from(vec![
            Span::styled(format!("  {}  ", STELLAR_MARK[1]), mark),
            Span::styled("Stellar development harness", dim),
        ]),
        Line::from(Span::styled(format!("  {}", STELLAR_MARK[2]), mark)),
        Line::from(""),
        Line::from(vec![
            Span::styled("        ", dim),
            Span::styled(state.cwd_label.clone(), dim),
        ]),
        Line::from(vec![
            Span::styled("        ", dim),
            Span::styled(
                state.active_network.clone(),
                Style::default().fg(palette.network),
            ),
            // The project only earns a slot once there is one — "No project" on the welcome
            // screen is a placeholder announcing its own emptiness.
            Span::styled(
                match state.project_name.as_str() {
                    "No project" => String::new(),
                    name => format!(" · {}", name),
                },
                dim,
            ),
            Span::styled(
                format!(" · {} {}", state.active_provider, state.active_model),
                dim,
            ),
        ]),
        Line::from(""),
        Line::from(Span::styled(
            "        Type / for commands · ctrl+k for the palette · ? for shortcuts",
            dim,
        )),
    ];

    frame.render_widget(Paragraph::new(lines), area);
}

fn render_statusline(frame: &mut Frame, state: &AppState, area: Rect, palette: &ColorPalette) {
    let dim = Style::default().fg(palette.dim);
    // Two columns in, so the status line starts on the same column as the text inside the frames
    // above it rather than half a step to their left.
    let mut spans = vec![Span::raw("  ")];

    // Network first. Mainnet switches to the brand yellow and goes bold — real funds are the one
    // piece of context worth interrupting for, and yellow is the colour the brand already uses to
    // draw the eye. Everything else stays in the calmer lavender.
    let network_style = if state.active_network == "mainnet" {
        Style::default()
            .fg(palette.accent)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(palette.network)
    };
    spans.push(Span::styled(state.active_network.clone(), network_style));

    spans.push(Span::styled(
        format!(" · {} {}", state.active_provider, state.active_model),
        dim,
    ));

    if let Some(contract) = &state.active_contract {
        spans.push(Span::styled(format!(" · {}", abbreviate(contract)), dim));
    }

    match state.status {
        AppStatus::Working => {
            let spinner = SPINNER_FRAMES[state.spinner_frame % SPINNER_FRAMES.len()];
            let activity = state
                .current_activity
                .as_deref()
                .map(crate::app::activity_label)
                .unwrap_or("Working...");
            spans.push(Span::styled(" · ", dim));
            spans.push(Span::styled(
                format!("{} {}", spinner, activity),
                Style::default().fg(palette.accent),
            ));
        }
        AppStatus::NeedsCredential => {
            spans.push(Span::styled(" · ", dim));
            spans.push(Span::styled(
                "● needs login",
                Style::default().fg(palette.err),
            ));
        }
        // Ready is the resting state: saying so every frame is noise.
        AppStatus::Ready => {}
    }

    // Hints go right-aligned, and shed the wordy half before they'd collide with the left side.
    let width = area.width as usize;
    let hint = if width >= 60 {
        "? shortcuts · ctrl+k "
    } else {
        "ctrl+k "
    };
    let mut used: usize = spans.iter().map(|s| s.content.chars().count()).sum();

    // On a narrow terminal the left side is cut with an ellipsis rather than let the renderer
    // clip it mid-word: an ellipsis says "there is more", a hard cut looks like a bug.
    if used > width {
        let mut budget = width;
        for span in spans.iter_mut() {
            let len = span.content.chars().count();
            if len <= budget {
                budget -= len;
            } else {
                span.content = truncate_to(span.content.as_ref(), budget).into();
                budget = 0;
            }
        }
        used = width;
    }

    // At least two columns of gap, or the hint reads as a word glued to the activity
    // ("Building contract? shortcuts"). With no room for the gap, drop the hint entirely.
    let gap = 2;
    if used + hint.chars().count() + gap <= width {
        spans.push(Span::raw(" ".repeat(width - used - hint.chars().count())));
        spans.push(Span::styled(hint, dim));
    }

    frame.render_widget(Paragraph::new(Line::from(spans)), area);
}

/// Shortens a Stellar contract/account id to head…tail, which is how people actually recognise
/// one, without spending 56 columns of a one-line status bar on it.
fn abbreviate(id: &str) -> String {
    let chars: Vec<char> = id.chars().collect();
    if chars.len() <= 12 {
        return id.to_string();
    }
    let head: String = chars[..4].iter().collect();
    let tail: String = chars[chars.len() - 4..].iter().collect();
    format!("{}{}", head, tail)
}

fn render_palette(frame: &mut Frame, state: &AppState, palette: &ColorPalette) {
    let area = frame.area();
    let width = (area.width.saturating_sub(10)).clamp(40, 70);
    let height = (state.palette_matches.len().min(8) as u16 + 4).min(area.height.saturating_sub(4));
    let x = (area.width.saturating_sub(width)) / 2;
    let y = (area.height.saturating_sub(height)) / 2;
    let popup = Rect::new(x, y, width, height);

    let block = frame_block(palette.dim).title(" commands ");

    let inner = block.inner(popup);
    // Cleared one column wider than the frame, so a line of transcript peeking out beside the
    // border reads as a gutter rather than as leftover debris.
    let gutter = Rect::new(
        popup.x.saturating_sub(1),
        popup.y,
        (popup.width + 2).min(area.width - popup.x.saturating_sub(1)),
        popup.height,
    );
    frame.render_widget(ratatui::widgets::Clear, gutter);
    frame.render_widget(block, popup);

    // Input line at top of palette
    let input_line = Line::from(vec![
        Span::styled(USER_GLYPH, Style::default().fg(palette.accent)),
        Span::styled(
            state.palette_input.as_str(),
            Style::default().fg(palette.fg),
        ),
    ]);
    let input_area = Rect::new(inner.x, inner.y, inner.width, 1);
    frame.render_widget(Paragraph::new(input_line), input_area);

    // Matches below. The window is taken *after* scrolling to the selection — taking the first
    // `list_height` entries first and then filtering them by the offset (as this used to) means
    // that once the highlight moves past the first screenful every row is skipped and the list
    // renders blank.
    let list_y = inner.y + 2;
    let list_height = inner.height.saturating_sub(2) as usize;
    let offset = scroll_offset(
        state.palette_selected,
        state.palette_matches.len(),
        list_height,
    );

    let lines: Vec<Line<'static>> = state
        .palette_matches
        .iter()
        .enumerate()
        .skip(offset)
        .take(list_height)
        .map(|(idx, item)| {
            let style = if idx == state.palette_selected {
                Style::default()
                    .fg(palette.accent)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(palette.fg)
            };
            Line::from(vec![
                Span::styled(format!(" {:<16} ", item.value), style),
                Span::styled(item.description.clone(), Style::default().fg(palette.dim)),
            ])
        })
        .collect();

    let list_area = Rect::new(inner.x, list_y, inner.width, list_height as u16);
    frame.render_widget(Paragraph::new(lines), list_area);

    // Cursor inside palette input
    let cx = inner.x + 2 + state.palette_cursor as u16;
    let cy = inner.y;
    if cx < inner.x + inner.width {
        frame.set_cursor_position((cx, cy));
    }
}

// Width is counted in chars rather than display cells, so double-width glyphs (CJK) wrap a little
// early. Good enough here, and it avoids a unicode-width dependency.
fn wrap_text(text: &str, width: usize) -> Vec<String> {
    if width == 0 {
        return vec![String::new()];
    }

    let mut lines = Vec::new();
    let mut current = String::new();
    let mut current_width = 0usize;

    for word in text.split(' ') {
        let word_width = word.chars().count();

        if word_width > width {
            if current_width > 0 {
                lines.push(std::mem::take(&mut current));
                current_width = 0;
            }
            let chars: Vec<char> = word.chars().collect();
            for chunk in chars.chunks(width) {
                lines.push(chunk.iter().collect());
            }
            // The trailing chunk stays open so following words can share the line.
            if let Some(last) = lines.pop() {
                current_width = last.chars().count();
                current = last;
            }
            continue;
        }

        let needed = if current_width == 0 {
            word_width
        } else {
            current_width + 1 + word_width
        };

        if needed > width {
            lines.push(std::mem::take(&mut current));
            current.push_str(word);
            current_width = word_width;
        } else {
            if current_width > 0 {
                current.push(' ');
            }
            current.push_str(word);
            current_width = needed;
        }
    }

    lines.push(current);
    lines
}

fn message_lines(msg: &ChatMessage, palette: &ColorPalette, width: usize) -> Vec<Line<'static>> {
    // Speaker labels are glyphs, not words: "You:"/"Agent:" spent five columns per line saying
    // something the colour and position already said. The agent — the bulk of the transcript —
    // gets no marker at all, so its prose reads as the body of the page.
    let (lead, lead_style, body_style) = match msg {
        ChatMessage::User(_) => (
            USER_GLYPH,
            Style::default()
                .fg(palette.accent)
                .add_modifier(Modifier::BOLD),
            Style::default().fg(palette.fg),
        ),
        ChatMessage::Agent(_) => ("", Style::default(), Style::default().fg(palette.fg)),
        ChatMessage::System(_) => (
            STEP_GLYPH,
            Style::default().fg(palette.dim),
            Style::default().fg(palette.dim),
        ),
        ChatMessage::Event(text) => {
            // Tool traces are rendered as execution steps, so suppress the duplicate inline copy.
            if text.starts_with("Using tool:") || text == "Thinking..." {
                return Vec::new();
            }
            (
                USER_GLYPH,
                Style::default().fg(palette.dim),
                Style::default().fg(palette.dim),
            )
        }
    };

    let content = match msg {
        ChatMessage::User(text)
        | ChatMessage::Agent(text)
        | ChatMessage::System(text)
        | ChatMessage::Event(text) => text.as_str(),
    };

    // Continuations line up under the first character of the text, so a wrapped paragraph reads
    // as one block. With no lead glyph (the agent) there is nothing to line up under.
    let lead_width = lead.chars().count();
    let indent = " ".repeat(lead_width);
    let mut out = Vec::new();

    for logical in content.split('\n') {
        let budget = width.saturating_sub(lead_width).max(1);
        for (wrapped_index, piece) in wrap_text(logical, budget).into_iter().enumerate() {
            let is_first = out.is_empty() && wrapped_index == 0;
            if is_first && !lead.is_empty() {
                out.push(Line::from(vec![
                    Span::styled(lead, lead_style),
                    Span::styled(piece, body_style),
                ]));
            } else if lead.is_empty() {
                out.push(Line::from(Span::styled(piece, body_style)));
            } else {
                out.push(Line::from(vec![
                    Span::raw(indent.clone()),
                    Span::styled(piece, body_style),
                ]));
            }
        }
    }

    out
}

fn render_chat(frame: &mut Frame, state: &mut AppState, area: Rect, palette: &ColorPalette) {
    let inner_width = area.width.saturating_sub(1) as usize;
    let viewport = area.height as usize;

    let mut lines: Vec<Line<'static>> = Vec::new();
    for msg in &state.messages {
        lines.extend(message_lines(msg, palette, inner_width));
    }

    // The execution trace flows in the transcript as indented steps rather than sitting inside a
    // hand-drawn box. Same information, none of the border arithmetic that used to slice
    // multibyte glyphs in half.
    if !state.execution_steps.is_empty() {
        if !lines.is_empty() {
            lines.push(Line::from(""));
        }
        lines.extend(execution_lines(state, palette, inner_width));
    }

    let max_scroll = lines.len().saturating_sub(viewport);
    let offset_from_top = state.resolve_scroll(max_scroll);

    frame.render_widget(
        Paragraph::new(lines).scroll((offset_from_top as u16, 0)),
        area,
    );

    // The old border title carried "(N lines below)". Without a border it becomes a floating
    // marker on the last row — only while scrolled back, so it costs nothing at rest.
    let below = max_scroll - offset_from_top;
    if !state.is_following_chat() && below > 0 && area.height > 0 {
        let marker = format!("{} more ", below);
        let w = (marker.chars().count() as u16).min(area.width);
        let row = Rect::new(
            area.x + area.width.saturating_sub(w),
            area.y + area.height - 1,
            w,
            1,
        );
        frame.render_widget(ratatui::widgets::Clear, row);
        frame.render_widget(
            Paragraph::new(Line::from(Span::styled(
                marker,
                Style::default().fg(palette.dim),
            ))),
            row,
        );
    }
}

fn execution_lines(state: &AppState, palette: &ColorPalette, width: usize) -> Vec<Line<'static>> {
    let mut out = Vec::new();
    for step in &state.execution_steps {
        // A tool call is detail hanging off whatever phase the agent announced; everything else
        // (Thinking, MCP notices, plain status) is a phase in its own right.
        let is_substep = step.label.to_lowercase().starts_with("using tool:");
        let (glyph, indent, style) = if is_substep {
            (SUBSTEP_GLYPH, "  ", Style::default().fg(palette.dim))
        } else {
            let color = match step.state {
                crate::app::ExecutionStepState::Done => palette.ok,
                crate::app::ExecutionStepState::Failed => palette.err,
                crate::app::ExecutionStepState::Running => palette.accent,
            };
            (STEP_GLYPH, "", Style::default().fg(color))
        };

        let lead_width = indent.chars().count() + glyph.chars().count();
        let budget = width.saturating_sub(lead_width).max(10);
        let pretty = pretty_execution_label(&step.label);
        let body = if is_substep {
            Style::default().fg(palette.dim)
        } else {
            Style::default().fg(palette.fg)
        };

        for (i, piece) in wrap_text(&pretty, budget).into_iter().enumerate() {
            if i == 0 {
                out.push(Line::from(vec![
                    Span::raw(indent),
                    Span::styled(glyph, style),
                    Span::styled(piece, body),
                ]));
            } else {
                out.push(Line::from(vec![
                    Span::raw(" ".repeat(lead_width)),
                    Span::styled(piece, body),
                ]));
            }
        }
    }
    out
}

fn pretty_execution_label(raw: &str) -> String {
    let lower = raw.to_lowercase();
    if lower.contains("thinking") {
        return "Thinking...".to_string();
    }
    if lower.starts_with("using tool:") {
        let tool = raw.split(':').nth(1).unwrap_or("").trim();
        return format!("{}{}", tool, friendly_tool_desc(tool));
    }
    if lower.starts_with("mcp ") {
        return raw.to_string();
    }
    raw.to_string()
}

fn friendly_tool_desc(tool: &str) -> &'static str {
    match tool {
        "caatinga_build" => "building contract",
        "caatinga_deploy" => "deploying to network",
        "caatinga_doctor" => "checking environment",
        "caatinga_invoke" => "invoking contract",
        "caatinga_read" => "reading contract",
        "stellar_invoke" => "invoking via CLI",
        "read_file" => "reading file",
        "write_file" => "writing file",
        "edit_file" => "editing file",
        "grep" => "searching code",
        "glob" => "locating files",
        "list_dir" => "listing directory",
        "account_create" => "creating account",
        "account_balance" => "checking balance",
        _ if tool.starts_with("raven__") => "searching Stellar Docs",
        _ => "executing",
    }
}

/// Cuts `text` to at most `max_chars`, replacing the tail with an ellipsis.
fn truncate_to(text: &str, max_chars: usize) -> String {
    if max_chars == 0 {
        return String::new();
    }
    if text.chars().count() <= max_chars {
        return text.to_string();
    }
    let mut out: String = text.chars().take(max_chars.saturating_sub(1)).collect();
    out.push('');
    out
}

/// How many suggestion rows the popup shows at once before it starts scrolling.
const AUTOCOMPLETE_MAX_VISIBLE: usize = 5;

/// Width of the command-name column, so the descriptions line up under each other.
const AUTOCOMPLETE_NAME_COLUMN: usize = 20;

/// Width the popup needs so the longest description fits without being cut, clamped to the space
/// the input area actually has.
fn autocomplete_popup_width(items: &[AutocompleteItem], available: u16) -> u16 {
    let widest_name = items
        .iter()
        .map(|c| c.value.chars().count())
        .max()
        .unwrap_or(0)
        .max(AUTOCOMPLETE_NAME_COLUMN);
    let widest_desc = items
        .iter()
        .map(|c| c.description.chars().count())
        .max()
        .unwrap_or(0);

    // " name<pad> " + description + a trailing space, plus the two border columns and the
    // frame's one column of padding on each side.
    let content = 1 + widest_name + 1 + widest_desc + 1;
    (content as u16 + 4).min(available)
}

/// Rows the popup occupies for `match_count` suggestions, borders included.
fn autocomplete_popup_height(match_count: usize) -> u16 {
    match_count.min(AUTOCOMPLETE_MAX_VISIBLE) as u16 + 2
}

/// First index to draw so the highlighted row stays inside a window of `visible` rows. Shared by
/// the suggestion popup and the command palette — they are the same list-with-a-cursor problem,
/// and the palette's own hand-rolled copy of this got it wrong.
fn scroll_offset(selected: usize, count: usize, visible: usize) -> usize {
    if visible == 0 || count <= visible {
        return 0;
    }
    let max_offset = count - visible;
    selected.saturating_sub(visible - 1).min(max_offset)
}

/// First suggestion index to draw, so the highlighted row stays inside the visible window.
fn autocomplete_scroll_offset(selected: usize, match_count: usize) -> usize {
    scroll_offset(selected, match_count, AUTOCOMPLETE_MAX_VISIBLE)
}

fn render_input(frame: &mut Frame, state: &AppState, area: Rect, palette: &ColorPalette) {
    let show_autocomplete = state.autocomplete_active && !state.autocomplete_matches.is_empty();

    let input_area = Rect {
        x: area.x,
        y: area.y,
        width: area.width,
        height: INPUT_FRAME_HEIGHT,
    };

    // The input frame is the one piece of chrome drawn in the brand yellow: it is where the user
    // acts, and it is the only thing on screen that is always waiting on them.
    let block = frame_block(palette.accent);
    let inner = block.inner(input_area);
    frame.render_widget(block, input_area);

    // The prompt glyph is the same one that marks the user's turns above, so the connection
    // between "what I typed" and "what I said" is visual rather than stated.
    let line = Line::from(vec![
        Span::styled(USER_GLYPH, Style::default().fg(palette.accent)),
        Span::styled(state.input.as_str(), Style::default().fg(palette.fg)),
    ]);
    frame.render_widget(Paragraph::new(line), inner);

    let cursor_x = (inner.x + USER_GLYPH.chars().count() as u16 + state.input_cursor as u16)
        .min(inner.x + inner.width.saturating_sub(1));
    frame.set_cursor_position((cursor_x, inner.y));

    if show_autocomplete {
        let items = &state.autocomplete_matches;

        let popup_area = Rect {
            // Aligned under the typed text, not under the glyph.
            x: inner.x + USER_GLYPH.chars().count() as u16,
            y: area.y + INPUT_FRAME_HEIGHT,
            width: autocomplete_popup_width(items, area.width.saturating_sub(2)),
            height: autocomplete_popup_height(items.len()),
        };

        let offset = autocomplete_scroll_offset(state.autocomplete_selected, items.len());

        let lines: Vec<Line<'static>> = items
            .iter()
            .enumerate()
            .skip(offset)
            .take(AUTOCOMPLETE_MAX_VISIBLE)
            .map(|(i, item)| {
                let style = if i == state.autocomplete_selected {
                    Style::default()
                        .fg(palette.accent)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(palette.fg)
                };
                Line::from(vec![
                    Span::styled(
                        format!(" {:<width$} ", item.value, width = AUTOCOMPLETE_NAME_COLUMN),
                        style,
                    ),
                    Span::styled(item.description.clone(), Style::default().fg(palette.dim)),
                ])
            })
            .collect();

        let popup = Paragraph::new(lines).block(frame_block(palette.dim));

        frame.render_widget(ratatui::widgets::Clear, popup_area);
        frame.render_widget(popup, popup_area);
    }
}

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

    fn palette() -> ColorPalette {
        ColorPalette::from_theme(&Theme::Dark)
    }

    fn rendered(msg: &ChatMessage, width: usize) -> Vec<String> {
        message_lines(msg, &palette(), width)
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
            })
            .collect()
    }

    // The input chunk has to reserve the popup's rows: sizing it to a fixed 8 clipped the last
    // suggestions, so a 10-match list rendered as 3.
    #[test]
    fn the_popup_reserves_a_row_per_visible_suggestion() {
        assert_eq!(autocomplete_popup_height(3), 5);
        assert_eq!(
            autocomplete_popup_height(10),
            AUTOCOMPLETE_MAX_VISIBLE as u16 + 2
        );
    }

    // The old fixed 52-column cap truncated the longer descriptions ("local/testne").
    #[test]
    fn the_popup_widens_to_fit_the_longest_description() {
        let items: Vec<AutocompleteItem> = AppState::slash_commands()
            .iter()
            .map(|c| AutocompleteItem {
                value: c.name.to_string(),
                description: c.description.to_string(),
            })
            .collect();

        let width = autocomplete_popup_width(&items, 200);
        let longest = items
            .iter()
            .map(|c| c.description.chars().count())
            .max()
            .unwrap();
        assert!(width as usize >= AUTOCOMPLETE_NAME_COLUMN + longest);

        // Never wider than the space it was given.
        assert_eq!(autocomplete_popup_width(&items, 30), 30);
    }

    #[test]
    fn the_popup_scrolls_to_keep_the_selection_visible() {
        // Short lists never scroll.
        assert_eq!(autocomplete_scroll_offset(2, 3), 0);
        // Long lists hold still until the highlight reaches the bottom row...
        assert_eq!(
            autocomplete_scroll_offset(AUTOCOMPLETE_MAX_VISIBLE - 1, 10),
            0
        );
        // ...then follow it, and stop once the last entry is on screen.
        assert_eq!(autocomplete_scroll_offset(AUTOCOMPLETE_MAX_VISIBLE, 10), 1);
        assert_eq!(
            autocomplete_scroll_offset(9, 10),
            10 - AUTOCOMPLETE_MAX_VISIBLE
        );
    }

    // Regression: the palette used to window the list before applying the scroll offset, so once
    // the highlight moved past the first screenful every row was filtered out and the popup went
    // blank below the first few entries.
    #[test]
    fn the_palette_keeps_showing_rows_as_the_selection_descends() {
        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let mut state = AppState::new();
        state.handle_key(
            KeyEvent::new(KeyCode::Char('k'), KeyModifiers::CONTROL),
            &tx,
        );
        assert!(state.palette_open, "ctrl+k should open the palette");
        let total = state.palette_matches.len();
        assert!(total > 5, "need a scrollable list, got {}", total);

        for step in 0..total {
            let screen = buffer_rows(80, 24, |frame, area| {
                let _ = area;
                render_palette(frame, &state, &palette())
            })
            .join("\n");

            let selected = &state.palette_matches[state.palette_selected].value;
            assert!(
                screen.contains(selected.as_str()),
                "selection {:?} off screen at step {}:\n{}",
                selected,
                step,
                screen
            );
            let before = state.palette_selected;
            state.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE), &tx);
            assert_ne!(
                before, state.palette_selected,
                "Down must move the selection, or this test proves nothing"
            );
        }
    }

    #[test]
    fn a_windowed_list_scrolls_only_once_the_cursor_reaches_the_bottom() {
        // Fits entirely: never scrolls.
        assert_eq!(scroll_offset(2, 3, 5), 0);
        // Holds still until the highlight reaches the last visible row...
        assert_eq!(scroll_offset(4, 10, 5), 0);
        // ...then follows it, and stops with the final entry on screen.
        assert_eq!(scroll_offset(5, 10, 5), 1);
        assert_eq!(scroll_offset(9, 10, 5), 5);
        // A zero-row window is a degenerate layout, not a panic.
        assert_eq!(scroll_offset(3, 10, 0), 0);
    }

    #[test]
    fn wraps_at_the_given_width() {
        let lines = wrap_text("aaa bbb ccc ddd", 7);
        assert_eq!(lines, vec!["aaa bbb", "ccc ddd"]);
        assert!(lines.iter().all(|l| l.chars().count() <= 7));
    }

    #[test]
    fn short_text_stays_on_one_line() {
        assert_eq!(wrap_text("hello", 40), vec!["hello"]);
    }

    #[test]
    fn breaks_a_word_longer_than_the_line() {
        let lines = wrap_text("aaaaaaaaaa", 4);
        assert!(lines.iter().all(|l| l.chars().count() <= 4), "{:?}", lines);
        assert_eq!(lines.concat(), "aaaaaaaaaa");
    }

    #[test]
    fn wrapping_preserves_multibyte_content() {
        let lines = wrap_text("ação corrigida direito", 10);
        assert!(lines.iter().all(|l| l.chars().count() <= 10), "{:?}", lines);
        assert_eq!(lines.join(" "), "ação corrigida direito");
    }

    #[test]
    fn long_message_produces_multiple_lines_instead_of_truncating() {
        let long = "palavra ".repeat(20).trim_end().to_string();
        let lines = rendered(&ChatMessage::Agent(long), 20);
        assert!(lines.len() > 1, "expected wrapping, got {:?}", lines);
        assert!(lines.iter().all(|l| l.chars().count() <= 20), "{:?}", lines);
    }

    #[test]
    fn the_user_turn_is_marked_and_continuations_line_up_under_the_text() {
        let lines = rendered(&ChatMessage::User("um dois tres quatro".to_string()), 12);
        assert!(lines[0].starts_with(USER_GLYPH), "got {:?}", lines);
        assert!(lines[1].starts_with("  "), "got {:?}", lines);
    }

    // The agent produces most of the transcript, so it carries no marker at all — its prose is
    // the body of the page, not a quoted participant.
    #[test]
    fn the_agent_speaks_without_a_marker() {
        let lines = rendered(&ChatMessage::Agent("um\ndois".to_string()), 40);
        assert_eq!(lines, vec!["um", "dois"]);
    }

    #[test]
    fn embedded_newlines_start_new_lines() {
        let lines = rendered(&ChatMessage::System("um\ndois\ntres".to_string()), 40);
        assert_eq!(lines, vec!["⏺ um", "  dois", "  tres"]);
    }

    // Event trace for non-tool events gets no speaker label. Tool traces ("Using tool:",
    // "Thinking...") are rendered as execution steps instead of inline.
    #[test]
    fn event_messages_get_a_trace_glyph_not_a_speaker_label() {
        let lines = rendered(&ChatMessage::Event("MCP raven connected".to_string()), 40);
        assert_eq!(lines, vec!["› MCP raven connected"]);
    }

    #[test]
    fn tool_event_messages_are_suppressed_inline_in_favor_of_execution_steps() {
        let lines = rendered(&ChatMessage::Event("Using tool: build".to_string()), 40);
        assert!(
            lines.is_empty(),
            "tool traces should be empty inline (they become execution steps), got {:?}",
            lines
        );
    }

    #[test]
    fn multiline_event_messages_indent_continuations() {
        let lines = rendered(&ChatMessage::Event("um\ndois".to_string()), 40);
        assert_eq!(lines, vec!["› um", "  dois"]);
    }

    #[test]
    fn following_resolves_to_the_last_screenful() {
        let mut state = AppState::new();
        assert!(state.is_following_chat());
        assert_eq!(state.resolve_scroll(6), 6);
    }

    #[test]
    fn scrolling_forward_to_the_bottom_resumes_following() {
        let mut state = AppState::new();
        state.resolve_scroll(6);

        state.scroll_back(2);
        assert!(!state.is_following_chat());
        assert_eq!(state.resolve_scroll(6), 4);

        state.scroll_forward(2);
        assert_eq!(state.resolve_scroll(6), 6);
        assert!(
            state.is_following_chat(),
            "reaching the bottom must re-enable auto-follow"
        );
    }

    fn buffer_rows(width: u16, height: u16, draw: impl FnOnce(&mut Frame, Rect)) -> Vec<String> {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
        terminal
            .draw(|frame| {
                let area = frame.area();
                draw(frame, area);
            })
            .unwrap();

        let buffer = terminal.backend().buffer().clone();
        (0..height)
            .map(|y| {
                (0..width)
                    .map(|x| buffer[(x, y)].symbol().to_string())
                    .collect::<String>()
                    .trim_end()
                    .to_string()
            })
            .collect()
    }

    // Renders through a real backend so the assertion is about what actually reaches the screen,
    // not about the intermediate offset arithmetic.
    fn visible_chat(state: &mut AppState, width: u16, height: u16) -> Vec<String> {
        buffer_rows(width, height, |frame, area| {
            render_chat(frame, state, area, &palette())
        })
    }

    fn numbered_state(count: usize) -> AppState {
        let mut state = AppState::new();
        state.messages.clear();
        for i in 0..count {
            state
                .messages
                .push(ChatMessage::System(format!("msg{}", i)));
        }
        state
    }

    #[test]
    fn at_rest_the_newest_messages_are_visible() {
        let mut state = numbered_state(20);
        let screen = visible_chat(&mut state, 30, 6).join("\n");

        assert!(screen.contains("msg19"), "newest missing:\n{}", screen);
        assert!(
            !screen.contains("msg0\n"),
            "oldest should be off-screen:\n{}",
            screen
        );
    }

    #[test]
    fn scrolling_up_reveals_older_messages() {
        let mut state = numbered_state(20);
        visible_chat(&mut state, 30, 6);

        for _ in 0..5 {
            state.scroll_back(1);
        }
        let screen = visible_chat(&mut state, 30, 6).join("\n");

        assert!(
            screen.contains("msg14"),
            "expected older content:\n{}",
            screen
        );
        assert!(
            !screen.contains("msg19"),
            "newest should have scrolled off:\n{}",
            screen
        );
    }

    #[test]
    fn scrolling_back_down_returns_to_the_newest() {
        let mut state = numbered_state(20);
        visible_chat(&mut state, 30, 6);
        state.scroll_back(5);
        visible_chat(&mut state, 30, 6);
        state.scroll_forward(5);

        let screen = visible_chat(&mut state, 30, 6).join("\n");
        assert!(
            screen.contains("msg19"),
            "should be back at the bottom:\n{}",
            screen
        );
    }

    // Scrolled back, the last row carries the "N more" marker, whose count legitimately changes
    // when a message arrives — so the comparison is over the rows above it.
    #[test]
    fn a_new_message_pins_the_view_to_the_bottom() {
        let mut state = numbered_state(20);
        visible_chat(&mut state, 30, 6);

        state
            .messages
            .push(ChatMessage::Agent("recem chegada".to_string()));
        let screen = visible_chat(&mut state, 30, 6).join("\n");

        assert!(
            screen.contains("recem chegada"),
            "new message not shown:\n{}",
            screen
        );
    }

    #[test]
    fn scrolling_up_then_receiving_a_message_keeps_the_reader_in_place() {
        let body = |screen: Vec<String>| screen[..screen.len() - 1].to_vec();

        let mut state = numbered_state(20);
        visible_chat(&mut state, 30, 6);
        state.scroll_back(5);
        let before = body(visible_chat(&mut state, 30, 6));

        state.messages.push(ChatMessage::Agent("nova".to_string()));
        let after = body(visible_chat(&mut state, 30, 6));

        assert_eq!(
            before, after,
            "a message arriving must not yank a scrolled-back reader"
        );
    }

    #[test]
    fn scrolled_back_the_transcript_says_how_much_is_below() {
        let mut state = numbered_state(20);
        visible_chat(&mut state, 30, 6);
        state.scroll_back(5);

        let screen = visible_chat(&mut state, 30, 6).join("\n");
        assert!(screen.contains("↓ 5 more"), "got:\n{}", screen);
    }

    #[test]
    fn at_rest_there_is_no_scroll_marker() {
        let mut state = numbered_state(20);
        let screen = visible_chat(&mut state, 30, 6).join("\n");
        assert!(!screen.contains("more"), "got:\n{}", screen);
    }

    #[test]
    fn scrolling_stops_at_the_oldest_message() {
        let mut state = numbered_state(20);
        for _ in 0..500 {
            state.scroll_back(1);
            visible_chat(&mut state, 30, 6);
        }
        let screen = visible_chat(&mut state, 30, 6).join("\n");
        assert!(
            screen.contains("msg0"),
            "oldest should be reachable:\n{}",
            screen
        );
    }

    #[test]
    fn runaway_scrolling_stops_at_the_first_line() {
        let mut state = AppState::new();
        state.resolve_scroll(7);
        for _ in 0..500 {
            state.scroll_back(1);
        }
        assert_eq!(
            state.resolve_scroll(7),
            0,
            "must not scroll above the first line"
        );
    }

    fn statusline(state: &AppState, width: u16) -> String {
        buffer_rows(width, 1, |frame, area| {
            render_statusline(frame, state, area, &palette())
        })
        .remove(0)
    }

    // The status line replaced a 34-column sidebar, so what it does and does not carry is the
    // whole design decision — network and model in, account and MCP out (they live in /status).
    #[test]
    fn the_statusline_carries_network_and_model() {
        let state = AppState::new();
        let row = statusline(&state, 90);

        assert!(row.contains(&state.active_network), "got: {:?}", row);
        assert!(row.contains(&state.active_model), "got: {:?}", row);
        assert!(row.contains("ctrl+k"), "got: {:?}", row);
    }

    #[test]
    fn the_statusline_shows_the_current_activity_while_working() {
        let mut state = AppState::new();
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Using tool: caatinga_build".to_string(),
        ));

        let row = statusline(&state, 90);
        assert!(row.contains("Building contract"), "got: {:?}", row);
    }

    // One row is all the layout budgets. A long activity string, or a narrow terminal, must not
    // wrap into a second line — there is no second line to wrap into.
    #[test]
    fn the_statusline_never_overflows_its_single_row() {
        let mut state = AppState::new();
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "a very long tool status that would otherwise overflow the whole status line"
                .to_string(),
        ));

        for width in [30u16, 45, 60, 90] {
            let row = statusline(&state, width);
            assert!(
                row.chars().count() <= width as usize,
                "overflowed at width {}: {:?}",
                width,
                row
            );
        }
    }

    // Regression: with the gap unenforced, a status line that filled the row exactly rendered
    // "Building contract? shortcuts · ctrl+k" — the hint read as part of the activity.
    #[test]
    fn the_hint_never_touches_the_text_on_its_left() {
        let mut state = AppState::new();
        state.active_model = "qwen3:4b-instruct-2507-q4_K_M".to_string();
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Using tool: caatinga_build".to_string(),
        ));

        for width in 60..120u16 {
            let row = statusline(&state, width);
            if let Some(at) = row.find("? shortcuts") {
                assert!(
                    row[..at].ends_with("  "),
                    "hint glued to the activity at width {}: {:?}",
                    width,
                    row
                );
            }
        }
    }

    #[test]
    fn mainnet_is_called_out_in_the_statusline() {
        let mut state = AppState::new();
        state.active_network = "mainnet".to_string();
        assert!(statusline(&state, 90).contains("mainnet"));
    }

    #[test]
    fn a_contract_id_is_abbreviated_rather_than_eating_the_status_line() {
        assert_eq!(abbreviate("CABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), "CABC…4567");
        // Short enough to show whole: leave it alone.
        assert_eq!(abbreviate("CABCDEF"), "CABCDEF");
    }

    #[test]
    fn truncation_marks_what_it_cut() {
        assert_eq!(truncate_to("abcdef", 4), "abc…");
        assert_eq!(truncate_to("abc", 10), "abc");
    }

    fn whole_screen(state: &mut AppState, width: u16, height: u16) -> Vec<String> {
        buffer_rows(width, height, |frame, _area| {
            render(frame, state, &Theme::Dark)
        })
    }

    // The frames are the only chrome left, so they have to be exactly two — the conversation and
    // the input — and they have to be the rounded house frame, not ratatui's square default.
    #[test]
    fn the_conversation_and_the_input_each_get_a_rounded_frame() {
        let mut state = AppState::new();
        let rows = whole_screen(&mut state, 60, 12);

        let top_corners: Vec<usize> = rows
            .iter()
            .enumerate()
            .filter(|(_, r)| r.starts_with(''))
            .map(|(i, _)| i)
            .collect();
        assert_eq!(
            top_corners,
            vec![0, 8],
            "expected two frames, got:\n{}",
            rows.join("\n")
        );

        // The input frame is the last one, and the status line sits outside it, unframed.
        assert!(rows[10].starts_with(''), "got:\n{}", rows.join("\n"));
        assert!(
            !rows[11].contains('') && rows[11].contains("testnet"),
            "status line must stay outside the frames:\n{}",
            rows.join("\n")
        );
    }

    // Text inside a frame must not touch it: without the padding the transcript rendered as
    // "│Built it: …", which reads as a rendering fault rather than as a margin.
    #[test]
    fn framed_content_keeps_a_column_of_air() {
        let mut state = AppState::new();
        state.messages.push(ChatMessage::Agent("olá".to_string()));
        state.input = "oi".to_string();

        for row in whole_screen(&mut state, 60, 12) {
            if let Some(rest) = row.strip_prefix('') {
                assert!(
                    rest.starts_with(' '),
                    "content flush against the frame: {:?}",
                    row
                );
            }
        }
    }

    fn welcome(state: &AppState, width: u16, height: u16) -> String {
        buffer_rows(width, height, |frame, area| {
            render_welcome(frame, state, area, &palette())
        })
        .join("\n")
    }

    // The banner is the only place the product says what it is, so it has to carry the Stellar
    // mark, the name, where you are, and the way in — nothing else in the interface repeats them.
    #[test]
    fn the_banner_introduces_the_session() {
        let state = AppState::new();
        let screen = welcome(&state, 90, 10);

        assert!(screen.contains("procyon"), "got:\n{}", screen);
        assert!(screen.contains("Stellar"), "got:\n{}", screen);
        for row in STELLAR_MARK {
            assert!(screen.contains(row.trim()), "mark missing:\n{}", screen);
        }
        assert!(screen.contains(&state.cwd_label), "got:\n{}", screen);
        assert!(screen.contains(&state.active_network), "got:\n{}", screen);
        assert!(screen.contains("ctrl+k"), "got:\n{}", screen);
    }

    // The working directory is a label, not a lookup: it must not change between frames and must
    // never be an absolute /home path when $HOME covers it.
    #[test]
    fn the_working_directory_is_written_the_way_a_person_writes_it() {
        let state = AppState::new();
        if std::env::var_os("HOME").is_some() && state.cwd_label != "." {
            assert!(
                !state.cwd_label.starts_with("/home/"),
                "expected a ~-relative path, got {:?}",
                state.cwd_label
            );
        }
        assert_eq!(state.cwd_label, AppState::new().cwd_label, "must be stable");
    }

    // The banner is a first impression, not a permanent header: the moment there is anything to
    // read it steps aside and the transcript owns the area.
    #[test]
    fn the_banner_gives_way_to_the_transcript() {
        let mut state = AppState::new();
        assert!(!has_conversation(&state));

        state.messages.push(ChatMessage::User("oi".to_string()));
        assert!(has_conversation(&state));
    }

    // Regression: slash commands reply with `System` and nothing else. While the banner only
    // yielded to User/Agent messages it stayed pinned over their output, so every command looked
    // like it had silently done nothing.
    #[test]
    fn a_command_reply_is_enough_to_retire_the_banner() {
        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let mut state = AppState::new();
        // Driven through the keyboard so the test covers the path a user actually takes.
        for c in "/help".chars() {
            state.handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE), &tx);
        }
        state.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE), &tx);

        assert!(has_conversation(&state), "banner would cover /help output");

        let screen = buffer_rows(90, 20, |frame, area| {
            let chunks = Layout::default()
                .direction(Direction::Vertical)
                .constraints([Constraint::Min(0)])
                .split(area);
            render_chat(frame, &mut state, chunks[0], &palette())
        })
        .join("\n");
        assert!(screen.contains("Quick actions"), "got:\n{}", screen);
    }

    fn execution_rows(state: &AppState, width: usize) -> Vec<String> {
        execution_lines(state, &palette(), width)
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
            })
            .collect()
    }

    #[test]
    fn a_phase_is_a_step_and_a_tool_call_hangs_off_it() {
        let mut state = AppState::new();
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Thinking...".to_string(),
        ));
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "Using tool: caatinga_build".to_string(),
        ));

        let rows = execution_rows(&state, 60);
        assert!(
            rows.iter().any(|r| r.starts_with("⏺ Thinking")),
            "got {:?}",
            rows
        );
        assert!(
            rows.iter()
                .any(|r| r.starts_with("  ⎿ caatinga_build — building contract")),
            "got {:?}",
            rows
        );
    }

    // Regression: the trace used to be wrapped in a hand-built border whose width arithmetic
    // sliced multibyte glyphs. There is no border now, and nothing may panic on multibyte labels.
    #[test]
    fn execution_labels_survive_multibyte_content_at_any_width() {
        let mut state = AppState::new();
        state.handle_agent_update(crate::channels::AgentUpdate::Status(
            "compilação atualizações — configuração".to_string(),
        ));

        for width in 1..40usize {
            let rows = execution_rows(&state, width);
            assert!(!rows.is_empty(), "no rows at width {}", width);
        }
    }
}