mnemo-rs 1.7.0

Local-first shell history manager with CLI/TUI, fuzzy search, project/session context, and DevSecOps-focused release hardening.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
//! Rendu Ratatui de la TUI, style « ops dashboard ».
//!
//! Disposition verticale :
//! - **barre de commande** (haut) : badges identité (mnemo + version + projet +
//!   branche + total), barre de recherche, puces de filtres actifs ;
//! - **synthèse / KPI** : total, visibles, succès, échecs, taux d'échec,
//!   projets, shell dominant (masquée sur terminal court) ;
//! - **corps** : liste des commandes (gauche) et panneau de détails sectionné
//!   (droite, masqué sur terminal étroit) ;
//! - **pied** : raccourcis essentiels et message de statut.
//!
//! Toutes les couleurs passent par [`crate::tui::theme`] ; le formatage des
//! chaînes par [`crate::tui::format`]. Le rendu est responsive et ne panique
//! jamais, y compris en dimensions réduites.

use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap};
use ratatui::Frame;

use crate::tui::app::{Overview, TuiApp, TuiFilters, TuiMode};
use crate::tui::{format, help, theme};

/// Largeur/hauteur minimales en dessous desquelles on affiche un avertissement.
const MIN_WIDTH: u16 = 60;
const MIN_HEIGHT: u16 = 12;
/// En dessous de cette hauteur, la barre de synthèse est masquée.
const OVERVIEW_MIN_HEIGHT: u16 = 18;
/// En dessous de cette largeur, le panneau de détails est masqué.
const DETAILS_MIN_WIDTH: u16 = 84;

/// Version compilée de mnemo, affichée comme badge d'identité.
const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Point d'entrée du rendu d'une frame.
pub fn render(f: &mut Frame, app: &mut TuiApp) {
    let area = f.area();
    if area.width < MIN_WIDTH || area.height < MIN_HEIGHT {
        render_too_small(f, area);
        return;
    }

    let show_overview = area.height >= OVERVIEW_MIN_HEIGHT;
    let overview_h = if show_overview { 3 } else { 0 };

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(5), // barre de commande (badges + recherche + filtres)
            Constraint::Length(overview_h),
            Constraint::Min(1),    // corps
            Constraint::Length(2), // pied
        ])
        .split(area);

    render_command_bar(f, chunks[0], app);
    if show_overview {
        render_overview(f, chunks[1], &app.overview());
    }

    let show_details = area.width >= DETAILS_MIN_WIDTH;
    let body = if show_details {
        Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(60), Constraint::Percentage(40)])
            .split(chunks[2])
    } else {
        Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(100)])
            .split(chunks[2])
    };

    // La hauteur visible de la liste sert de taille de page.
    app.page_size = body[0].height.saturating_sub(2).max(1) as usize;

    render_list(f, body[0], app);
    if show_details {
        render_details(f, body[1], app);
    }
    render_footer(f, chunks[3], app);

    match app.mode {
        TuiMode::Help => render_help_popup(f, area),
        TuiMode::Filters => render_filters_popup(f, area, app),
        TuiMode::ConfirmDelete => render_confirm_popup(f, area, app),
        _ => {}
    }
}

fn render_too_small(f: &mut Frame, area: Rect) {
    let msg = Paragraph::new(format!(
        "Terminal trop petit ({}x{}).\nAgrandissez la fenêtre (min {MIN_WIDTH}x{MIN_HEIGHT}).",
        area.width, area.height
    ))
    .alignment(Alignment::Center)
    .style(Style::default().fg(theme::WARNING));
    f.render_widget(msg, area);
}

// -- Barre de commande -----------------------------------------------------

/// Badge « clé valeur » avec une couleur d'accent sur la valeur.
fn badge(label: &str, value: &str, color: Color) -> Vec<Span<'static>> {
    vec![
        Span::styled(format!("{label} "), theme::label()),
        Span::styled(value.to_string(), theme::badge(color)),
    ]
}

