all-smi 0.26.2

Command-line utility for monitoring GPU hardware. It provides a real-time view of GPU utilization, memory usage, temperature, power consumption, and other metrics.
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
// Copyright 2025 Lablup Inc. and Jeongkyu Shin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::app_state::AppState;
use crossterm::style::{Color, Stylize};

/// Generate a full-screen, colorful help interface with three sections:
/// 1. Top: Title section with ASCII logo
/// 2. Middle: Keyboard shortcuts cheat sheet  
/// 3. Bottom: Terminal usage options
pub fn generate_help_popup_content(
    cols: u16,
    rows: u16,
    state: &AppState,
    is_remote: bool,
) -> String {
    let width = cols as usize;
    let height = rows as usize;

    let mut content = String::new();

    // Create full-screen help with window border
    for row in 0..height {
        let line = match row {
            0 => format!("{}", "".repeat(width.saturating_sub(2))),
            r if r == height - 1 => format!("{}", "".repeat(width.saturating_sub(2))),
            _ => {
                let inner_content = get_row_content(row, width, height, state, is_remote);
                // Ensure content exactly fills the space between borders
                let padded_content = pad_content_to_width(inner_content, width.saturating_sub(2));
                format!("{padded_content}")
            }
        };

        content.push_str(&line);
        if row < height - 1 {
            content.push('\n');
        }
    }

    content
}

fn pad_content_to_width(content: String, target_width: usize) -> String {
    // Calculate display width correctly for Unicode characters
    let display_width = calculate_display_width(&content);

    if display_width >= target_width {
        // If content is too long, just return as-is since our content should fit
        content
    } else {
        // Pad with spaces to reach target width
        format!("{content}{}", " ".repeat(target_width - display_width))
    }
}

fn calculate_display_width(text: &str) -> usize {
    // First strip ANSI escape codes
    let clean_text = strip_ansi_codes(text);

    // Count display width of each character
    let mut width = 0;
    for ch in clean_text.chars() {
        width += char_display_width(ch);
    }
    width
}

fn char_display_width(ch: char) -> usize {
    match ch {
        // Box drawing characters (ALL-SMI logo)
        '' | '' | '' | '' | '' | '' | '' | '' | '' | '' | '' | '' | '' | '' | ''
        | '' | '' | '' | '' | '' | '' | '' => 1,

        // Arrow characters
        '' | '' | '' | '' => 1,

        // Regular ASCII characters
        c if c.is_ascii() => 1,

        // Most other Unicode characters (default to width 1 for terminal safety)
        _ => 1,
    }
}

fn get_row_content(
    row: usize,
    width: usize,
    height: usize,
    state: &AppState,
    is_remote: bool,
) -> String {
    let content_width = width.saturating_sub(2); // Account for border

    // Define section boundaries
    let title_start = 2;
    let title_end = 12;
    let shortcuts_start = 14;
    let shortcuts_end = height.saturating_sub(16); // Reserve space for terminal section
    let terminal_start = shortcuts_end + 1;

    if row >= title_start && row <= title_end {
        // TOP SECTION: Title and Logo
        render_title_section(row - title_start, content_width)
    } else if row >= shortcuts_start && row < shortcuts_end {
        // MIDDLE SECTION: Keyboard Shortcuts
        render_shortcuts_section(row - shortcuts_start, content_width, state, is_remote)
    } else if row >= terminal_start && row < height - 1 {
        // BOTTOM SECTION: Terminal Usage
        render_terminal_section(row - terminal_start, content_width)
    } else {
        // Empty spacer lines
        " ".repeat(content_width)
    }
}

fn render_title_section(line_idx: usize, width: usize) -> String {
    let title_lines = [
        "",
        "    █████╗ ██╗     ██╗          ███████╗███╗   ███╗██╗",
        "   ██╔══██╗██║     ██║          ██╔════╝████╗ ████║██║",
        "   ███████║██║     ██║    █████╗███████╗██╔████╔██║██║",
        "   ██╔══██║██║     ██║    ╚════╝╚════██║██║╚██╔╝██║██║",
        "   ██║  ██║███████╗███████╗     ███████║██║ ╚═╝ ██║██║",
        "   ╚═╝  ╚═╝╚══════╝╚══════╝     ╚══════╝╚═╝     ╚═╝╚═╝",
        "",
        "GPU Monitoring and Management Tool",
        "",
    ];

    let description_lines = ["Developed and maintained as part of the Backend.AI project."];

    if line_idx < title_lines.len() {
        center_text_colored(title_lines[line_idx], width, Color::Cyan)
    } else if line_idx < title_lines.len() + description_lines.len() {
        center_text_colored(
            description_lines[line_idx - title_lines.len()],
            width,
            Color::Green,
        )
    } else {
        " ".repeat(width)
    }
}

