helix-toolbox 1.24.13

Build, configure and optimize a Linux machine from a terminal menu: installs, dotfiles, updates, backups and health checks, every change planned and confirmed first.
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
//! The Performance screen.

use super::super::*;

impl App {
    /// Read the boot and the machine in the background, recording this boot.
    pub(in crate::tui::app) fn read_performance(&mut self) {
        if !self.examine_here {
            self.build_performance_rows();
            return;
        }
        let (sender, receiver) = mpsc::channel();
        std::thread::spawn(move || {
            let state = history::state_dir();
            let history = history::read(1000).unwrap_or_default();
            let found = performance::gather(&doctor::Here, state.as_deref(), &history);
            let boots = state
                .map(|state| performance::load(&performance::boots_path(&state)))
                .unwrap_or_default();
            let _ = sender.send((found, boots));
        });
        self.reading_performance = Some(receiver);
    }

    /// The recorded boots before this one, newest first.
    pub(in crate::tui::app) fn earlier_boots(&self) -> Vec<&performance::Boot> {
        let Some((found, boots)) = &self.performance_found else {
            return Vec::new();
        };
        let Some(boot) = &found.boot else {
            return Vec::new();
        };
        boots
            .iter()
            .filter(|other| other.id != boot.id && other.booted <= boot.booted)
            .collect()
    }

    /// This boot beside the chosen earlier one.
    pub(in crate::tui::app) fn performance_comparison(&self) -> Option<performance::Comparison> {
        let (found, _) = self.performance_found.as_ref()?;
        if self.performance_against == 0 {
            return found.previous.clone();
        }
        let before = self
            .earlier_boots()
            .get(self.performance_against)
            .copied()?;
        let history = if self.examine_here {
            history::read(1000).unwrap_or_default()
        } else {
            Vec::new()
        };
        Some(performance::compare(before, found.boot.as_ref()?, &history))
    }