fn render_command_bar(f: &mut Frame, area: Rect, app: &TuiApp) {
    let inner = block_inner(f, area, " mnemo ");
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // badges
            Constraint::Length(1), // recherche
            Constraint::Length(1), // filtres
        ])
        .split(inner);

    f.render_widget(Paragraph::new(badges_line(app)), rows[0]);
    f.render_widget(Paragraph::new(search_line(app)), rows[1]);
    f.render_widget(Paragraph::new(filters_line(&app.filters)), rows[2]);
}

/// Ligne d'identité : mnemo + version + projet + branche + total.
fn badges_line(app: &TuiApp) -> Line<'static> {
    let mut spans = vec![
        Span::styled("mnemo ", theme::title()),
        Span::styled(format!("v{VERSION}"), theme::badge(theme::INFO)),
    ];
    let sep = || Span::styled("  ·  ", theme::label());

    if let Some(project) = &app.current_project {
        spans.push(sep());
        spans.extend(badge("projet", project, theme::INFO));
    }
    if let Some(branch) = &app.current_branch {
        spans.push(sep());
        spans.extend(badge("branche", branch, theme::ACCENT));
    }
    spans.push(sep());
    spans.extend(badge(
        "total",
        &app.records.len().to_string(),
        theme::WARNING,
    ));
    Line::from(spans)
}

/// Ligne de recherche avec curseur en mode Search.
fn search_line(app: &TuiApp) -> Line<'static> {
    let (text, style) = if app.query.is_empty() {
        (
            "(tapez pour filtrer)".to_string(),
            Style::default().fg(theme::MUTED),
        )
    } else {
        (app.query.clone(), theme::strong())
    };
    Line::from(vec![
        Span::styled("Recherche ", theme::label()),
        Span::styled(text, style),
        Span::styled(
            if app.mode == TuiMode::Search {
                ""
            } else {
                ""
            },
            Style::default().fg(theme::WARNING),
        ),
    ])
}

/// Ligne de puces décrivant les filtres actifs.
fn filters_line(filters: &TuiFilters) -> Line<'static> {
    let mut spans = vec![Span::styled("Filtres ", theme::label())];
    if filters.is_empty() {
        spans.push(Span::styled("[aucun filtre]", theme::label()));
        return Line::from(spans);
    }
    let mut chip = |label: &str, value: String, color: Color| {
        spans.push(Span::styled(format!("[{label}: "), theme::label()));
        spans.push(Span::styled(value, theme::badge(color)));
        spans.push(Span::styled("] ", theme::label()));
    };
    if let Some(p) = &filters.project {
        chip("projet", p.clone(), theme::INFO);
    }
    if let Some(b) = &filters.branch {
        chip("branche", b.clone(), theme::ACCENT);
    }
    if let Some(c) = &filters.cwd {
        chip("dossier", format::truncate_middle(c, 28), theme::INFO);
    }
    if filters.status != crate::tui::app::StatusFilter::All {
        let color = match filters.status {
            crate::tui::app::StatusFilter::Success => theme::SUCCESS,
            crate::tui::app::StatusFilter::Failure => theme::DANGER,
            crate::tui::app::StatusFilter::All => theme::MUTED,
        };
        chip("statut", filters.status.label().to_string(), color);
    }
    Line::from(spans)
}

// -- Synthèse / KPI --------------------------------------------------------

fn render_overview(f: &mut Frame, area: Rect, ov: &Overview) {
    let inner = block_inner(f, area, " Synthèse ");

    let rate = ov.failure_rate();
    let rate_color = if rate >= 25.0 {
        theme::DANGER
    } else if rate >= 10.0 {
        theme::WARNING
    } else {
        theme::SUCCESS
    };

    let mut spans = vec![
        Span::styled("Total ", theme::label()),
        Span::styled(ov.total.to_string(), theme::strong()),
        Span::styled("   Visibles ", theme::label()),
        Span::styled(ov.visible.to_string(), theme::strong()),
        Span::styled("   Succès ", theme::label()),
        Span::styled(ov.success.to_string(), theme::badge(theme::SUCCESS)),
        Span::styled("   Échecs ", theme::label()),
        Span::styled(ov.failed.to_string(), theme::badge(theme::DANGER)),
        Span::styled("   Taux d'échec ", theme::label()),
        Span::styled(format!("{rate:.1}%"), theme::badge(rate_color)),
        Span::styled("   Projets ", theme::label()),
        Span::styled(ov.projects.to_string(), theme::badge(theme::INFO)),
    ];
    if let Some(shell) = &ov.top_shell {
        spans.push(Span::styled("   Shell ", theme::label()));
        spans.push(Span::styled(shell.clone(), theme::badge(theme::ACCENT)));
    }
    f.render_widget(Paragraph::new(Line::from(spans)), inner);
}

