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
// 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 std::io::Write;
use crossterm::{queue, style::Color, style::Print};
use crate::app_state::AppState;
use crate::metrics::gpu_readings;
use crate::ui::buffer::BufferWriter;
use crate::ui::led_grid;
use crate::ui::remote_sparkline_panel;
use crate::ui::text::{format_ram_value, print_colored_text};
pub fn draw_system_view<W: Write>(stdout: &mut W, state: &AppState, cols: u16) {
let box_width = (cols as usize).min(80);
// Calculate cluster statistics
let is_local_mode = state.is_local_mode;
let total_nodes = if is_local_mode {
1 // Local mode has 1 node
} else {
// Count only host tabs — `state.tabs` also carries the reserved
// cluster-level entries (All, Users, Topology). Counting them as
// nodes is what caused `50/52` on a 50-host cluster.
crate::ui::tabs::host_tab_count(&state.tabs)
};
let live_nodes = if is_local_mode {
1 // Local node is always considered live
} else {
state
.connection_status
.values()
.filter(|status| status.is_connected)
.count()
};
let total_gpus = state.gpu_info.len();
// Check if we're on Apple Silicon. The native reader writes the
// architecture detail under the lowercase "architecture" key
// (see device/readers/apple_silicon_native.rs); previously this lookup
// used "Architecture" and never matched, so the special-case path
// (thermal pressure display, unified memory totals, etc.) was dead.
let is_apple_silicon = state.gpu_info.iter().any(|gpu| {
gpu.detail
.get("architecture")
.map(|arch| arch == "Apple Silicon")
.unwrap_or(false)
});
// Calculate GPU cores/count based on mode
// - Remote mode: show number of GPUs in the cluster
// - Local Apple Silicon: show actual GPU core count
// - Local non-Apple Silicon: show number of GPUs
let gpu_cores_display = if !is_local_mode {
// Remote mode: show total number of GPUs
total_gpus
} else if is_apple_silicon {
// Local Apple Silicon: show actual GPU core count
state
.gpu_info
.iter()
.map(|gpu| gpu.gpu_core_count.unwrap_or(0) as usize)
.sum::<usize>()
} else {
// Local non-Apple Silicon: show number of GPUs
total_gpus
};
let total_memory_gb = if is_apple_silicon {
// Use system RAM for Apple Silicon
state
.memory_info
.iter()
.map(|memory| memory.total_bytes)
.sum::<u64>() as f64
/ (1024.0 * 1024.0 * 1024.0)
} else {
// Use GPU memory for other platforms
state
.gpu_info
.iter()
.map(|gpu| gpu.total_memory)
.sum::<u64>() as f64
/ (1024.0 * 1024.0 * 1024.0)
};
// Calculate total power
// For Apple Silicon: use combined power (CPU + GPU + ANE) from native metrics
// For other platforms: sum GPU power consumption
let total_power_watts = if is_apple_silicon {
// Try to get combined power from GPU detail (set by native metrics manager)
state
.gpu_info
.iter()
.filter_map(|gpu| {
gpu.detail
.get("combined_power_mw")
.and_then(|s| s.parse::<f64>().ok())
.map(|mw| mw / 1000.0) // Convert mW to W
})
.next() // Only one GPU entry for Apple Silicon
.unwrap_or_else(|| {
// Fallback to GPU power if combined power not available
gpu_readings::total_power_watts(&state.gpu_info)
})
} else {
gpu_readings::total_power_watts(&state.gpu_info)
};
// Calculate total CPU cores
let total_cpu_cores = state
.cpu_info
.iter()
.map(|cpu| {
if let Some(apple_info) = &cpu.apple_silicon_info {
apple_info.p_core_count + apple_info.e_core_count
} else {
cpu.total_cores
}
})
.sum::<u32>();
// Calculate total system memory
let total_system_memory_gb = state
.memory_info
.iter()
.map(|memory| memory.total_bytes)
.sum::<u64>() as f64
/ (1024.0 * 1024.0 * 1024.0);
let used_system_memory_gb = state
.memory_info
.iter()
.map(|memory| memory.used_bytes)
.sum::<u64>() as f64
/ (1024.0 * 1024.0 * 1024.0);
// Calculate averages. These skip devices with no reading rather than
// folding a sentinel in, and render N/A when nothing reported at all —
// an average over zero reporting GPUs is not 0% (issue #325).
let avg_utilization = gpu_readings::mean_utilization(&state.gpu_info);
// Average GPU temperature in °C — shown identically on every platform.
// On Apple Silicon, gpu.temperature is sourced from the SMC CPU die sensor
// (CPU/GPU share the same SoC die), so this is a real die temperature
// rather than the qualitative thermal-pressure text we used to show.
let avg_temperature = gpu_readings::mean_temperature(&state.gpu_info);
let avg_temperature_display = match avg_temperature {
Some(temp) => format!("{temp:.0}°C"),
None => "N/A".to_string(),
};
// The second-row temperature cell is platform-dependent:
// - On Apple Silicon (single SoC die) standard deviation is meaningless,
// so we surface NSProcessInfo's thermal pressure level instead — that
// qualitative reading is the only OS-blessed thermal hint Apple exposes.
// - On multi-GPU platforms we keep the cross-GPU temperature spread.
let (temp_secondary_label, temp_secondary_display) = if is_apple_silicon && total_gpus > 0 {
let thermal_pressure = state
.gpu_info
.first()
.and_then(|gpu| gpu.detail.get("thermal_pressure"))
.cloned()
.unwrap_or_else(|| "Unknown".to_string());
("Thermal", thermal_pressure)
} else {
let display = match gpu_readings::temperature_std_dev(&state.gpu_info) {
Some(sd) => format!("±{sd:.1}°C"),
// Fewer than two devices reported a temperature, so the spread
// is undefined. Preserves the previous "±0.0°C" for the
// single-GPU case, which callers read as "no spread".
None if total_gpus <= 1 => "±0.0°C".to_string(),
None => "N/A".to_string(),
};
("Temp. Stdev", display)
};
let avg_power = if total_gpus > 0 {
total_power_watts / total_gpus as f64
} else {
0.0
};
// Calculate used GPU memory in GB
let used_gpu_memory_gb = if is_apple_silicon {
// Use system RAM for Apple Silicon
state
.memory_info
.iter()
.map(|memory| memory.used_bytes)
.sum::<u64>() as f64
/ (1024.0 * 1024.0 * 1024.0)
} else {
// Use GPU memory for other platforms
state
.gpu_info
.iter()
.map(|gpu| gpu.used_memory)
.sum::<u64>() as f64
/ (1024.0 * 1024.0 * 1024.0)
};
// Render dashboard card rows into a buffer so we can interleave with
// the LED grid in remote mode.
let card_lines = {
let mut buf = BufferWriter::new();
// First row: | Nodes | Total RAM | GPU Cores | Total GPU RAM | Avg. Temp | Total Power |
print_dashboard_row(
&mut buf,
&[
(
"Nodes",
format!("{live_nodes}/{total_nodes}"),
Color::Yellow,
),
(
"Total RAM",
format_ram_value(total_system_memory_gb),
Color::Green,
),
("GPU Cores", format!("{gpu_cores_display}"), Color::Cyan),
("Total VRAM", format_ram_value(total_memory_gb), Color::Blue),
("Avg. Temp", avg_temperature_display, Color::Magenta),
(
"Total Power",
format!("{:.1}kW", total_power_watts / 1000.0),
Color::Red,
),
],
box_width,
);
// Second row: | CPU Cores | Used RAM | GPU Util | Used GPU RAM | Temp Stdev | Avg. Power |
print_dashboard_row(
&mut buf,
&[
("CPU Cores", format!("{total_cpu_cores}"), Color::Cyan),
(
"Used RAM",
format_ram_value(used_system_memory_gb),
Color::Green,
),
(
"GPU Util",
match avg_utilization {
Some(util) => format!("{util:.1}%"),
None => "N/A".to_string(),
},
Color::Blue,
),
(
"Used VRAM",
format_ram_value(used_gpu_memory_gb),
Color::Blue,
),
(temp_secondary_label, temp_secondary_display, Color::Magenta),
("Avg. Power", format!("{avg_power:.1}W"), Color::Red),
],
box_width,
);
let raw = buf.get_buffer().to_string();
raw.split("\r\n")
.filter(|line| !line.is_empty())
.map(String::from)
.collect::<Vec<_>>()
};
// In remote mode, render LED grid beside the dashboard cards
if !is_local_mode {
// Dashboard cards occupy ~85 columns (1 border + 6 * 14 chars).
// LED grid fills the remaining width.
const CARD_COLUMNS: usize = 85;
let grid_gap = 2; // space between cards and grid
let grid_width = (cols as usize).saturating_sub(CARD_COLUMNS + grid_gap);
let grid_lines = led_grid::render_led_grid_lines(state, grid_width, card_lines.len());
for (i, card_line) in card_lines.iter().enumerate() {
stdout.write_all(card_line.as_bytes()).unwrap();
// Gap between cards and grid
print_colored_text(stdout, &" ".repeat(grid_gap), Color::White, None, None);
led_grid::write_led_row(stdout, &grid_lines, i, grid_width);
queue!(stdout, Print("\r\n")).unwrap();
}
} else {
// Local mode: just output the card lines as-is
for card_line in &card_lines {
stdout.write_all(card_line.as_bytes()).unwrap();
queue!(stdout, Print("\r\n")).unwrap();
}
}
}
pub fn draw_dashboard_items<W: Write>(stdout: &mut W, state: &AppState, cols: u16) {
// Print separator
let separator = "\u{2500}".repeat(cols as usize);
print_colored_text(stdout, &separator, Color::DarkGrey, None, None);
queue!(stdout, Print("\r\n")).unwrap();
// Remote mode: full-width braille sparkline panel replaces the old
// split node-list + bar-chart layout.
remote_sparkline_panel::draw_remote_sparkline_panel(stdout, state, cols);
}
fn print_dashboard_row<W: Write>(
stdout: &mut W,
items: &[(&str, String, Color)],
_total_width: usize,
) {
const ITEM_WIDTH: usize = 15; // Fixed width for each dashboard item
// Print labels row
print_colored_text(stdout, "│", Color::DarkGrey, None, None);
for (label, _, color) in items {
// Truncate label if too long, ensuring it fits in 15 characters minus padding and separator
let max_label_len = ITEM_WIDTH.saturating_sub(3);
let truncated_label = if label.len() > max_label_len {
&label[..max_label_len]
} else {
label
};
let formatted_label = format!(" {truncated_label:<max_label_len$}");
print_colored_text(stdout, &formatted_label, *color, None, None);
print_colored_text(stdout, "│", Color::DarkGrey, None, None);
}
queue!(stdout, Print("\r\n")).unwrap();
// Print values row
print_colored_text(stdout, "│", Color::DarkGrey, None, None);
for (_, value, _) in items {
// Truncate value if too long, ensuring it fits in 15 characters minus padding and separator
let max_value_len = ITEM_WIDTH.saturating_sub(3);
let truncated_value = if value.len() > max_value_len {
&value[..max_value_len]
} else {
value
};
let formatted_value = format!(" {truncated_value:<max_value_len$}");
print_colored_text(stdout, &formatted_value, Color::White, None, None);
print_colored_text(stdout, "│", Color::DarkGrey, None, None);
}
queue!(stdout, Print("\r\n")).unwrap();
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use crate::app_state::{AppState, ConnectionStatus};
use crate::device::GpuInfo;
use std::collections::HashMap;
fn make_local_state() -> AppState {
let mut state = AppState::new();
state.is_local_mode = true;
state
}
fn make_remote_state(node_count: usize) -> AppState {
let mut state = AppState::new();
state.is_local_mode = false;
state.tabs = vec!["All".to_string()];
for i in 0..node_count {
let host = format!("host-{i}");
state.tabs.push(host.clone());
let mut cs = ConnectionStatus::new(host.clone(), format!("http://{host}:9090"));
cs.mark_success();
state.connection_status.insert(host.clone(), cs);
state.gpu_info.push(GpuInfo {
uuid: format!("gpu-{i}"),
time: String::new(),
name: "Test GPU".to_string(),
device_type: "GPU".to_string(),
host_id: host.clone(),
hostname: host.clone(),
instance: host,
utilization: (i as f64 * 10.0) % 100.0,
ane_utilization: 0.0,
dla_utilization: None,
tensorcore_utilization: None,
temperature: 60,
used_memory: 2048,
total_memory: 8192,
frequency: 1500,
power_consumption: 200.0,
gpu_core_count: None,
temperature_threshold_slowdown: None,
temperature_threshold_shutdown: None,
temperature_threshold_max_operating: None,
temperature_threshold_acoustic: None,
performance_state: None,
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(),
});
}
state.current_tab = 0;
state
}
#[test]
fn test_draw_system_view_local_does_not_panic() {
let state = make_local_state();
let mut buf: Vec<u8> = Vec::new();
draw_system_view(&mut buf, &state, 160);
assert!(!buf.is_empty());
}
#[test]
fn test_draw_system_view_remote_does_not_panic() {
let state = make_remote_state(8);
let mut buf: Vec<u8> = Vec::new();
draw_system_view(&mut buf, &state, 160);
assert!(!buf.is_empty());
}
#[test]
fn test_draw_system_view_remote_narrow_terminal() {
// Narrow terminal: grid_width will be zero or negative — no panic.
let state = make_remote_state(4);
let mut buf: Vec<u8> = Vec::new();
draw_system_view(&mut buf, &state, 80);
assert!(!buf.is_empty());
}
#[test]
fn test_draw_dashboard_items_does_not_panic() {
let state = make_remote_state(2);
let mut buf: Vec<u8> = Vec::new();
draw_dashboard_items(&mut buf, &state, 160);
// Should at least write the separator
assert!(!buf.is_empty());
}
}