twc-rs 4.0.4

Fast single-binary CLI and interactive TUI dashboard for Timeweb Cloud
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
// SPDX-FileCopyrightText: 2026 RAprogramm <andrey.rozanov.vl@gmail.com>
// SPDX-License-Identifier: MIT

//! Details widget — shows information about the selected resource.

mod resources;

use ratatui::{
    Frame,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Paragraph}
};
use resources::{
    render_ai_agent_details, render_app_details, render_balancer_details, render_database_details,
    render_dedicated_details, render_domain_details, render_finances_details,
    render_firewall_details, render_floating_ip_details, render_image_details, render_k8s_details,
    render_knowledge_details, render_mail_details, render_network_drive_details,
    render_project_details, render_registry_details, render_s3_details, render_server_details,
    render_ssh_key_details, render_vpc_details
};
use rust_i18n::t;

use crate::tui::{
    app::{App, ResourceTab},
    themes::Palette
};

const KEY_WIDTH: usize = 13;
const RULE_WIDTH: usize = 32;

/// An action attached to an interactive detail row.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DetailAction {
    /// Trigger a new deployment of the application.
    Redeploy,
    /// One of the resource's regular API actions (start, backup, delete, ...).
    Kind(crate::tui::app::ActionKind)
}

/// One row of the details panel: its rendered line, the raw value the user
/// can copy from it, and an optional action Enter triggers on it.
pub struct DetailLine {
    pub line:   Line<'static>,
    pub copy:   Option<String>,
    pub action: Option<DetailAction>
}

impl DetailLine {
    /// True when the cursor can land on this row.
    #[must_use]
    pub const fn is_interactive(&self) -> bool {
        self.copy.is_some() || self.action.is_some()
    }
}

impl From<Line<'static>> for DetailLine {
    fn from(line: Line<'static>) -> Self {
        Self {
            line,
            copy: None,
            action: None
        }
    }
}

/// A blank spacer row.
pub(super) fn blank() -> DetailLine {
    Line::from("").into()
}

/// Builds every row of the details panel for the selected resource: the
/// per-type fields, the background-fetched deep sections, and the action
/// buttons the API offers for it.
#[must_use]
pub fn build(app: &App) -> Vec<DetailLine> {
    let palette = app.theme.palette();

    let mut rows = action_rows(app, palette);
    rows.extend(match app.active_tab {
        ResourceTab::Servers => render_server_details(app, palette),
        ResourceTab::Databases => render_database_details(app, palette),
        ResourceTab::S3 => render_s3_details(app, palette),
        ResourceTab::Kubernetes => render_k8s_details(app, palette),
        ResourceTab::Projects => render_project_details(app, palette),
        ResourceTab::Balancers => render_balancer_details(app, palette),
        ResourceTab::Registry => render_registry_details(app, palette),
        ResourceTab::Domains => render_domain_details(app, palette),
        ResourceTab::Firewall => render_firewall_details(app, palette),
        ResourceTab::FloatingIps => render_floating_ip_details(app, palette),
        ResourceTab::Images => render_image_details(app, palette),
        ResourceTab::NetworkDrives => render_network_drive_details(app, palette),
        ResourceTab::Vpc => render_vpc_details(app, palette),
        ResourceTab::DedicatedServers => render_dedicated_details(app, palette),
        ResourceTab::Mail => render_mail_details(app, palette),
        ResourceTab::Apps => render_app_details(app, palette),
        ResourceTab::AiAgents => render_ai_agent_details(app, palette),
        ResourceTab::KnowledgeBases => render_knowledge_details(app, palette),
        ResourceTab::SshKeys => render_ssh_key_details(app, palette),
        ResourceTab::Finances => render_finances_details(app, palette)
    });

    append_extra_sections(&mut rows, app, palette);

    rows
}