// -- Liste -----------------------------------------------------------------

fn render_list(f: &mut Frame, area: Rect, app: &TuiApp) {
    let title = format!(" Commandes ({}) ", app.filtered.len());
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(theme::border())
        .title(Span::styled(title, theme::title()));

    if app.filtered.is_empty() {
        let hint = if app.records.is_empty() {
            "Aucune commande en base.\nImportez votre historique : mnemo import."
        } else {
            "Aucun résultat.\nAjustez la recherche ou videz les filtres (Ctrl+L)."
        };
        let p = Paragraph::new(hint)
            .block(block)
            .alignment(Alignment::Center)
            .style(theme::label());
        f.render_widget(p, area);
        return;
    }

    // Largeur disponible pour la commande, après colonnes heure/statut/contexte.
    let inner_width = area.width.saturating_sub(2) as usize;
    let ctx_width = 14usize;
    let fixed = 2 /* symbole > */ + 5 /* heure */ + 2 + 2 /* statut */ + ctx_width + 1;
    let cmd_width = inner_width.saturating_sub(fixed).max(8);

    let items: Vec<ListItem> = app
        .filtered
        .iter()
        .map(|&idx| {
            let r = &app.records[idx];
            let time = format::short_time(&r.created_at);
            let status = Span::styled(
                format!("{} ", format::status_symbol(r.exit_code)),
                Style::default().fg(theme::status_color(r.exit_code)),
            );
            let ctx = format!(
                "{:<width$}",
                format::truncate_end(&format::context_label(r), ctx_width),
                width = ctx_width
            );
            ListItem::new(Line::from(vec![
                Span::styled(format!("{time}  "), Style::default().fg(theme::WARNING)),
                status,
                Span::styled(ctx, Style::default().fg(theme::INFO)),
                Span::raw(" "),
                Span::styled(format::truncate_end(&r.command, cmd_width), theme::value()),
            ]))
        })
        .collect();

    let list = List::new(items)
        .block(block)
        .highlight_style(theme::selected())
        .highlight_symbol("> ");

    let mut state = ListState::default();
    state.select(Some(app.selected));
    f.render_stateful_widget(list, area, &mut state);
}

// -- Détails ---------------------------------------------------------------

fn render_details(f: &mut Frame, area: Rect, app: &TuiApp) {
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(theme::border())
        .title(Span::styled(" Détails ", theme::title()));
    let Some(r) = app.selected_record() else {
        let p = Paragraph::new("Sélectionnez une commande pour voir ses détails.")
            .block(block)
            .alignment(Alignment::Center)
            .style(theme::label());
        f.render_widget(p, area);
        return;
    };

    let mut lines: Vec<Line> = Vec::new();
    let opt = |v: &Option<String>| v.clone().unwrap_or_else(|| "-".to_string());

    // Section COMMAND : commande + badge de statut.
    lines.push(section("COMMAND"));
    lines.push(Line::from(Span::styled(r.command.clone(), theme::strong())));
    lines.push(Line::from(vec![
        Span::styled("statut     ", theme::label()),
        Span::styled(
            format::status_text(r.exit_code),
            theme::badge(theme::status_color(r.exit_code)),
        ),
    ]));
    lines.push(Line::from(""));

    // Section CONTEXT.
    lines.push(section("CONTEXT"));
    lines.push(field("cwd", opt(&r.cwd)));
    lines.push(field("hostname", opt(&r.hostname)));
    lines.push(field("shell", opt(&r.shell)));
    lines.push(Line::from(""));

    // Section EXECUTION.
    lines.push(section("EXECUTION"));
    lines.push(field(
        "exit_code",
        r.exit_code
            .map(|c| c.to_string())
            .unwrap_or("-".to_string()),
    ));
    lines.push(field("created_at", r.created_at.clone()));
    lines.push(Line::from(""));

    // Section GIT.
    lines.push(section("GIT"));
    lines.push(field("root", opt(&r.git_root)));
    lines.push(field("branch", opt(&r.git_branch)));
    lines.push(field("remote", opt(&r.git_remote)));
    lines.push(Line::from(""));

    // Section METADATA.
    lines.push(section("METADATA"));
    lines.push(field("id", r.id.to_string()));
    lines.push(field("session", opt(&r.session_id)));

    let p = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false });
    f.render_widget(p, area);
}