    pub(in crate::tui::app) fn build_performance_rows(&mut self) {
        let mut rows = Vec::new();
        let comparison = self.performance_comparison();
        if let Some((found, _)) = &self.performance_found {
            rows.push(PerformanceRow::Heading("This boot".into()));
            match &found.boot {
                Some(boot) => {
                    rows.push(PerformanceRow::Text(format!(
                        "{}, kernel {}: {}",
                        timestamp(boot.booted),
                        boot.kernel,
                        performance::shown(boot.phases.total)
                    )));
                    rows.push(PerformanceRow::Text(
                        boot.phases
                            .parts()
                            .iter()
                            .map(|(name, took)| format!("{name} {}", performance::shown(*took)))
                            .collect::<Vec<_>>()
                            .join(" · "),
                    ));
                }
                None => rows.push(PerformanceRow::Text(
                    found.no_boot.clone().unwrap_or_default(),
                )),
            }
            match &comparison {
                Some(compared) => {
                    rows.push(PerformanceRow::Heading(format!(
                        "Against the boot of {}: {}",
                        timestamp(compared.before.booted),
                        performance::shown_change(compared.total())
                    )));
                    for change in compared.phases.iter().skip(1).chain(&compared.units) {
                        let now = change
                            .after
                            .map(performance::shown)
                            .unwrap_or_else(|| "not now".into());
                        let (how, slower) = match change.difference() {
                            Some(difference) if difference.unsigned_abs() < 100 => continue,
                            Some(difference) => {
                                (performance::shown_change(difference), difference > 0)
                            }
                            None if change.before.is_none() => ("new".to_string(), true),
                            None => ("gone".to_string(), false),
                        };
                        rows.push(PerformanceRow::Change(
                            format!("{:<40} {now:>10}  ({how})", change.name),
                            slower,
                        ));
                    }
                    if compared.before.kernel != compared.after.kernel
                        && !compared.before.kernel.is_empty()
                    {
                        rows.push(PerformanceRow::Text(format!(
                            "The kernel changed: {} to {}",
                            compared.before.kernel, compared.after.kernel
                        )));
                    }
                    if compared.runs.is_empty() {
                        rows.push(PerformanceRow::Text(
                            "No Helix Toolbox runs in between.".into(),
                        ));
                    }
                    for run in &compared.runs {
                        rows.push(PerformanceRow::Text(format!(
                            "Ran in between, {}: {}{}",
                            timestamp(run.at),
                            run.names.join(", "),
                            if run.success { "" } else { " (failed)" }
                        )));
                    }
                }
                None if found.boot.is_some() => rows.push(PerformanceRow::Text(
                    "No earlier boot is recorded yet; after the next boot, this one is compared with it."
                        .into(),
                )),
                None => {}
            }
            if let Some(boot) = &found.boot {
                let waited: Vec<&performance::Link> = boot
                    .chain
                    .iter()
                    .filter(|link| link.took.is_some())
                    .collect();
                if !waited.is_empty() {
                    rows.push(PerformanceRow::Heading(
                        "The login screen waited for".into(),
                    ));
                    for link in waited {
                        rows.push(PerformanceRow::Unit(
                            link.name.clone(),
                            performance::shown(link.took.unwrap_or(0)),
                        ));
                    }
                }
                if !boot.slowest.is_empty() {
                    rows.push(PerformanceRow::Heading(
                        "Slowest services since the boot".into(),
                    ));
                    for timed in &boot.slowest {
                        rows.push(PerformanceRow::Unit(
                            timed.name.clone(),
                            performance::shown(timed.took),
                        ));
                    }
                }
            }
            let now = &found.now;
            rows.push(PerformanceRow::Heading("Now".into()));
            if let Some([one, five, fifteen]) = now.load {
                rows.push(PerformanceRow::Text(format!(
                    "Load {one:.2} {five:.2} {fifteen:.2} on {} processors",
                    now.cpus
                )));
            }
            if now.memory_total > 0 {
                rows.push(PerformanceRow::Text(format!(
                    "Memory: {} free of {}",
                    storage::shown(now.memory_available),
                    storage::shown(now.memory_total)
                )));
            }
            rows.push(PerformanceRow::Text(if now.swaps.is_empty() {
                "Swap: none".to_string()
            } else {
                format!(
                    "Swap: {} used of {}{}",
                    storage::shown(now.swap_used()),
                    storage::shown(now.swap_total()),
                    if now.swaps.iter().any(|swap| swap.zram) {
                        " (zram)"
                    } else {
                        ""
                    }
                )
            }));
            let pressure: Vec<String> = [
                ("processor", now.pressure.cpu),
                ("memory", now.pressure.memory),
                ("disk", now.pressure.io),
            ]
            .into_iter()
            .filter_map(|(what, waited)| Some(format!("{what} {:.0}%", waited?)))
            .collect();
            if !pressure.is_empty() {
                rows.push(PerformanceRow::Text(format!(
                    "Waiting in the last minute: {}",
                    pressure.join(", ")
                )));
            }
            if let Some(governor) = &now.governor {
                rows.push(PerformanceRow::Text(format!(
                    "Governor {governor}{}",
                    now.power_profile
                        .as_ref()
                        .map(|profile| format!(", power profile {profile}"))
                        .unwrap_or_default()
                )));
            }
            if !now.heaviest.is_empty() {
                rows.push(PerformanceRow::Text(format!(
                    "Most memory: {}",
                    now.heaviest
                        .iter()
                        .take(5)
                        .map(|process| format!(
                            "{} {}",
                            helix_toolbox_core::printable(&process.name),
                            storage::shown(process.memory)
                        ))
                        .collect::<Vec<_>>()
                        .join(", ")
                )));
            }
            if !found.hints.is_empty() {
                rows.push(PerformanceRow::Heading("Worth knowing".into()));
                rows.extend((0..found.hints.len()).map(PerformanceRow::Hint));
            }
        }
        self.performance_rows = rows;
        self.clamp_main();
    }

    pub(in crate::tui::app) fn selected_performance_row(&self) -> Option<PerformanceRow> {
        self.performance_rows
            .get(self.main_state.selected()?)
            .cloned()
    }

    pub(in crate::tui::app) fn selected_hint(&self) -> Option<performance::Hint> {
        let Some(PerformanceRow::Hint(index)) = self.selected_performance_row() else {
            return None;
        };
        let (found, _) = self.performance_found.as_ref()?;
        found.hints.get(index).cloned()
    }

    pub(in crate::tui::app) fn describe_performance(&mut self) {
        let (title, text) = match self.selected_performance_row() {
            Some(PerformanceRow::Hint(_)) => {
                let Some(hint) = self.selected_hint() else {
                    return;
                };
                let mut text = hint.detail.clone();
                if let Some(command) = &hint.command {
                    text.push_str(&format!("\n\n{command}\nEnter plans it here, then asks."));
                    if command.contains(" show ") {
                        text = text.replace(
                            "Enter plans it here, then asks.",
                            "Enter shows it in Services.",
                        );
                    }
                }
                if let Some(entry) = hint.entry.as_deref().and_then(|id| self.catalog.find(id)) {
                    text.push_str(&format!(
                        "\n\nThe {} entry sets it up; Enter runs it after confirmation.",
                        entry.name
                    ));
                }
                (hint.title, text)
            }
            Some(PerformanceRow::Unit(name, took)) => (
                name.clone(),
                format!(
                    "{name} took {took}.\n\nEnter shows it in Services, with what needs it and what stopping it costs."
                ),
            ),
            _ => return,
        };
        self.popup = Some(Popup::Text(TextPopup::new(title, text, true)));
    }