fn render_shortcuts_section(
    line_idx: usize,
    width: usize,
    state: &AppState,
    is_remote: bool,
) -> String {
    // Split content into left and right columns
    let mut left_column = vec![
        ("Navigation Keys:", "", "header"),
        (
            "  ← →",
            "Switch tabs (remote) / Scroll process list (local)",
            "shortcut",
        ),
        ("  ↑ ↓", "Scroll up/down in lists", "shortcut"),
        ("  PgUp PgDn", "Page up/down navigation", "shortcut"),
        ("  Home End", "Jump to top/bottom", "shortcut"),
        ("", "", ""),
        ("Display Control:", "", "header"),
        ("  H", "Toggle this help screen", "shortcut"),
        ("  F", "Toggle GPU process filter", "shortcut"),
        (
            "  /",
            "Open filter query bar (temp>85, host~=dgx, ...)",
            "shortcut",
        ),
        (
            "  Ctrl-R",
            "Recall a previous filter query (while editing)",
            "shortcut",
        ),
        ("  A", "Toggle alert history panel", "shortcut"),
        (
            "  R",
            "Reset energy session counter (keeps Prometheus total)",
            "shortcut",
        ),
        ("  V", "Jump to cluster-wide Users tab (remote)", "shortcut"),
        ("  T", "Jump to Topology tab (remote/replay)", "shortcut"),
        ("  Q", "Exit application", "shortcut"),
        ("  ESC", "Close help / clear filter / exit", "shortcut"),
        ("", "", ""),
        ("Data Sorting:", "", "header"),
        ("  D", "Sort by default (hostname+index)", "shortcut"),
        ("  U", "Sort by GPU utilization", "shortcut"),
        ("  G", "Sort by GPU memory usage", "shortcut"),
    ];

    // Add mode-specific shortcuts
    if !is_remote {
        left_column.extend(vec![
            ("  P", "Sort processes by PID", "shortcut"),
            ("  C", "Sort processes by CPU%", "shortcut"),
            ("  M", "Sort processes by memory", "shortcut"),
        ]);
    }

    // Users-tab keybindings (issue #189).  Only emitted in remote /
    // replay modes; the tab itself doesn't exist in local mode.
    if is_remote || state.replay.is_some() {
        left_column.extend(vec![
            ("", "", ""),
            ("Users tab (V):", "", "header"),
            ("  u", "Sort by username (default)", "shortcut"),
            ("  m", "Sort by total GPU memory", "shortcut"),
            ("  p", "Sort by total power (derived)", "shortcut"),
            ("  n", "Sort by node count", "shortcut"),
            ("  t", "Sort by oldest process start time", "shortcut"),
            ("  Enter", "Drill down on the selected user", "shortcut"),
            (
                "  ESC",
                "Exit drill-down (or close if top-level)",
                "shortcut",
            ),
            ("  f", "Toggle system-account filter (uid<1000)", "shortcut"),
            ("  e", "Export visible table to CSV", "shortcut"),
        ]);

        // Topology tab keybindings (issue #190).  Only visible when the
        // tab is available in the tab strip, i.e. remote / replay mode.
        left_column.extend(vec![
            ("", "", ""),
            ("Topology tab (T):", "", "header"),
            (
                "  M",
                "Toggle between graph and matrix render modes",
                "shortcut",
            ),
        ]);
    }

    // Replay mode keybindings — only shown when replay is active.
    if state.replay.is_some() {
        left_column.extend(vec![
            ("", "", ""),
            ("Replay Controls (--replay):", "", "header"),
            ("  SPACE", "Play / pause", "shortcut"),
            ("  ] / [", "Step one frame forward / back", "shortcut"),
            ("  + / -", "Cycle speed (0.25x–8x)", "shortcut"),
            ("  j / k", "Seek -10s / +10s", "shortcut"),
            ("  g", "Open timecode editor (HH:MM:SS)", "shortcut"),
            ("  L", "Toggle loop playback", "shortcut"),
        ]);
    }

    left_column.extend(vec![
        ("", "", ""),
        ("Process View Columns:", "", "header"),
        ("  PID", "Process ID", "legend"),
        ("  USER", "Process owner", "legend"),
        ("  PRI", "Priority (0-139, lower is higher)", "legend"),
        ("  NI", "Nice value (-20 to 19)", "legend"),
        ("  VIRT", "Virtual memory size", "legend"),
        ("  RES", "Resident memory size", "legend"),
        ("  S", "Process state (R/S/D/Z/T)", "legend"),
        ("  CPU%", "CPU utilization", "legend"),
        ("  MEM%", "Memory utilization", "legend"),
        ("  GPU%", "GPU utilization (if available)", "legend"),
        ("  VRAM", "GPU memory usage", "legend"),
        ("  TIME+", "Total CPU time used", "legend"),
        ("  Command", "Command line (← → to scroll)", "legend"),
    ]);

    let mut right_column = vec![
        ("Process Color Legend:", "", "header"),
        ("  Your processes", "White text", "legend"),
        ("  Root/unknown", "Dark grey text", "legend"),
        ("  High usage", "Red/Yellow based on CPU/Memory %", "legend"),
        (
            "  GPU processes",
            "Green/Cyan based on system load",
            "legend",
        ),
        ("", "", ""),
        ("Resource Gauge Legend:", "", "header"),
        (
            "  Memory gauge:",
            "[used/buffers/cache                    used%]",
            "membar",
        ),
        (
            "  Swap gauge:",
            "[swap                                   GB] (red = active)",
            "swapbar",
        ),
        ("", "", ""),
        ("Energy Session:", "", "header"),
        (
            "  Shows",
            "kWh accumulated since session start, avg W, est. cost",
            "legend",
        ),
        ("  R key", "Resets the kWh/cost session counter", "legend"),
        (
            "  Price",
            "$/kWh from [energy] TOML or ALL_SMI_ENERGY_PRICE",
            "legend",
        ),
        (
            "  Currency",
            "ALL_SMI_ENERGY_CURRENCY (default USD)",
            "legend",
        ),
        (
            "  Hide cost",
            "ALL_SMI_ENERGY_NO_COST=1 (kWh still shown)",
            "legend",
        ),
        ("", "", ""),
        ("Current Status:", "", "header"),
    ];

    // Add current sort status
    let sort_status = get_current_sort_status(&state.sort_criteria);
    right_column.push(("  Sort mode:", &sort_status, "status"));

    // Add filter status
    let filter_status = if state.gpu_filter_enabled {
        "GPU Only"
    } else {
        "All Processes"
    };
    right_column.push(("  Filter:", filter_status, "status"));

    // Handle special rows
    match line_idx {
        0 => center_text_colored("KEYBOARD SHORTCUTS & NAVIGATION", width, Color::Yellow),
        1 => "".repeat(width).with(Color::DarkGrey).to_string(),
        2 => " ".repeat(width),
        _ => {
            let content_line = line_idx - 3; // Adjust for title and separator
            let column_width = (width - 4) / 2; // Leave space for middle separator

            // Get content from both columns
            let left_content = if content_line < left_column.len() {
                let (key, desc, style) = &left_column[content_line];
                format_shortcut_line(key, desc, style, column_width)
            } else {
                " ".repeat(column_width)
            };

            let right_content = if content_line < right_column.len() {
                let (key, desc, style) = &right_column[content_line];
                format_shortcut_line(key, desc, style, column_width)
            } else {
                " ".repeat(column_width)
            };

            // Combine columns with separator
            format!("{left_content}{right_content}")
        }
    }
}