/// Builds the action-button block shown at the very top of the details panel,
/// so the API actions are reachable without scrolling past the fields. The
/// buttons take the first interactive indices, so the cursor opens on them.
fn action_rows(app: &App, palette: Palette) -> Vec<DetailLine> {
    let mut actions: Vec<(String, DetailAction)> = Vec::new();
    if app.active_tab == ResourceTab::Apps && !app.apps.is_empty() {
        actions.push((t!("details.redeploy").into_owned(), DetailAction::Redeploy));
    }
    if app.selected_resource().is_some() {
        for kind in app.active_tab.actions() {
            actions.push((kind.display_label().into_owned(), DetailAction::Kind(*kind)));
        }
    }
    if actions.is_empty() {
        return Vec::new();
    }

    let mut rows = vec![section(&t!("details.actions"), palette)];
    for (index, (label, action)) in actions.into_iter().enumerate() {
        rows.push(action_row(
            &label,
            action,
            app.detail_open && app.detail_selected == index,
            palette
        ));
    }
    rows.push(blank());
    rows
}

/// The interactive index the details cursor should start on.
///
/// It lands on the first field below the action buttons, so a stray extra
/// Enter right after opening never fires an action, while the buttons stay
/// one `Up` away.
#[must_use]
pub fn initial_cursor(app: &App) -> usize {
    let buttons = action_rows(app, app.theme.palette())
        .iter()
        .filter(|r| r.is_interactive())
        .count();
    if buttons < interactive_len(app) {
        buttons
    } else {
        0
    }
}

/// The copy value and action of the `index`-th interactive row.
#[must_use]
pub fn interactive_at(app: &App, index: usize) -> Option<(Option<String>, Option<DetailAction>)> {
    build(app)
        .into_iter()
        .filter(DetailLine::is_interactive)
        .nth(index)
        .map(|row| (row.copy, row.action))
}

/// Number of interactive rows in the current details panel.
#[must_use]
pub fn interactive_len(app: &App) -> usize {
    build(app).iter().filter(|r| r.is_interactive()).count()
}

/// Renders the details panel.
///
/// Interactive rows carry a cursor highlight, the text flows into smart
/// multi-column layout, and live CPU/RAM sparklines appear when the resource
/// reports statistics. Returns the clamped scroll offset actually used.
pub fn render(frame: &mut Frame, area: Rect, app: &App, border_color: Color) -> u16 {
    let palette = app.theme.palette();
    let rows = build(app);

    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(border_color))
        .title(Line::from(Span::styled(
            format!(" {} ", breadcrumbs(app)),
            Style::default()
                .fg(palette.title)
                .add_modifier(Modifier::BOLD)
        )));
    let inner = block.inner(area);
    frame.render_widget(block, area);
    if inner.height == 0 || inner.width == 0 {
        return 0;
    }

    let charts_h = chart_rows(app, inner);
    let text_area = Rect::new(
        inner.x,
        inner.y,
        inner.width,
        inner.height.saturating_sub(charts_h)
    );
    if charts_h > 0 {
        render_charts(
            frame,
            Rect::new(inner.x, inner.y + text_area.height, inner.width, charts_h),
            app,
            palette
        );
    }

    let mut selected_abs = None;
    let mut interactive_seen = 0usize;
    let lines: Vec<Line> = rows
        .into_iter()
        .enumerate()
        .map(|(abs, row)| {
            let interactive = row.is_interactive();
            let mut line = row.line;
            if interactive {
                if interactive_seen == app.detail_selected {
                    selected_abs = Some(abs);
                    if row.action.is_some() {
                        line.spans.insert(0, Span::raw(" "));
                    } else {
                        line.spans.insert(
                            0,
                            Span::styled("\u{258E}", Style::default().fg(palette.accent))
                        );
                    }
                } else {
                    line.spans.insert(0, Span::raw(" "));
                }
                interactive_seen += 1;
            } else {
                line.spans.insert(0, Span::raw(" "));
            }
            line
        })
        .collect();

    render_columns(frame, text_area, lines, app.detail_scroll, selected_abs)
}