/// Titre de section dans le panneau de détails.
fn section(title: &str) -> Line<'static> {
    Line::from(Span::styled(
        title.to_string(),
        Style::default()
            .fg(theme::ACCENT)
            .add_modifier(Modifier::BOLD),
    ))
}

/// Champ « libellé valeur » avec libellé atténué.
fn field(label: &str, value: String) -> Line<'static> {
    Line::from(vec![
        Span::styled(format!("{label:<11}"), theme::label()),
        Span::styled(value, theme::value()),
    ])
}

// -- Pied ------------------------------------------------------------------

fn render_footer(f: &mut Frame, area: Rect, app: &TuiApp) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Length(1)])
        .split(area);

    f.render_widget(Paragraph::new(footer_hints(app.mode)), chunks[0]);

    if let Some(msg) = &app.status_message {
        f.render_widget(
            Paragraph::new(msg.clone()).style(Style::default().fg(theme::WARNING)),
            chunks[1],
        );
    }
}

/// Construit la ligne de raccourcis du pied selon le mode.
fn footer_hints(mode: TuiMode) -> Line<'static> {
    let pairs: &[(&str, &str)] = match mode {
        TuiMode::Details => &[
            ("Enter", "sélection"),
            ("/", "recherche"),
            ("j/k", "naviguer"),
            ("F", "filtres"),
            ("y", "copier"),
            ("e", "export"),
            ("x", "suppr"),
            ("?", "aide"),
            ("Esc", "quitter"),
        ],
        _ => &[
            ("Enter", "sélection"),
            ("Tab", "détails"),
            ("Ctrl+P/B/D", "filtrer"),
            ("Ctrl+L", "clear"),
            ("F1", "aide"),
            ("Esc", "quitter"),
        ],
    };
    let mut spans: Vec<Span<'static>> = Vec::new();
    for (i, (key, desc)) in pairs.iter().enumerate() {
        if i > 0 {
            spans.push(Span::styled("  ", theme::label()));
        }
        spans.push(Span::styled(format!("[{key}]"), theme::badge(theme::INFO)));
        spans.push(Span::styled(format!(" {desc}"), theme::label()));
    }
    Line::from(spans)
}

// -- Overlays --------------------------------------------------------------

fn render_help_popup(f: &mut Frame, area: Rect) {
    let popup = centered_rect(70, 80, area);
    f.render_widget(Clear, popup);

    let lines: Vec<Line> = help::shortcuts()
        .into_iter()
        .map(|(key, desc)| {
            if desc.is_empty() {
                Line::from(Span::styled(
                    key,
                    Style::default()
                        .fg(theme::ACCENT)
                        .add_modifier(Modifier::BOLD),
                ))
            } else {
                Line::from(vec![
                    Span::styled(format!("  {key:<20}"), theme::badge(theme::INFO)),
                    Span::styled(desc, theme::value()),
                ])
            }
        })
        .collect();

    let p = Paragraph::new(lines)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(theme::border())
                .title(Span::styled(
                    " Aide - raccourcis (Esc pour fermer) ",
                    theme::title(),
                )),
        )
        .wrap(Wrap { trim: false });
    f.render_widget(p, popup);
}