fn render_terminal_section(line_idx: usize, width: usize) -> String {
    let terminal_lines = vec![
        ("", "TERMINAL USAGE OPTIONS", "title"),
        ("", "", "separator"),
        ("", "", ""),
        ("Local Monitoring:", "", "header"),
        ("  all-smi", "Monitor local GPUs (default mode)", "command"),
        ("", "", ""),
        ("Remote Monitoring:", "", "header"),
        (
            "  all-smi view --hosts http://node1:9090",
            "Monitor specific remote hosts",
            "command",
        ),
        (
            "  all-smi view --hostfile hosts.csv",
            "Monitor hosts from CSV file",
            "command",
        ),
        ("", "", ""),
        ("Agentless SSH:", "", "header"),
        (
            "  all-smi view --ssh user@dgx-01,user@dgx-02",
            "Connect over SSH (no agent install)",
            "command",
        ),
        (
            "  all-smi view --ssh-hostfile hosts-ssh.txt",
            "SSH targets from a hostfile",
            "command",
        ),
        (
            "  --ssh-fallback nvidia-smi,rocm-smi",
            "Fallback probes when all-smi not present",
            "command",
        ),
        ("", "", ""),
        ("API Server Mode:", "", "header"),
        (
            "  all-smi api --port 9090",
            "Run as Prometheus metrics server",
            "command",
        ),
        (
            "  curl http://localhost:9090/metrics",
            "Fetch Prometheus metrics via HTTP",
            "command",
        ),
    ];

    if line_idx < terminal_lines.len() {
        let (cmd, desc, style) = &terminal_lines[line_idx];
        format_terminal_line(cmd, desc, style, width)
    } else {
        " ".repeat(width)
    }
}