/// Rows reserved at the bottom for the CPU/RAM sparklines, when the selected
/// resource has live statistics loaded and the panel is tall enough.
fn chart_rows(app: &App, inner: Rect) -> u16 {
    let has_stats = matches!(app.active_tab, ResourceTab::Apps | ResourceTab::Servers)
        && (!app.cpu_history.is_empty() || !app.ram_history.is_empty());
    if has_stats && inner.height >= 14 {
        8
    } else {
        0
    }
}

/// Renders every live metric series as a sparkline: CPU and RAM as
/// percentages, network in/out as humanized rates. The charts flow into as
/// many columns as the panel width fits, so four series still read well on
/// a narrow terminal.
fn render_charts(frame: &mut Frame, area: Rect, app: &App, palette: Palette) {
    use ratatui::widgets::Sparkline;

    /// One metric series ready for the sparkline grid: its title, samples,
    /// line color and the formatter for the latest value in the chart title.
    type ChartSeries = (String, Vec<f64>, Color, fn(f64) -> String);

    let percent = |v: f64| format!("{v:.1}%");
    let rate = crate::tui::humanize::bytes_rate;
    let mut charts: Vec<ChartSeries> = Vec::new();
    if !app.cpu_history.is_empty() {
        let data = app.cpu_history.iter().copied().collect();
        charts.push(("CPU".to_string(), data, palette.accent, percent));
    }
    if !app.ram_history.is_empty() {
        let data = app.ram_history.iter().copied().collect();
        charts.push(("RAM".to_string(), data, palette.success, percent));
    }
    if !app.net_in_history.is_empty() {
        let data = app.net_in_history.iter().copied().collect();
        charts.push((
            t!("details.net_in").into_owned(),
            data,
            palette.warning,
            rate
        ));
    }
    if !app.net_out_history.is_empty() {
        let data = app.net_out_history.iter().copied().collect();
        charts.push((
            t!("details.net_out").into_owned(),
            data,
            palette.header,
            rate
        ));
    }
    if charts.is_empty() {
        return;
    }

    let cols = charts.len().min(usize::from(area.width / 24).max(1));
    let rows = charts.len().div_ceil(cols);
    let row_areas =
        ratatui::layout::Layout::vertical(vec![ratatui::layout::Constraint::Fill(1); rows])
            .split(area);

    for (row_area, row_charts) in row_areas.iter().zip(charts.chunks(cols)) {
        let cells = ratatui::layout::Layout::horizontal(vec![
            ratatui::layout::Constraint::Fill(1);
            row_charts.len()
        ])
        .spacing(2)
        .split(*row_area);
        for ((title, data, color, label), cell) in row_charts.iter().zip(cells.iter()) {
            #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            let points: Vec<u64> = data.iter().map(|v| (v.max(0.0) * 100.0) as u64).collect();
            let last = data.last().copied().unwrap_or(0.0);
            let spark = Sparkline::default()
                .block(
                    Block::default()
                        .borders(Borders::TOP)
                        .border_style(Style::default().fg(palette.border))
                        .title(Line::from(Span::styled(
                            format!(" {title} {} ", label(last)),
                            Style::default().fg(palette.header)
                        )))
                )
                .data(points)
                .style(Style::default().fg(*color));
            frame.render_widget(spark, *cell);
        }
    }
}

/// Builds the breadcrumb trail for the panel border: the project the user
/// drilled through (when any) and the resource the details describe.
fn breadcrumbs(app: &App) -> String {
    let name = app
        .selected_resource()
        .map_or_else(|| t!("details.title").into_owned(), |(_, name)| name);
    app.drill_view().map_or_else(
        || format!("{} \u{2192} {name}", app.active_tab.display_name()),
        |drill| format!("{} \u{2192} {name}", drill.title)
    )
}