fn render_filters_popup(f: &mut Frame, area: Rect, app: &TuiApp) {
    let popup = centered_rect(60, 50, area);
    f.render_widget(Clear, popup);

    let lines = vec![
        filters_line(&app.filters),
        Line::from(""),
        Line::from(Span::styled("Depuis la sélection :", theme::label())),
        field_help("p", "filtrer par projet"),
        field_help("b", "filtrer par branche"),
        field_help("w", "filtrer par dossier (cwd)"),
        field_help("s", "statut : tous / succès / échecs"),
        field_help("c", "effacer tous les filtres"),
        Line::from(""),
        Line::from(Span::styled("Esc / f : fermer ce panneau", theme::label())),
    ];
    let p = Paragraph::new(lines).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(theme::border())
            .title(Span::styled(" Filtres interactifs ", theme::title())),
    );
    f.render_widget(p, popup);
}

/// Ligne d'aide « touche  description » pour le panneau de filtres.
fn field_help(key: &str, desc: &str) -> Line<'static> {
    Line::from(vec![
        Span::styled(format!("  {key:<3}"), theme::badge(theme::INFO)),
        Span::styled(desc.to_string(), theme::value()),
    ])
}

fn render_confirm_popup(f: &mut Frame, area: Rect, app: &TuiApp) {
    let popup = centered_rect(60, 30, area);
    f.render_widget(Clear, popup);

    let id = app
        .selected_id()
        .map(|i| i.to_string())
        .unwrap_or_else(|| "?".to_string());
    let cmd = app
        .selected_record()
        .map(|r| r.command.clone())
        .unwrap_or_default();

    let lines = vec![
        Line::from(Span::styled(
            format!("Supprimer la commande #{id} ?"),
            Style::default()
                .fg(theme::DANGER)
                .add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(Span::styled(cmd, theme::strong())),
        Line::from(""),
        Line::from(Span::styled(
            "Une sauvegarde est créée avant suppression.",
            theme::label(),
        )),
        Line::from(vec![
            Span::styled("[y]", theme::badge(theme::SUCCESS)),
            Span::styled(" confirmer   ", theme::label()),
            Span::styled("[n / Esc]", theme::badge(theme::WARNING)),
            Span::styled(" annuler", theme::label()),
        ]),
    ];
    let p = Paragraph::new(lines)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(theme::DANGER))
                .title(Span::styled(
                    " Confirmation ",
                    Style::default()
                        .fg(theme::DANGER)
                        .add_modifier(Modifier::BOLD),
                )),
        )
        .wrap(Wrap { trim: false });
    f.render_widget(p, popup);
}

// -- Utilitaires de layout -------------------------------------------------

/// Rend un bloc bordé titré et renvoie son aire intérieure.
fn block_inner(f: &mut Frame, area: Rect, title: &str) -> Rect {
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(theme::border())
        .title(Span::styled(title.to_string(), theme::title()));
    let inner = block.inner(area);
    f.render_widget(block, area);
    inner
}