    /// Show a unit in the Services screen, filtered to it.
    pub(in crate::tui::app) fn show_unit(&mut self, name: &str) {
        self.service_filter = name.to_string();
        self.service_view = ServiceView::System;
        self.open_screen(Screen::Services);
    }

    /// Enter on a hint plans what changes it; on a unit, shows it in
    /// Services.
    pub(in crate::tui::app) fn act_on_performance(&mut self) {
        match self.selected_performance_row() {
            Some(PerformanceRow::Unit(name, _)) => self.show_unit(&name),
            Some(PerformanceRow::Hint(_)) => {
                let Some(hint) = self.selected_hint() else {
                    return;
                };
                match (&hint.unit, &hint.command, &hint.entry) {
                    (Some(unit), Some(command), _) if command.contains(" disable ") => {
                        let needed = if self.examine_here {
                            services::needed_by(&doctor::Here, unit, false)
                        } else {
                            Vec::new()
                        };
                        match services::plan(
                            unit,
                            false,
                            Verb::Disable,
                            &needed,
                            std::env::var_os("SSH_CONNECTION").is_some(),
                        ) {
                            Ok(planned) => self.confirm_plan(Ok(planned)),
                            Err(why) => {
                                self.popup =
                                    Some(Popup::Text(TextPopup::new("Cannot plan", why, true)));
                            }
                        }
                    }
                    (Some(unit), _, _) => {
                        let unit = unit.clone();
                        self.show_unit(&unit);
                    }
                    (None, _, Some(entry)) => match self.catalog.find(entry).cloned() {
                        Some(entry) => self.confirm(vec![entry]),
                        None => self.describe_performance(),
                    },
                    _ => self.describe_performance(),
                }
            }
            _ => {}
        }
    }

    pub(in crate::tui::app) fn draw_performance(&mut self, frame: &mut Frame, area: Rect) {
        let inner = self.page(
            frame,
            area,
            "Performance",
            "How long the boot took and where the time went, and the machine now. It only reads.",
        );
        self.fill(frame, inner);
        let focused = self.focus == Focus::Main;
        let mut items: Vec<Line> = Vec::new();
        if self.performance_rows.is_empty() {
            items.push(Line::styled(
                if self.reading_performance.is_some() {
                    "Reading the boot…"
                } else {
                    "Press r to read this boot and the machine now."
                },
                Style::default().fg(self.theme.muted()),
            ));
        }
        let hints = self
            .performance_found
            .as_ref()
            .map(|(found, _)| found.hints.clone())
            .unwrap_or_default();
        for row in &self.performance_rows {
            items.push(match row {
                PerformanceRow::Heading(text) => {
                    Line::styled(text.clone(), Style::default().fg(self.theme.group()).bold())
                }
                PerformanceRow::Text(text) => {
                    Line::styled(format!("  {text}"), Style::default().fg(self.theme.entry()))
                }
                PerformanceRow::Change(text, slower) => Line::styled(
                    format!("  {text}"),
                    Style::default().fg(if *slower {
                        self.theme.warning()
                    } else {
                        self.theme.success()
                    }),
                ),
                PerformanceRow::Unit(name, took) => Line::from(vec![
                    Span::styled(
                        format!("  {took:>10}  "),
                        Style::default().fg(self.theme.muted()),
                    ),
                    Span::styled(name.clone(), Style::default().fg(self.theme.entry())),
                ]),
                PerformanceRow::Hint(index) => {
                    let hint = &hints[*index];
                    let offer = match (&hint.command, &hint.entry) {
                        (Some(command), _) if command.contains(" disable ") => {
                            "  · Enter turns it off"
                        }
                        (Some(_), _) => "  · Enter shows it",
                        (None, Some(_)) => "  · Enter sets it up",
                        _ => "  · d details",
                    };
                    Line::from(vec![
                        Span::styled(
                            format!("  {}", hint.title),
                            Style::default().fg(self.theme.warning()),
                        ),
                        Span::styled(offer, Style::default().fg(self.theme.focused())),
                    ])
                }
            });
        }
        let title = if self.reading_performance.is_some() && !self.performance_rows.is_empty() {
            "Boot and machine (reading again…)"
        } else {
            "Boot and machine"
        };
        let list = List::new(self.measure(items))
            .block(self.card(title))
            .highlight_style(self.highlight(focused))
            .highlight_symbol(self.marker(focused))
            .scroll_padding(1);
        bordered_list(frame, list, inner, &mut self.main_state, &self.hits);
    }
}