/// Horizontal gap between details columns.
const COLUMN_GAP: u16 = 3;

/// Appends the background-fetched deep-detail sections (connection, nested
/// databases, tariff, ...) for the resource currently shown, when loaded.
fn append_extra_sections(text: &mut Vec<DetailLine>, app: &App, palette: Palette) {
    let Some((id, _)) = app.selected_resource() else {
        return;
    };
    let Some(sections) = app.detail_extra.get(&(app.active_tab, id)) else {
        return;
    };
    for (title, rows) in sections {
        text.push(blank());
        text.push(heading(title, palette));
        text.push(rule(palette));
        for (key, value) in rows {
            text.push(kv(key, value.clone(), name_style(palette), palette));
        }
    }
}

/// Lays the detail lines out smartly: when they exceed the panel height and
/// the panel is wide enough, they flow into additional columns instead of
/// hiding below the fold. The column width comes from the widest line of the
/// actual content. The scroll offset follows the cursor row when one is
/// given, and is always clamped to the content.
///
/// Returns the clamped scroll offset actually used, so the caller can write
/// it back and the scroll state never runs past the content.
fn render_columns(
    frame: &mut Frame,
    inner: Rect,
    text: Vec<Line<'static>>,
    scroll: u16,
    follow: Option<usize>
) -> u16 {
    let height = usize::from(inner.height);
    if height == 0 {
        return 0;
    }
    let column_width = u16::try_from(text.iter().map(Line::width).max().unwrap_or(0))
        .unwrap_or(u16::MAX)
        .clamp(1, inner.width);
    let max_cols = usize::from((inner.width + COLUMN_GAP) / (column_width + COLUMN_GAP)).max(1);
    let needed = text.len().div_ceil(height);
    let cols = needed.clamp(1, max_cols);

    let capacity = cols * height;
    let max_scroll = text.len().saturating_sub(capacity);
    let mut offset = usize::from(scroll).min(max_scroll);
    if let Some(target) = follow {
        if target < offset {
            offset = target;
        } else if target >= offset + capacity {
            offset = target + 1 - capacity;
        }
    }
    let clamped = u16::try_from(offset).unwrap_or(u16::MAX);
    let visible: Vec<Line> = text.into_iter().skip(offset).take(capacity).collect();

    if cols == 1 {
        frame.render_widget(Paragraph::new(visible), inner);
        return clamped;
    }

    let mut constraints = Vec::with_capacity(cols);
    for _ in 0..cols - 1 {
        constraints.push(ratatui::layout::Constraint::Length(column_width));
    }
    constraints.push(ratatui::layout::Constraint::Min(10));
    let areas = ratatui::layout::Layout::horizontal(constraints)
        .spacing(COLUMN_GAP)
        .split(inner);

    for (chunk, column) in visible.chunks(height).zip(areas.iter()) {
        frame.render_widget(Paragraph::new(chunk.to_vec()), *column);
    }
    clamped
}

/// Builds the bold heading line shown at the top of a populated panel.
pub(super) fn heading(name: &str, palette: Palette) -> DetailLine {
    Line::from(Span::styled(
        name.to_string(),
        Style::default()
            .fg(palette.title)
            .add_modifier(Modifier::BOLD)
    ))
    .into()
}

/// Builds a dim horizontal rule used to separate sections.
pub(super) fn rule(palette: Palette) -> DetailLine {
    Line::from(Span::styled(
        "\u{2500}".repeat(RULE_WIDTH),
        Style::default().fg(palette.dim)
    ))
    .into()
}

/// Builds a dim, bold section header line.
pub(super) fn section(label: &str, palette: Palette) -> DetailLine {
    Line::from(Span::styled(
        label.to_string(),
        Style::default()
            .fg(palette.header)
            .add_modifier(Modifier::BOLD)
    ))
    .into()
}