fn format_shortcut_line(key: &str, desc: &str, style: &str, width: usize) -> String {
    let content = match style {
        "title" => center_text_colored(desc, width, Color::Yellow),
        "separator" => "".repeat(width).with(Color::DarkGrey).to_string(),
        "header" => format!(" {}", key.green()),
        "shortcut" => {
            if key.is_empty() {
                String::new()
            } else {
                let key_str = key.white().bold().to_string();
                let desc_str = desc.white().to_string();
                // Calculate available space for description
                let key_display_width = calculate_display_width(&key_str) + 1; // +1 for leading space
                let available_desc_width = width.saturating_sub(key_display_width + 2); // +2 for spaces
                let truncated_desc = if calculate_display_width(&desc_str) > available_desc_width {
                    let mut truncated = String::new();
                    let mut current_width = 0;
                    for ch in desc.chars() {
                        let ch_width = char_display_width(ch);
                        if current_width + ch_width + 3 > available_desc_width {
                            truncated.push_str("...");
                            break;
                        }
                        truncated.push(ch);
                        current_width += ch_width;
                    }
                    truncated
                } else {
                    desc.to_string()
                };
                format!(" {key_str:<10} {}", truncated_desc.white())
            }
        }
        "legend" => {
            let available_desc_width = width.saturating_sub(12); // 10 for key + 2 for spacing
            let truncated_desc = if desc.len() > available_desc_width {
                format!("{}...", &desc[..available_desc_width.saturating_sub(3)])
            } else {
                desc.to_string()
            };
            format!(" {key:<10} {}", truncated_desc.white())
        }
        "status" => {
            let key_str = key.cyan().to_string();
            let desc_str = desc.yellow().to_string();
            format!(" {key_str:<10} {desc_str}")
        }
        "membar" => {
            // Format memory bar with colored segments
            let colored_desc = desc
                .replace("used", &"used".green().to_string())
                .replace("buffers", &"buffers".blue().to_string())
                .replace("cache", &"cache".yellow().to_string());
            format!(" {key:<10} {colored_desc}")
        }
        "swapbar" => {
            // Mirror "membar" styling for the swap row added in issue
            // #220. The bar text is colored red to convey "active
            // swapping = bad"; the parenthetical clarifier stays in
            // the default text color so the legend remains readable.
            let colored_desc = desc.replace("swap", &"swap".red().to_string());
            format!(" {key:<10} {colored_desc}")
        }
        _ => String::new(),
    };

    // Ensure content fills exactly the width
    pad_content_to_width(content, width)
}

fn format_terminal_line(cmd: &str, desc: &str, style: &str, width: usize) -> String {
    let content = match style {
        "title" => center_text_colored(desc, width, Color::Magenta),
        "separator" => "".repeat(width).with(Color::DarkGrey).to_string(),
        "header" => format!(" {}", cmd.green()),
        "command" => {
            if cmd.is_empty() {
                String::new()
            } else {
                let formatted_cmd = format!(" {:<35}", cmd.white().bold().to_string());
                let formatted_seperator = "#".with(Color::DarkGrey).to_string();
                let formatted_desc = desc.blue().to_string();
                format!("{formatted_cmd} {formatted_seperator} {formatted_desc}")
            }
        }
        _ => String::new(),
    };

    // Ensure content fills exactly the width
    pad_content_to_width(content, width)
}