/// Calcule un rectangle centré occupant `percent_x` × `percent_y` de `area`.
fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect {
    let vertical = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - percent_y) / 2),
            Constraint::Percentage(percent_y),
            Constraint::Percentage((100 - percent_y) / 2),
        ])
        .split(area);
    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - percent_x) / 2),
            Constraint::Percentage(percent_x),
            Constraint::Percentage((100 - percent_x) / 2),
        ])
        .split(vertical[1])[1]
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::CommandRecord;
    use crate::tui::app::{StatusFilter, TuiFilters};
    use ratatui::backend::TestBackend;
    use ratatui::Terminal;

    fn rec(id: i64, command: &str, exit: Option<i64>) -> CommandRecord {
        CommandRecord {
            id,
            command: command.to_string(),
            cwd: Some("/home/killian/mnemo".to_string()),
            shell: Some("bash".to_string()),
            hostname: Some("host".to_string()),
            exit_code: exit,
            created_at: "2026-06-14 17:29:11".to_string(),
            git_root: Some("/home/killian/mnemo".to_string()),
            git_branch: Some("main".to_string()),
            git_remote: None,
            session_id: Some("abcd".to_string()),
        }
    }

    fn sample() -> Vec<CommandRecord> {
        vec![
            rec(1, "cargo build", Some(0)),
            rec(2, "cargo test", Some(1)),
            rec(3, &"git commit -m ".repeat(40), Some(0)),
        ]
    }

    fn app() -> TuiApp {
        let mut a = TuiApp::new(sample(), TuiFilters::default(), String::new());
        a.set_current_context(Some("mnemo".to_string()), Some("main".to_string()));
        a
    }

    /// Rend l'app dans un backend de test de dimensions données : ne doit pas
    /// paniquer et doit produire une frame.
    fn render_at(width: u16, height: u16, app: &mut TuiApp) {
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|f| render(f, app)).unwrap();
    }

    /// Rend l'app et renvoie le texte concaténé du buffer (pour vérifier la
    /// présence de libellés).
    fn render_text(width: u16, height: u16, app: &mut TuiApp) -> String {
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|f| render(f, app)).unwrap();
        terminal
            .backend()
            .buffer()
            .content
            .iter()
            .map(|c| c.symbol())
            .collect()
    }

    #[test]
    fn rendu_dimensions_standard_sans_panique() {
        render_at(120, 40, &mut app());
    }

    #[test]
    fn rendu_synthese_affiche_les_libelles_kpi() {
        let text = render_text(120, 40, &mut app());
        assert!(text.contains("Synthèse"));
        assert!(text.contains("Total"));
        assert!(text.contains("Visibles"));
        assert!(text.contains("Succès"));
        assert!(text.contains("Échecs"));
        assert!(text.contains("Taux d'échec"));
    }

    #[test]
    fn rendu_terminal_etroit_masque_details() {
        // Largeur < DETAILS_MIN_WIDTH : pas de panneau de détails, pas de panique.
        render_at(70, 30, &mut app());
    }

    #[test]
    fn rendu_terminal_court_masque_synthese() {
        // Hauteur < OVERVIEW_MIN_HEIGHT : pas de barre de synthèse.
        render_at(120, 14, &mut app());
    }

    #[test]
    fn rendu_dimensions_minimales_sans_panique() {
        render_at(MIN_WIDTH, MIN_HEIGHT, &mut app());
    }

    #[test]
    fn rendu_trop_petit_affiche_avertissement() {
        render_at(40, 8, &mut app());
    }

    #[test]
    fn rendu_liste_vide_sans_panique() {
        let mut a = TuiApp::new(Vec::new(), TuiFilters::default(), String::new());
        render_at(120, 40, &mut a);
    }

    #[test]
    fn rendu_commande_tres_longue_sans_panique() {
        let mut a = app();
        a.push_query_char('g');
        a.push_query_char('i');
        a.push_query_char('t');
        render_at(100, 30, &mut a);
    }

    #[test]
    fn rendu_tous_les_overlays_sans_panique() {
        for mode in [TuiMode::Help, TuiMode::Filters, TuiMode::ConfirmDelete] {
            let mut a = app();
            a.mode = mode;
            render_at(120, 40, &mut a);
        }
    }

    #[test]
    fn ligne_filtres_aucun() {
        let line = filters_line(&TuiFilters::default());
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("[aucun filtre]"));
    }

    #[test]
    fn ligne_filtres_affiche_les_puces_actives() {
        let filters = TuiFilters {
            project: Some("mnemo".to_string()),
            branch: Some("main".to_string()),
            cwd: None,
            status: StatusFilter::Failure,
        };
        let line = filters_line(&filters);
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("projet"));
        assert!(text.contains("mnemo"));
        assert!(text.contains("branche"));
        assert!(text.contains("main"));
        assert!(text.contains("statut"));
        assert!(text.contains("échecs"));
    }

    #[test]
    fn badges_contiennent_version_et_contexte() {
        let line = badges_line(&app());
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("mnemo"));
        assert!(text.contains(&format!("v{VERSION}")));
        assert!(text.contains("projet"));
        assert!(text.contains("branche"));
        assert!(text.contains("total"));
    }

    #[test]
    fn pied_details_contient_les_actions_cles() {
        let line = footer_hints(TuiMode::Details);
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("Enter"));
        assert!(text.contains("recherche"));
        assert!(text.contains("export"));
        assert!(text.contains("quitter"));
    }
}