/// Builds a key/value row, dimming the key via the palette's dim color.
/// The raw value is attached for copying. Keys longer than the standard
/// column keep at least two spaces before the value instead of gluing to it.
pub(super) fn kv(key: &str, value: String, value_style: Style, palette: Palette) -> DetailLine {
    let padded = if key.chars().count() >= KEY_WIDTH {
        format!("{key}  ")
    } else {
        format!("{key:<KEY_WIDTH$}")
    };
    DetailLine {
        line:   Line::from(vec![
            Span::styled(padded, Style::default().fg(palette.dim)),
            Span::styled(value.clone(), value_style),
        ]),
        copy:   Some(value),
        action: None
    }
}

/// Builds a key/value row that falls back to a dim `—` when the value is
/// empty, keeping the field visible so the panel layout stays stable across
/// selections instead of collapsing rows in and out.
pub(super) fn kv_field(
    key: &str,
    value: &str,
    value_style: Style,
    palette: Palette
) -> DetailLine {
    if value.is_empty() {
        let mut row = kv(
            key,
            "\u{2014}".to_string(),
            Style::default().fg(palette.dim),
            palette
        );
        row.copy = None;
        return row;
    }
    kv(key, value.to_string(), value_style, palette)
}

/// Builds a status row rendered as a colored `● label` chip.
pub(super) fn chip(key: &str, label: &str, color: Color, palette: Palette) -> DetailLine {
    DetailLine {
        line:   Line::from(vec![
            Span::styled(
                format!("{key:<KEY_WIDTH$}"),
                Style::default().fg(palette.dim)
            ),
            Span::styled(
                format!("\u{25CF} {label}"),
                Style::default().fg(color).add_modifier(Modifier::BOLD)
            ),
        ]),
        copy:   Some(label.to_string()),
        action: None
    }
}

/// Builds a status chip colored by the generic status classifier from
/// [`crate::tui::widgets::resource_list::status_view`].
pub(super) fn status_chip(key: &str, status: &str, palette: Palette) -> DetailLine {
    let (color, label) = crate::tui::widgets::resource_list::status_view(status, &palette);
    chip(key, &label, color, palette)
}

/// Builds an action-button row through the shared button chip: Enter on it
/// triggers `action`, and the chip fills with the accent color while the
/// details cursor rests on it.
pub(super) fn action_row(
    label: &str,
    action: DetailAction,
    focused: bool,
    palette: Palette
) -> DetailLine {
    DetailLine {
        line:   crate::tui::widgets::button::chip(label, focused, &palette),
        copy:   None,
        action: Some(action)
    }
}

/// Builds a centered, dim empty-state notice.
pub(super) fn empty(message: &str, palette: Palette) -> Vec<DetailLine> {
    vec![
        blank(),
        Line::from(Span::styled(
            format!("  {message}"),
            Style::default()
                .fg(palette.dim)
                .add_modifier(Modifier::ITALIC)
        ))
        .into(),
    ]
}

pub(super) fn accent(palette: Palette) -> Style {
    Style::default().fg(palette.accent)
}

pub(super) fn name_style(palette: Palette) -> Style {
    Style::default().fg(palette.fg).add_modifier(Modifier::BOLD)
}

pub(super) fn warn(palette: Palette) -> Style {
    Style::default().fg(palette.warning)
}

/// Widget wrapper for the details panel.
pub struct DetailsWidget {
    enabled: bool
}

impl DetailsWidget {
    /// Creates a new details widget with enabled state.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether the widget is initially visible.
    #[must_use]
    pub const fn new(enabled: bool) -> Self {
        Self {
            enabled
        }
    }
}

impl crate::tui::widgets::Widget for DetailsWidget {
    fn id(&self) -> &'static str {
        "details"
    }

    fn name(&self) -> &'static str {
        "Details"
    }

    fn enabled(&self) -> bool {
        self.enabled
    }

    fn toggle(&mut self) {
        self.enabled = !self.enabled;
    }

    fn render(&self, frame: &mut Frame, area: Rect, app: &App) {
        let border_color = if app.focus == crate::tui::app::Focus::Details {
            app.theme.palette().accent
        } else {
            app.theme.palette().border
        };
        render(frame, area, app, border_color);
    }
}