fn center_text_colored(text: &str, width: usize, color: Color) -> String {
    let display_width = calculate_display_width(text);

    if display_width >= width {
        text.to_string()
    } else {
        let total_padding = width - display_width;
        let left_padding = total_padding / 2;
        let right_padding = total_padding - left_padding;

        format!(
            "{}{}{}",
            " ".repeat(left_padding),
            text.with(color),
            " ".repeat(right_padding)
        )
    }
}

fn strip_ansi_codes(text: &str) -> String {
    // Simple ANSI escape sequence removal for length calculation
    let mut result = String::new();
    let mut chars = text.chars();

    while let Some(ch) = chars.next() {
        if ch == '\x1b' {
            // Skip ANSI escape sequence
            if chars.next() == Some('[') {
                // Skip until we find the end character (typically 'm')
                for c in chars.by_ref() {
                    if c.is_ascii_alphabetic() {
                        break;
                    }
                }
            }
        } else {
            result.push(ch);
        }
    }

    result
}

fn get_current_sort_status(sort_criteria: &crate::app_state::SortCriteria) -> String {
    match sort_criteria {
        crate::app_state::SortCriteria::Default => "Default (hostname+index)",
        crate::app_state::SortCriteria::Pid => "Process PID",
        crate::app_state::SortCriteria::User => "User",
        crate::app_state::SortCriteria::Priority => "Priority",
        crate::app_state::SortCriteria::Nice => "Nice Value",
        crate::app_state::SortCriteria::VirtualMemory => "Virtual Memory",
        crate::app_state::SortCriteria::ResidentMemory => "Resident Memory",
        crate::app_state::SortCriteria::State => "Process State",
        crate::app_state::SortCriteria::CpuPercent => "CPU Usage %",
        crate::app_state::SortCriteria::MemoryPercent => "Memory Usage %",
        crate::app_state::SortCriteria::GpuPercent => "GPU Usage %",
        crate::app_state::SortCriteria::GpuMemoryUsage => "GPU Memory Usage",
        crate::app_state::SortCriteria::CpuTime => "CPU Time",
        crate::app_state::SortCriteria::Command => "Command",
        crate::app_state::SortCriteria::Utilization => "GPU Utilization",
        crate::app_state::SortCriteria::GpuMemory => "GPU Memory",
        crate::app_state::SortCriteria::Power => "Power Consumption",
        crate::app_state::SortCriteria::Temperature => "Temperature",
    }
    .to_string()
}

#[cfg(test)]
mod tests {
    use super::{render_shortcuts_section, render_terminal_section};
    use crate::app_state::AppState;

    #[test]
    fn local_help_advertises_cpu_sort_shortcut() {
        let state = AppState::new();
        let shortcuts: String = (0..40)
            .map(|line| render_shortcuts_section(line, 118, &state, false))
            .collect::<Vec<_>>()
            .join("\n");

        assert!(
            shortcuts.contains("Sort processes by CPU%"),
            "local shortcuts must advertise the CPU sort shortcut.\n--- shortcuts ---\n{shortcuts}"
        );
    }

    #[test]
    fn remote_help_hides_local_cpu_sort_shortcut() {
        let state = AppState::new();
        let shortcuts: String = (0..40)
            .map(|line| render_shortcuts_section(line, 118, &state, true))
            .collect::<Vec<_>>()
            .join("\n");

        assert!(
            !shortcuts.contains("Sort processes by CPU%"),
            "remote shortcuts must not advertise the local-only CPU sort shortcut.\n--- shortcuts ---\n{shortcuts}"
        );
    }

    #[test]
    fn local_help_omits_obsolete_macos_sudo_command() {
        let output = render_terminal_section(0, 120)
            + "\n"
            + &render_terminal_section(1, 120)
            + "\n"
            + &render_terminal_section(2, 120)
            + "\n"
            + &render_terminal_section(3, 120)
            + "\n"
            + &render_terminal_section(4, 120)
            + "\n"
            + &render_terminal_section(5, 120);

        assert!(output.contains("Local Monitoring:"));
        assert!(output.contains("all-smi"));
        assert!(!output.contains("sudo all-smi local"));
        assert!(!output.contains("requires sudo on macOS"));
    }
}