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
// 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.
//! Frame content assembly operating on a `RenderSnapshot`.
//!
//! All methods here are pure functions: they read the snapshot and produce
//! a `String` (or write into a `BufferWriter`) without touching shared state.
//! This means the `AppState` mutex is not held during any of this work.
use std::borrow::Cow;
use std::collections::HashMap;
use std::io::Write;
use chrono::Local;
use crossterm::{
queue,
style::{Color, Print},
};
use crate::app_state::AppState;
use crate::cli::ViewArgs;
use crate::device::ProcessInfo;
use crate::ui::activity_panel;
use crate::ui::buffer::BufferWriter;
use crate::ui::dashboard::{draw_dashboard_items, draw_system_view};
use crate::ui::gpu_sparkline_panel;
use crate::ui::layout::LayoutCalculator;
use crate::ui::local_header::draw_local_header_bar;
use crate::ui::renderer::{
print_chassis_info, print_cpu_info, print_function_keys, print_gpu_info,
print_loading_indicator, print_memory_info, print_mig_section, print_process_info,
print_storage_info, print_vgpu_section,
};
use crate::ui::renderers::print_chassis_energy_row;
use crate::ui::tabs::draw_tabs;
use crate::ui::text::print_colored_text;
use crate::view::render_snapshot::RenderSnapshot;
use crate::view::view_cache::ViewCache;
/// Stateless frame renderer that operates on a `RenderSnapshot`.
///
/// This struct holds no mutable state of its own. Each method takes an
/// immutable snapshot and returns the assembled frame content as a `String`.
pub struct FrameRenderer;
impl FrameRenderer {
/// Render help popup content from the snapshot.
pub fn render_help(snapshot: &RenderSnapshot, args: &ViewArgs, cols: u16, rows: u16) -> String {
let is_remote = args.hosts.is_some() || args.hostfile.is_some();
let view_state = snapshot.as_app_state();
crate::ui::help::generate_help_popup_content(cols, rows, &view_state, is_remote)
}
/// Render the alert history panel (`A` key). Lists the most recent
/// transitions newest-first with their timestamp, host, rule, and
/// transition.
pub fn render_alert_panel(snapshot: &RenderSnapshot, cols: u16, rows: u16) -> String {
let mut buffer = BufferWriter::new();
let width = cols as usize;
let title = "Alert History (press A or ESC to close)";
let header = format!(" {title:<width$}");
print_colored_text(
&mut buffer,
&header,
Color::Black,
Some(Color::Yellow),
None,
);
queue!(buffer, Print("\r\n")).unwrap();
if snapshot.alert_history.is_empty() {
let msg = "No alert transitions yet. Thresholds are configured — keep \
monitoring.";
print_colored_text(&mut buffer, msg, Color::DarkGrey, None, None);
queue!(buffer, Print("\r\n")).unwrap();
} else {
let limit = (rows as usize).saturating_sub(3).max(1);
for t in snapshot.alert_history.iter().take(limit) {
let ts = t.timestamp.format("%H:%M:%S").to_string();
let line = format!(" {ts} {msg}", msg = t.message);
let color = match t.to {
crate::ui::alerts::AlertLevel::Crit => Color::Red,
crate::ui::alerts::AlertLevel::Warn => Color::Yellow,
crate::ui::alerts::AlertLevel::Ok => Color::Green,
};
print_colored_text(&mut buffer, &line, color, None, None);
queue!(buffer, Print("\r\n")).unwrap();
}
}
buffer.get_buffer().to_string()
}
/// Render loading screen content from the snapshot.
pub fn render_loading(
snapshot: &RenderSnapshot,
is_remote: bool,
cols: u16,
rows: u16,
) -> String {
let mut buffer = BufferWriter::new();
let view_state = snapshot.as_app_state();
print_function_keys(&mut buffer, cols, rows, &view_state, is_remote);
print_loading_indicator(
&mut buffer,
cols,
rows,
snapshot.frame_counter,
&snapshot.startup_status_lines,
);
buffer.get_buffer().to_string()
}
/// Render main content (the primary monitoring view) from the snapshot.
///
/// When a `ViewCache` is provided, pre-computed sorted/filtered indices
/// are used instead of re-sorting and re-filtering on every frame.
/// Render the main TUI view.
///
/// Returns `(content, visible_process_rows)` where `visible_process_rows`
/// is the actual number of process rows that fit on screen. The caller
/// should store this value so the event handler can scroll correctly.
pub fn render_main(
snapshot: &RenderSnapshot,
args: &ViewArgs,
cols: u16,
rows: u16,
cache: Option<&ViewCache>,
) -> (String, usize) {
let width = cols as usize;
let mut buffer = BufferWriter::new();
let view_state = snapshot.as_app_state();
// Write time/date header to buffer first
let current_time = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
let version = env!("CARGO_PKG_VERSION");
let header_text = format!("all-smi - {current_time}");
let version_text = format!("v{version}");
// Get runtime environment info
let runtime_shield =
if let Some((name, color)) = snapshot.runtime_environment.display_info() {
let shield_content = format!(" {name} ");
let shield_len = shield_content.len();
Some((shield_content, color, shield_len))
} else {
None
};
// Calculate spacing to right-align version, accounting for runtime shield
let total_width = cols as usize;
let runtime_shield_len = runtime_shield
.as_ref()
.map(|(_, _, len)| len + 1)
.unwrap_or(0);
let content_length = header_text.len() + runtime_shield_len + version_text.len();
let spacing = if total_width > content_length {
" ".repeat(total_width - content_length)
} else {
" ".to_string()
};
// Print header with runtime environment shield
print_colored_text(&mut buffer, &header_text, Color::White, None, None);
if let Some((shield_content, shield_color, _)) = runtime_shield {
print_colored_text(&mut buffer, " ", Color::White, None, None);
print_colored_text(
&mut buffer,
&shield_content,
Color::Black,
Some(shield_color),
None,
);
}
print_colored_text(
&mut buffer,
&format!("{spacing}{version_text}\r\n"),
Color::White,
None,
None,
);
let is_remote = args.hosts.is_some() || args.hostfile.is_some();
// Cluster Overview, dashboard items, and the tabs row are only meaningful
// when monitoring multiple remote hosts. `is_local_mode` is false the moment
// any --hosts / --hostfile argument is supplied (see the assignment sites in
// `src/view/runner.rs::run_view_mode` / `run_local_mode`), so a single remote
// host still shows these widgets.
//
// In local mode we show the compact two-line host summary bar instead.
if view_state.is_local_mode {
draw_local_header_bar(&mut buffer, &view_state, cols);
// Activity panel: CPU per-core bars (left) + GPU sparklines (right)
if activity_panel::should_show_panel(cols) {
gpu_sparkline_panel::render_combined_activity_panel(
&mut buffer,
&view_state,
&snapshot.cpu_info,
width,
rows,
);
}
} else {
// Write remaining header content to buffer
print_colored_text(&mut buffer, "Cluster Overview\r\n", Color::Cyan, None, None);
draw_system_view(&mut buffer, &view_state, cols);
draw_dashboard_items(&mut buffer, &view_state, cols);
draw_tabs(&mut buffer, &view_state, cols);
}
// Users tab (issue #189) owns its own section and skips the
// normal GPU / chassis / device pipeline. The tab is only
// present in remote / replay mode; local mode never inserts
// the `"Users"` entry into `AppState::tabs`.
let on_users_tab = is_users_tab_selected(snapshot);
if on_users_tab {
// Budget: rows minus function-key footer minus the 4-row
// heading we already printed above.
let heading_rows = buffer.line_count() as u16;
let avail = rows.saturating_sub(heading_rows).saturating_sub(1).max(1);
crate::ui::renderers::user_renderer::render_users_tab(
&mut buffer,
&snapshot.users_aggregation,
&snapshot.users_tab_state,
&snapshot.remote_process_info,
cols,
avail,
);
print_function_keys(&mut buffer, cols, rows, &view_state, is_remote);
return (buffer.get_buffer().to_string(), 0);
}
// Topology tab (issue #190): similar short-circuit — owns the
// body of the frame, emits its own header, and skips the normal
// GPU / chassis / device pipeline.
if is_topology_tab_selected(snapshot) {
let target_host = topology_target_host(snapshot);
crate::ui::renderers::topology_renderer::render_topology_tab(
&mut buffer,
&snapshot.gpu_info,
&target_host,
snapshot.topology_view_mode,
cols,
rows,
);
print_function_keys(&mut buffer, cols, rows, &view_state, is_remote);
return (buffer.get_buffer().to_string(), 0);
}
// Render chassis information (node-level metrics)
Self::render_chassis_section(&mut buffer, snapshot, width, cache);
// Render GPU information (reuse the single view_state for layout calculation)
Self::render_gpu_section(&mut buffer, snapshot, &view_state, args, cols, rows, cache);
// Render other device information based on mode
let visible_process_rows = if is_remote {
Self::render_remote_devices(&mut buffer, snapshot, width, cache);
0
} else {
Self::render_local_devices(&mut buffer, snapshot, cols, rows, cache)
};
// Add function keys to main content view
print_function_keys(&mut buffer, cols, rows, &view_state, is_remote);
(buffer.get_buffer().to_string(), visible_process_rows)
}
fn render_gpu_section(
buffer: &mut BufferWriter,
snapshot: &RenderSnapshot,
view_state: &AppState,
args: &ViewArgs,
cols: u16,
rows: u16,
cache: Option<&ViewCache>,
) {
// Use cached sorted indices when available, otherwise fall back to
// the previous per-frame filter + sort path.
let cached_indices;
let fallback_indices;
let display_indices: &[usize] = if let Some(indices) = cache.and_then(|c| c.gpu_indices()) {
cached_indices = indices;
cached_indices
} else {
// Fallback: filter + sort inline (only reached when cache is None).
// Use .get() to guard against out-of-bounds current_tab.
let mut indices: Vec<usize> =
if let Some(tab_name) = snapshot.tabs.get(snapshot.current_tab) {
if tab_name == "All" {
(0..snapshot.gpu_info.len()).collect()
} else {
snapshot
.gpu_info
.iter()
.enumerate()
.filter(|(_, info)| info.host_id == *tab_name)
.map(|(i, _)| i)
.collect()
}
} else {
// Out-of-bounds tab index: show all (defensive)
(0..snapshot.gpu_info.len()).collect()
};
indices.sort_by(|&a, &b| {
snapshot
.sort_criteria
.sort_gpus(&snapshot.gpu_info[a], &snapshot.gpu_info[b])
});
fallback_indices = indices;
&fallback_indices
};
// Calculate content area and GPU display parameters using the shared
// view_state from render_main, avoiding a second as_app_state() call.
let content_area = LayoutCalculator::calculate_content_area(view_state, cols, rows);
let gpu_display_params =
LayoutCalculator::calculate_gpu_display_params(view_state, args, &content_area);
let max_gpu_items = gpu_display_params.max_items;
// Display GPUs with scrolling
let start_gpu_index = snapshot.gpu_scroll_offset;
let end_gpu_index = (start_gpu_index + max_gpu_items).min(display_indices.len());
// Build O(1) lookup maps for vGPU and MIG matching, replacing the
// previous per-GPU linear scans that were O(G*V) + O(G*M) per frame.
let vgpu_lookup = build_vgpu_lookup(&snapshot.vgpu_info);
let mig_lookup = build_mig_lookup(&snapshot.mig_info);
for (i, &gpu_idx) in display_indices
.iter()
.enumerate()
.skip(start_gpu_index)
.take(end_gpu_index.saturating_sub(start_gpu_index))
{
let gpu_info = &snapshot.gpu_info[gpu_idx];
let device_name_scroll_offset = snapshot
.device_name_scroll_offsets
.get(&gpu_info.uuid)
.copied()
.unwrap_or(0);
let hostname_scroll_offset = snapshot
.host_id_scroll_offsets
.get(&gpu_info.host_id)
.copied()
.unwrap_or(0);
// Filter matching (issue #186). Non-matching rows are dimmed
// by default and hidden when `filter_hide_nonmatching` is on.
let matched = crate::ui::filter_dsl::apply(snapshot.filter_query.as_ref(), gpu_info);
if !matched && snapshot.filter_hide_nonmatching {
continue;
}
// Border-flash support: when this GPU has a pending alert
// flash we prefix/postfix the row with red marker characters.
// Alternating at ~1 Hz is driven by `frame_counter`.
let flashing = snapshot.alerter.is_flashing(gpu_info.uuid.as_str())
&& (snapshot.frame_counter / 10).is_multiple_of(2);
if matched && !flashing {
// Fast path: no filter mismatch, no flash — emit directly.
print_gpu_info(
buffer,
i,
gpu_info,
cols as usize,
device_name_scroll_offset,
hostname_scroll_offset,
!view_state.is_local_mode,
);
if let Some(vgpu_host) =
lookup_vgpu_host(&vgpu_lookup, &snapshot.vgpu_info, gpu_info)
{
print_vgpu_section(buffer, vgpu_host, cols as usize);
}
if let Some(mig_host) = lookup_mig_gpu(&mig_lookup, &snapshot.mig_info, gpu_info) {
print_mig_section(buffer, mig_host, cols as usize);
}
} else {
// Render into a scratch buffer so we can post-process
// (dim for filter-mismatch, prefix for flash) before the
// bytes reach the main output.
let mut scratch = BufferWriter::new();
print_gpu_info(
&mut scratch,
i,
gpu_info,
cols as usize,
device_name_scroll_offset,
hostname_scroll_offset,
!view_state.is_local_mode,
);
if let Some(vgpu_host) =
lookup_vgpu_host(&vgpu_lookup, &snapshot.vgpu_info, gpu_info)
{
print_vgpu_section(&mut scratch, vgpu_host, cols as usize);
}
if let Some(mig_host) = lookup_mig_gpu(&mig_lookup, &snapshot.mig_info, gpu_info) {
print_mig_section(&mut scratch, mig_host, cols as usize);
}
let raw = scratch.get_buffer().to_string();
let processed = if !matched {
crate::ui::renderers::dim::dim_ansi(&raw)
} else {
raw
};
if flashing {
// Cheap border marker: bright red `!` in the first
// column of every line of the GPU block for 2 s.
let marker = "\x1b[1;31m!\x1b[0m ";
let with_marker = processed
.split_inclusive('\n')
.map(|line| format!("{marker}{line}"))
.collect::<String>();
write!(buffer, "{with_marker}").ok();
} else {
write!(buffer, "{processed}").ok();
}
}
}
}
fn render_chassis_section(
buffer: &mut BufferWriter,
snapshot: &RenderSnapshot,
width: usize,
cache: Option<&ViewCache>,
) {
if snapshot.chassis_info.is_empty() {
return;
}
// Use cached chassis indices when available
if let Some(hd) = cache.and_then(|c| c.host_device_indices()) {
if hd.chassis_indices.is_empty() {
return;
}
for (i, &idx) in hd.chassis_indices.iter().enumerate() {
let chassis = &snapshot.chassis_info[idx];
let hostname_scroll_offset = snapshot
.host_id_scroll_offsets
.get(&chassis.host_id)
.copied()
.unwrap_or(0);
print_chassis_info(buffer, i, chassis, width, hostname_scroll_offset);
// Energy session + cost row (issue #191). Self-hides
// when no chassis samples have been recorded yet.
print_chassis_energy_row(
buffer,
chassis,
snapshot.energy.integrator(),
&snapshot.energy_config,
);
}
return;
}
// Fallback: filter inline (only reached when cache is None)
let chassis_to_display: Vec<_> = if snapshot.is_local_mode {
snapshot.chassis_info.iter().collect()
} else if snapshot.current_tab == 0 {
return;
} else if snapshot.current_tab < snapshot.tabs.len() {
let current_host = &snapshot.tabs[snapshot.current_tab];
snapshot
.chassis_info
.iter()
.filter(|c| c.host_id == *current_host || c.hostname == *current_host)
.collect()
} else {
snapshot.chassis_info.iter().collect()
};
for (i, chassis) in chassis_to_display.iter().enumerate() {
let hostname_scroll_offset = snapshot
.host_id_scroll_offsets
.get(&chassis.host_id)
.copied()
.unwrap_or(0);
print_chassis_info(buffer, i, chassis, width, hostname_scroll_offset);
// Energy session + cost row (issue #191). Self-hides when no
// chassis samples have been recorded yet.
print_chassis_energy_row(
buffer,
chassis,
snapshot.energy.integrator(),
&snapshot.energy_config,
);
}
}
fn render_remote_devices(
buffer: &mut BufferWriter,
snapshot: &RenderSnapshot,
width: usize,
cache: Option<&ViewCache>,
) {
if snapshot.current_tab == 0 || snapshot.current_tab >= snapshot.tabs.len() {
return;
}
let current_hostname = &snapshot.tabs[snapshot.current_tab];
// Check connection status for the current node
let is_connected = if let Some(host_id) = snapshot.hostname_to_host_id.get(current_hostname)
{
snapshot
.connection_status
.get(host_id)
.map(|status| status.is_connected)
.unwrap_or(false)
} else {
snapshot
.connection_status
.get(current_hostname)
.map(|status| status.is_connected)
.unwrap_or(true)
};
if !is_connected {
Self::render_disconnection_notification(buffer, current_hostname, width);
return;
}
// Resolve host-device indices: use cache when available, otherwise
// build a temporary index list from an inline filter.
let fallback_cpu;
let fallback_mem;
let fallback_stor;
let (cpu_idx, mem_idx, stor_idx) = if let Some(hd) =
cache.and_then(|c| c.host_device_indices())
{
(
hd.cpu_indices.as_slice(),
hd.memory_indices.as_slice(),
hd.storage_indices.as_slice(),
)
} else {
fallback_cpu =
Self::filter_indices(&snapshot.cpu_info, |c| c.host_id == *current_hostname);
fallback_mem =
Self::filter_indices(&snapshot.memory_info, |m| m.host_id == *current_hostname);
fallback_stor =
Self::filter_indices(&snapshot.storage_info, |s| s.host_id == *current_hostname);
(
fallback_cpu.as_slice(),
fallback_mem.as_slice(),
fallback_stor.as_slice(),
)
};
// CPU
for (i, &idx) in cpu_idx.iter().enumerate() {
let cpu_info = &snapshot.cpu_info[idx];
let cpu_name_scroll_offset = snapshot
.cpu_name_scroll_offsets
.get(&format!("{}-{}", cpu_info.hostname, cpu_info.cpu_model))
.copied()
.unwrap_or(0);
let hostname_scroll_offset = snapshot
.host_id_scroll_offsets
.get(&cpu_info.host_id)
.copied()
.unwrap_or(0);
print_cpu_info(
buffer,
i,
cpu_info,
width,
false,
cpu_name_scroll_offset,
hostname_scroll_offset,
true,
);
}
// Memory
for (i, &idx) in mem_idx.iter().enumerate() {
let memory_info = &snapshot.memory_info[idx];
let hostname_scroll_offset = snapshot
.host_id_scroll_offsets
.get(&memory_info.host_id)
.copied()
.unwrap_or(0);
print_memory_info(buffer, i, memory_info, width, hostname_scroll_offset, true);
}
// Storage with scroll offset
for (i, &idx) in stor_idx
.iter()
.skip(snapshot.storage_scroll_offset)
.take(10)
.enumerate()
{
let storage_info = &snapshot.storage_info[idx];
let hostname_scroll_offset = snapshot
.host_id_scroll_offsets
.get(&storage_info.host_id)
.copied()
.unwrap_or(0);
print_storage_info(buffer, i, storage_info, width, hostname_scroll_offset, true);
}
}
/// Collect indices of elements matching a predicate.
fn filter_indices<T>(items: &[T], predicate: impl Fn(&T) -> bool) -> Vec<usize> {
items
.iter()
.enumerate()
.filter(|(_, item)| predicate(item))
.map(|(i, _)| i)
.collect()
}
fn render_disconnection_notification(buffer: &mut BufferWriter, hostname: &str, width: usize) {
writeln!(buffer).unwrap();
writeln!(buffer).unwrap();
let box_width = width.saturating_sub(4).min(60);
// Ensure minimum box width for the border characters
if box_width < 6 {
return;
}
let margin = width.saturating_sub(box_width) / 2;
let margin_str = " ".repeat(margin);
// Top border
write!(buffer, "{margin_str}").unwrap();
print_colored_text(buffer, "\u{250c}", Color::Red, None, None);
print_colored_text(
buffer,
&"\u{2500}".repeat(box_width.saturating_sub(2)),
Color::Red,
None,
None,
);
print_colored_text(buffer, "\u{2510}", Color::Red, None, None);
writeln!(buffer).unwrap();
// Content rows: title, blank, hostname, status, blank
let rows: &[(&str, Color)] = &[
("CONNECTION LOST", Color::Red),
("", Color::White),
(&format!("Node: {hostname}"), Color::Yellow),
("Unable to retrieve node information", Color::DarkGrey),
("", Color::White),
];
// Inner width available for text content (between "| " and " |")
let inner_width = box_width.saturating_sub(4);
for (text, color) in rows {
write!(buffer, "{margin_str}").unwrap();
if text.is_empty() {
// Empty row
print_colored_text(buffer, "\u{2502}", Color::Red, None, None);
print_colored_text(
buffer,
&" ".repeat(box_width.saturating_sub(2)),
Color::White,
None,
None,
);
print_colored_text(buffer, "\u{2502}", Color::Red, None, None);
} else {
// Truncate text if it exceeds available inner width
let display_text: Cow<'_, str> = if text.len() > inner_width {
Cow::Owned(text.chars().take(inner_width).collect())
} else {
Cow::Borrowed(text)
};
let pad_left = inner_width.saturating_sub(display_text.len()) / 2;
let pad_right = inner_width.saturating_sub(pad_left + display_text.len());
print_colored_text(buffer, "\u{2502} ", Color::Red, None, None);
print_colored_text(buffer, &" ".repeat(pad_left), Color::White, None, None);
print_colored_text(buffer, &display_text, *color, None, None);
print_colored_text(buffer, &" ".repeat(pad_right), Color::White, None, None);
print_colored_text(buffer, " \u{2502}", Color::Red, None, None);
}
writeln!(buffer).unwrap();
}
// Bottom border
write!(buffer, "{margin_str}").unwrap();
print_colored_text(buffer, "\u{2514}", Color::Red, None, None);
print_colored_text(
buffer,
&"\u{2500}".repeat(box_width.saturating_sub(2)),
Color::Red,
None,
None,
);
print_colored_text(buffer, "\u{2518}", Color::Red, None, None);
writeln!(buffer).unwrap();
}
/// Returns the number of visible process rows for event handler scroll calculation.
fn render_local_devices(
buffer: &mut BufferWriter,
snapshot: &RenderSnapshot,
cols: u16,
rows: u16,
cache: Option<&ViewCache>,
) -> usize {
let width = cols as usize;
// CPU information for local mode
// Per-core bars are now always shown in the Activity panel above,
// so we pass show_per_core=false here to avoid duplication.
for (i, cpu_info) in snapshot.cpu_info.iter().enumerate() {
let cpu_name_scroll_offset = snapshot
.cpu_name_scroll_offsets
.get(&format!("{}-{}", cpu_info.hostname, cpu_info.cpu_model))
.copied()
.unwrap_or(0);
let hostname_scroll_offset = snapshot
.host_id_scroll_offsets
.get(&cpu_info.host_id)
.copied()
.unwrap_or(0);
print_cpu_info(
buffer,
i,
cpu_info,
width,
false,
cpu_name_scroll_offset,
hostname_scroll_offset,
false,
);
}
// Memory information for local mode
for (i, memory_info) in snapshot.memory_info.iter().enumerate() {
let hostname_scroll_offset = snapshot
.host_id_scroll_offsets
.get(&memory_info.host_id)
.copied()
.unwrap_or(0);
print_memory_info(buffer, i, memory_info, width, hostname_scroll_offset, false);
}
// Storage information for local mode
for (i, storage_info) in snapshot.storage_info.iter().enumerate() {
let hostname_scroll_offset = snapshot
.host_id_scroll_offsets
.get(&storage_info.host_id)
.copied()
.unwrap_or(0);
print_storage_info(
buffer,
i,
storage_info,
width,
hostname_scroll_offset,
false,
);
}
// Process information for local mode (if available)
if !snapshot.process_info.is_empty() {
let lines_used = buffer.line_count();
// Add a blank line before process list
queue!(buffer, Print("\r\n")).unwrap();
// Reserve 1 line for function keys at the bottom
let function_key_rows = 1;
let available_rows = rows.saturating_sub(lines_used as u16 + 1 + function_key_rows);
// Calculate actual visible process rows (must match process_renderer logic)
// RESERVED_HEADER_ROWS = 4 ("Processes:" title, column header, separator, blank)
// footer_rows = 2 ("Showing..." + "Active..." stats)
let visible = (available_rows as usize).saturating_sub(4 + 2);
// Get current user for process coloring
let current_user = whoami::username().unwrap_or_default();
// Use cached GPU-filtered process list when available, avoiding
// a per-frame clone of the entire process vector.
let base_processes: Cow<'_, [ProcessInfo]> =
if let Some(pl) = cache.and_then(|c| c.process_display_list()) {
match &pl.filtered {
Some(filtered) => Cow::Borrowed(filtered.as_slice()),
None => Cow::Borrowed(&snapshot.process_info),
}
} else if snapshot.gpu_filter_enabled {
// Fallback: filter inline (only when cache is None)
Cow::Owned(
snapshot
.process_info
.iter()
.filter(|p| p.used_memory > 0)
.cloned()
.collect(),
)
} else {
Cow::Borrowed(&snapshot.process_info)
};
// Issue #186: also narrow by the interactive filter query. In
// hide-non-matching mode this removes non-matches; otherwise
// we leave the list as-is (process rows have far less real
// estate than GPU rows so dimming them is less useful).
let processes_to_display: Cow<'_, [ProcessInfo]> = if snapshot.filter_hide_nonmatching
&& let Some(expr) = snapshot.filter_query.as_ref()
{
Cow::Owned(
base_processes
.iter()
.filter(|p| crate::ui::filter_dsl::apply(Some(expr), *p))
.cloned()
.collect(),
)
} else {
base_processes
};
print_process_info(
buffer,
&processes_to_display,
snapshot.selected_process_index,
snapshot.start_index,
available_rows,
cols,
snapshot.process_horizontal_scroll_offset,
¤t_user,
&snapshot.sort_criteria,
&snapshot.sort_direction,
);
return visible;
}
0
}
}
/// True when the snapshot's current tab is the cluster-wide Users tab
/// (issue #189). Kept outside of [`FrameRenderer`] so it can be used
/// by tests and `render_main` alike without plumbing a snapshot through
/// multiple call sites.
fn is_users_tab_selected(snapshot: &RenderSnapshot) -> bool {
snapshot
.tabs
.get(snapshot.current_tab)
.map(|t| t == crate::ui::tabs::USERS_TAB_NAME)
.unwrap_or(false)
}
/// True when the snapshot's current tab is the per-host Topology tab
/// (issue #190).
fn is_topology_tab_selected(snapshot: &RenderSnapshot) -> bool {
snapshot
.tabs
.get(snapshot.current_tab)
.map(|t| t == crate::ui::tabs::TOPOLOGY_TAB_NAME)
.unwrap_or(false)
}
/// Pick the host to display in the Topology tab.
///
/// When the operator last pointed at a specific host tab (e.g. "node-03"),
/// we stash its name in `snapshot.topology_last_host_tab`. The Topology
/// tab itself has no host, so we have to derive one:
///
/// * In local mode the lone known host (or empty string ⇒ "(local)") is
/// returned.
/// * In remote mode we first honour the operator's remembered selection
/// (still present in the tab strip), falling back to the first host tab
/// if the remembered tab is absent or stale.
fn topology_target_host(snapshot: &RenderSnapshot) -> String {
if snapshot.is_local_mode {
return snapshot
.gpu_info
.first()
.map(|g| g.host_id.clone())
.unwrap_or_default();
}
// Remote mode: honour the operator's last-selected host tab when it
// is still in the tab strip.
if let Some(last) = snapshot.topology_last_host_tab.as_ref()
&& snapshot.tabs.iter().any(|t| t == last)
{
return last.clone();
}
// Fall through: first host-shaped tab after the reserved entries.
for tab in &snapshot.tabs {
if tab != "All"
&& tab != crate::ui::tabs::USERS_TAB_NAME
&& tab != crate::ui::tabs::TOPOLOGY_TAB_NAME
{
return tab.clone();
}
}
String::new()
}
/// Locate the [`crate::device::VgpuHostInfo`] record matching a given GPU row.
///
/// Build an O(1) lookup map from `gpu_uuid` to index in the vGPU info slice.
/// Called once per frame to replace per-GPU linear scans.
fn build_vgpu_lookup(vgpu_info: &[crate::device::VgpuHostInfo]) -> HashMap<&str, usize> {
let mut map = HashMap::with_capacity(vgpu_info.len());
for (i, host) in vgpu_info.iter().enumerate() {
map.entry(host.gpu_uuid.as_str()).or_insert(i);
}
map
}
/// Build an O(1) lookup map from `gpu_uuid` to index in the MIG info slice.
/// Called once per frame to replace per-GPU linear scans.
fn build_mig_lookup(mig_info: &[crate::device::MigGpuInfo]) -> HashMap<&str, usize> {
let mut map = HashMap::with_capacity(mig_info.len());
for (i, host) in mig_info.iter().enumerate() {
map.entry(host.gpu_uuid.as_str()).or_insert(i);
}
map
}
/// O(1) vGPU host lookup by UUID with hostname+gpu_name fallback.
///
/// Matching precedence:
/// 1. Exact `gpu_uuid` match via HashMap (authoritative, O(1)).
/// 2. Fallback: same `hostname` + matching `gpu_name` — used when UUID
/// propagation is missing (e.g. remote mode with incomplete metrics).
/// This path is a rare linear scan only hit for entries not found by UUID.
///
/// Returns `None` when no match is found, which keeps the vGPU section from
/// appearing under unrelated GPU rows.
fn lookup_vgpu_host<'a>(
lookup: &HashMap<&str, usize>,
vgpu_info: &'a [crate::device::VgpuHostInfo],
gpu: &crate::device::GpuInfo,
) -> Option<&'a crate::device::VgpuHostInfo> {
if let Some(&idx) = lookup.get(gpu.uuid.as_str()) {
return Some(&vgpu_info[idx]);
}
// Fallback: hostname + gpu_name linear scan for entries without UUID match.
vgpu_info
.iter()
.find(|v| v.hostname == gpu.hostname && v.gpu_name == gpu.name)
}
/// O(1) MIG GPU lookup by UUID with hostname+gpu_name fallback.
///
/// Same precedence as [`lookup_vgpu_host`]:
/// 1. Exact `gpu_uuid` match via HashMap (authoritative, O(1)).
/// 2. Fallback: same `hostname` + matching `gpu_name` — used when UUID
/// propagation is missing (e.g. remote mode with incomplete metrics).
///
/// Returns `None` when no match is found, keeping the MIG section from
/// appearing under unrelated GPU rows.
fn lookup_mig_gpu<'a>(
lookup: &HashMap<&str, usize>,
mig_info: &'a [crate::device::MigGpuInfo],
gpu: &crate::device::GpuInfo,
) -> Option<&'a crate::device::MigGpuInfo> {
if let Some(&idx) = lookup.get(gpu.uuid.as_str()) {
return Some(&mig_info[idx]);
}
// Fallback: hostname + gpu_name linear scan for entries without UUID match.
mig_info
.iter()
.find(|m| m.hostname == gpu.hostname && m.gpu_name == gpu.name)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::app_state::AppState;
use crate::view::render_snapshot::RenderSnapshot;
fn make_local_args() -> ViewArgs {
ViewArgs::empty()
}
fn make_snapshot() -> RenderSnapshot {
let mut state = AppState::new();
RenderSnapshot::capture(&mut state)
}
// -----------------------------------------------------------------------
// FrameRenderer: construction
// -----------------------------------------------------------------------
#[test]
fn test_frame_renderer_is_zero_sized() {
// FrameRenderer is a unit struct; assert it holds no state.
assert_eq!(std::mem::size_of::<FrameRenderer>(), 0);
}
// -----------------------------------------------------------------------
// render_loading: smoke tests
// -----------------------------------------------------------------------
#[test]
fn test_render_loading_does_not_panic() {
let snapshot = make_snapshot();
let output = FrameRenderer::render_loading(&snapshot, false, 80, 24);
// Loading screen must produce some output even when state is empty.
assert!(!output.is_empty());
}
#[test]
fn test_render_loading_remote_does_not_panic() {
let snapshot = make_snapshot();
let output = FrameRenderer::render_loading(&snapshot, true, 80, 24);
assert!(!output.is_empty());
}
#[test]
fn test_render_loading_with_startup_status_lines() {
let mut state = AppState::new();
state
.startup_status_lines
.push("Connecting to GPUs...".to_string());
let snapshot = RenderSnapshot::capture(&mut state);
// Should not panic and produce output with the status line.
let output = FrameRenderer::render_loading(&snapshot, false, 80, 24);
assert!(!output.is_empty());
}
// -----------------------------------------------------------------------
// render_main: smoke tests
// -----------------------------------------------------------------------
#[test]
fn test_render_main_does_not_panic_empty_state() {
let snapshot = make_snapshot();
let args = make_local_args();
let (output, _) = FrameRenderer::render_main(&snapshot, &args, 80, 24, None);
// Header must be present.
assert!(output.contains("all-smi"));
}
#[test]
fn test_render_main_contains_header_timestamp() {
let snapshot = make_snapshot();
let args = make_local_args();
let (output, _) = FrameRenderer::render_main(&snapshot, &args, 120, 40, None);
// The header includes the current year which is deterministic for the test run.
assert!(output.contains("all-smi - 20"));
}
#[test]
fn test_render_main_contains_version() {
let snapshot = make_snapshot();
let args = make_local_args();
let (output, _) = FrameRenderer::render_main(&snapshot, &args, 80, 24, None);
let version = env!("CARGO_PKG_VERSION");
assert!(output.contains(version));
}
// -----------------------------------------------------------------------
// render_disconnection_notification: box geometry
// -----------------------------------------------------------------------
#[test]
fn test_disconnection_notification_width_too_narrow_produces_no_box() {
// width=9 → box_width = min(9-4, 60) = 5 which is < 6, so nothing is rendered
// (only the two leading blank lines appear).
let mut buffer = BufferWriter::new();
FrameRenderer::render_disconnection_notification(&mut buffer, "node1", 9);
let output = buffer.get_buffer().to_string();
// The box should NOT be rendered; the output must not contain the box corner.
assert!(!output.contains('\u{250c}'));
}
#[test]
fn test_disconnection_notification_normal_width_contains_hostname() {
let mut buffer = BufferWriter::new();
FrameRenderer::render_disconnection_notification(&mut buffer, "my-node", 80);
let output = buffer.get_buffer().to_string();
assert!(output.contains("my-node"));
assert!(output.contains("CONNECTION LOST"));
}
#[test]
fn test_disconnection_notification_box_max_width_capped_at_60() {
// With a very wide terminal (200 cols) the box should be capped at 60 chars.
let mut buffer = BufferWriter::new();
FrameRenderer::render_disconnection_notification(&mut buffer, "node1", 200);
let output = buffer.get_buffer().to_string();
// The box top border is: "─" repeated (box_width-2) times, capped at 58 for width=200.
// Count the number of consecutive box-drawing horizontal lines.
let horizontal_line_count = output.matches('\u{2500}').count();
// max box_width = 60, so max horizontal lines per border = 58
// Two borders (top + bottom) → at most 116.
assert!(horizontal_line_count <= 116);
// But there must be at least some lines (it renders).
assert!(horizontal_line_count > 0);
}
#[test]
fn test_disconnection_notification_long_hostname_is_truncated() {
// A hostname that exceeds inner_width (box_width - 4) should be truncated.
let long_hostname = "a".repeat(200);
let mut buffer = BufferWriter::new();
FrameRenderer::render_disconnection_notification(&mut buffer, &long_hostname, 80);
let output = buffer.get_buffer().to_string();
// "Node: " prefix plus some of the hostname must appear, but not all 200 'a's.
assert!(output.contains("Node: "));
assert!(!output.contains(&long_hostname));
}
// -----------------------------------------------------------------------
// render_help: smoke test
// -----------------------------------------------------------------------
#[test]
fn test_render_help_does_not_panic() {
let snapshot = make_snapshot();
let args = make_local_args();
let output = FrameRenderer::render_help(&snapshot, &args, 80, 24);
// Help popup must produce output.
assert!(!output.is_empty());
}
// -----------------------------------------------------------------------
// topology_target_host: remote-mode host selection
// -----------------------------------------------------------------------
/// Build a minimal remote-mode snapshot whose tab strip mirrors the
/// layout produced by `update_remote_tabs`:
/// `[All, Users, Topology, host1, host2]`. Helpers for the host-
/// selection tests below.
fn make_remote_topology_snapshot(last_host: Option<&str>) -> RenderSnapshot {
let mut state = AppState::new();
state.is_local_mode = false;
state.tabs = vec![
"All".to_string(),
crate::ui::tabs::USERS_TAB_NAME.to_string(),
crate::ui::tabs::TOPOLOGY_TAB_NAME.to_string(),
"host1".to_string(),
"host2".to_string(),
];
state.topology_last_host_tab = last_host.map(|s| s.to_string());
RenderSnapshot::capture(&mut state)
}
#[test]
fn topology_target_host_uses_last_host_tab_when_set() {
// When the operator has previously selected "host2", the Topology
// tab should render that host — not fall through to the first
// host-shaped tab ("host1").
let snapshot = make_remote_topology_snapshot(Some("host2"));
assert_eq!(topology_target_host(&snapshot), "host2");
}
#[test]
fn topology_target_host_falls_back_to_first_host_when_unset() {
// With no remembered selection the renderer falls back to the
// first host-shaped tab after the reserved ones.
let snapshot = make_remote_topology_snapshot(None);
assert_eq!(topology_target_host(&snapshot), "host1");
}
#[test]
fn topology_target_host_falls_back_when_remembered_host_missing() {
// The remembered host "ghost" is not in the tab strip → fall back
// to the first host tab rather than returning the stale name.
let snapshot = make_remote_topology_snapshot(Some("ghost"));
assert_eq!(topology_target_host(&snapshot), "host1");
}
// -----------------------------------------------------------------------
// Degenerate and minimum terminal geometry (issue #326).
//
// `ui::viewport::MIN_COLS` claims to sit above every unchecked width
// subtraction in the renderer set. That claim is only worth anything if
// it is checked against a snapshot that actually reaches those
// renderers, so these drive real device rows rather than the empty
// snapshot the smoke tests above use.
// -----------------------------------------------------------------------
fn make_gpu(uuid: &str, name: &str) -> crate::device::GpuInfo {
crate::device::GpuInfo {
uuid: uuid.to_string(),
time: String::new(),
name: name.to_string(),
device_type: "GPU".to_string(),
host_id: "localhost".to_string(),
hostname: "testhost".to_string(),
instance: "testhost".to_string(),
utilization: 42.0,
ane_utilization: 5.0,
dla_utilization: None,
tensorcore_utilization: None,
temperature: 61,
used_memory: 8 * 1024 * 1024 * 1024,
total_memory: 24 * 1024 * 1024 * 1024,
frequency: 1400,
power_consumption: 120.0,
gpu_core_count: Some(38),
temperature_threshold_slowdown: Some(93),
temperature_threshold_shutdown: Some(98),
temperature_threshold_max_operating: Some(87),
temperature_threshold_acoustic: None,
performance_state: Some(2),
fan_speed_rpm: None,
numa_node_id: None,
gsp_firmware_mode: None,
gsp_firmware_version: None,
nvlink_remote_devices: Vec::new(),
gpm_metrics: None,
detail: HashMap::new(),
}
}
fn make_cpu() -> crate::device::CpuInfo {
use crate::device::{CoreType, CoreUtilization, CpuPlatformType};
crate::device::CpuInfo {
index: 0,
host_id: "localhost".to_string(),
hostname: "testhost".to_string(),
instance: "testhost".to_string(),
cpu_model: "Test CPU".to_string(),
architecture: "aarch64".to_string(),
platform_type: CpuPlatformType::AppleSilicon,
socket_count: 1,
total_cores: 4,
total_threads: 4,
base_frequency_mhz: 2400,
max_frequency_mhz: 3600,
cache_size_mb: 16,
utilization: 37.5,
temperature: Some(55),
power_consumption: Some(18.0),
per_socket_info: Vec::new(),
apple_silicon_info: None,
per_core_utilization: (0..4)
.map(|i| CoreUtilization {
core_id: i,
core_type: CoreType::Standard,
utilization: f64::from(i) * 20.0,
})
.collect(),
time: String::new(),
}
}
/// A local-mode snapshot carrying device rows, so `render_main` walks the
/// GPU and CPU gauge renderers instead of short-circuiting on empty
/// vectors. The Apple-named GPU is deliberate: it selects the
/// three-gauge layout in `gpu_renderer`, which is the narrowest-tolerant
/// row in the whole renderer set.
fn make_populated_snapshot() -> RenderSnapshot {
let mut state = AppState::new();
state.is_local_mode = true;
state.gpu_info = vec![
make_gpu("gpu-0", "Apple M3 Max"),
make_gpu("gpu-1", "NVIDIA H100 80GB HBM3"),
];
state.cpu_info = vec![make_cpu()];
RenderSnapshot::capture(&mut state)
}
#[test]
fn render_paths_survive_every_size_at_or_above_the_minimum() {
use crate::ui::viewport::{MIN_COLS, MIN_ROWS};
let snapshot = make_populated_snapshot();
let args = make_local_args();
// Bounded sweep across the interesting band just above the floor,
// plus a couple of ordinary sizes. Every width in this range crosses
// at least one gauge-layout branch.
for cols in MIN_COLS..=(MIN_COLS + 12) {
for rows in MIN_ROWS..=(MIN_ROWS + 6) {
let (main, _) = FrameRenderer::render_main(&snapshot, &args, cols, rows, None);
assert!(
!main.is_empty(),
"render_main produced nothing at {cols}x{rows}"
);
let _ = FrameRenderer::render_loading(&snapshot, false, cols, rows);
let _ = FrameRenderer::render_loading(&snapshot, true, cols, rows);
let _ = FrameRenderer::render_help(&snapshot, &args, cols, rows);
let _ = FrameRenderer::render_alert_panel(&snapshot, cols, rows);
}
}
}
#[test]
fn render_paths_survive_a_resolved_zero_size_pty() {
use crate::ui::viewport::Viewport;
// End to end for the reported reproduction: a pty with no window
// size reports 0x0, `Viewport` resolves it, and the frame composes
// normally. Before the fix this aborted in `print_function_keys`.
let viewport = Viewport::resolve(0, 0);
assert!(viewport.is_renderable());
let snapshot = make_populated_snapshot();
let args = make_local_args();
let (content, _) =
FrameRenderer::render_main(&snapshot, &args, viewport.cols, viewport.rows, None);
assert!(content.contains("all-smi"));
assert!(
content.contains("h:Help"),
"the status bar must render on a resolved zero-size pty"
);
}
#[test]
fn tall_help_popup_survives_a_one_column_terminal() {
use crate::ui::viewport::Viewport;
// The help popup only reaches its two-column shortcut layout once
// the terminal is tall enough, so a narrow-and-tall geometry is the
// one that exercises `help.rs`'s width arithmetic. Production gates
// this size out, which the assertion records.
assert!(!Viewport { cols: 1, rows: 40 }.is_renderable());
let snapshot = make_populated_snapshot();
let args = make_local_args();
let resolved = Viewport::resolve(0, 40);
let _ = FrameRenderer::render_help(&snapshot, &args, resolved.cols, resolved.rows);
}
}