#[cfg(test)]
mod tests {
    use ratatui::{Terminal, backend::TestBackend};

    use super::*;
    use crate::tui::app::{App, DatabaseSummary};

    #[test]
    fn scroll_state_clamps_to_content_each_frame() {
        let mut app = App::new(5);
        app.active_tab = crate::tui::app::ResourceTab::Databases;
        app.databases = vec![DatabaseSummary {
            id: 1,
            name: "db".to_string(),
            status: "started".to_string(),
            engine: "postgres".to_string(),
            size_mb: 100,
            ..Default::default()
        }];
        app.detail_scroll = 500;
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| {
                app.detail_scroll = render(f, Rect::new(0, 0, 80, 24), &app, Color::Reset);
            })
            .unwrap();
        assert_eq!(
            app.detail_scroll, 0,
            "short content must clamp runaway scroll back to zero"
        );
    }

    #[test]
    fn finances_details_show_the_balance() {
        let mut app = App::new(5);
        app.active_tab = crate::tui::app::ResourceTab::Finances;
        app.finances = Some(crate::tui::app::FinancesSummary {
            balance: 987.65,
            currency: "RUB".to_string(),
            monthly_cost: 300.0,
            hourly_cost: 0.42,
            ..Default::default()
        });
        let rows = build(&app);
        let copies: Vec<&str> = rows.iter().filter_map(|r| r.copy.as_deref()).collect();
        assert!(copies.contains(&"987.65 RUB"), "copies: {copies:?}");
        assert!(copies.contains(&"300.00 RUB"), "copies: {copies:?}");
        assert!(copies.contains(&"0.42 RUB"), "copies: {copies:?}");
    }

    #[test]
    fn ssh_key_details_expose_the_copyable_body_and_used_by() {
        let mut app = App::new(5);
        app.active_tab = crate::tui::app::ResourceTab::SshKeys;
        app.ssh_keys = vec![crate::tui::app::SshKeySummary {
            id:         7,
            name:       "laptop".to_string(),
            body:       "ssh-ed25519 AAAA laptop".to_string(),
            created_at: "2026-06-08T02:33:05+00:00".to_string(),
            used_by:    vec!["web-1".to_string()],
            is_default: true
        }];
        let rows = build(&app);
        let copies: Vec<&str> = rows.iter().filter_map(|r| r.copy.as_deref()).collect();
        assert!(copies.contains(&"ssh-ed25519 AAAA laptop"), "{copies:?}");
        assert!(copies.contains(&"web-1"), "{copies:?}");
    }

    #[test]
    fn long_details_flow_into_columns_on_wide_panels() {
        let mut app = App::new(5);
        app.active_tab = crate::tui::app::ResourceTab::Databases;
        app.databases = vec![DatabaseSummary {
            id: 1,
            name: "db".to_string(),
            status: "started".to_string(),
            engine: "postgres".to_string(),
            size_mb: 100,
            config: (0..40)
                .map(|i| (format!("param_{i}"), i.to_string()))
                .collect(),
            ..Default::default()
        }];
        let (w, h) = (140u16, 14u16);
        let backend = TestBackend::new(w, h);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| {
                render(f, Rect::new(0, 0, w, h), &app, Color::Reset);
            })
            .unwrap();
        let buf = terminal.backend().buffer().clone();
        let mut second_column = String::new();
        for y in 1..h - 1 {
            for x in w / 3..w - 1 {
                second_column.push_str(buf[(x, y)].symbol());
            }
        }
        assert!(
            second_column.contains("param_"),
            "expected a second column of parameters on a wide panel"
        );
    }
}