lazyprune 0.4.0

A TUI tool to find and delete heavy cache/dependency directories
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
use std::collections::{HashMap, HashSet};
use std::sync::mpsc;

use nix::sys::signal::{self, Signal};
use nix::unistd::Pid;
use ratatui::widgets::ListState;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Protocol {
    Tcp,
    Udp,
}

// ── Sort mode ────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PortsSortMode {
    PortAsc,
    PortDesc,
    ProcessName,
    PidAsc,
}

impl PortsSortMode {
    pub fn next(self) -> Self {
        match self {
            PortsSortMode::PortAsc => PortsSortMode::PortDesc,
            PortsSortMode::PortDesc => PortsSortMode::ProcessName,
            PortsSortMode::ProcessName => PortsSortMode::PidAsc,
            PortsSortMode::PidAsc => PortsSortMode::PortAsc,
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            PortsSortMode::PortAsc => "Port \u{2191}",
            PortsSortMode::PortDesc => "Port \u{2193}",
            PortsSortMode::ProcessName => "Process",
            PortsSortMode::PidAsc => "PID",
        }
    }
}

// ── Kill messages ─────────────────────────────────────────────────────────────

#[allow(dead_code)]
pub enum KillMessage {
    Killing {
        port: u16,
        pid: u32,
        process: String,
    },
    Killed {
        port: u16,
        pid: u32,
    },
    Error {
        port: u16,
        pid: u32,
        error: String,
    },
    Complete,
}

// ── PortsState ────────────────────────────────────────────────────────────────

pub struct PortsState {
    pub items: Vec<PortInfo>,
    pub filtered_indices: Vec<usize>,
    pub selected: Vec<bool>,
    pub list_state: ListState,
    pub sort_mode: PortsSortMode,
    pub filter_text: String,
    pub protocol_filter: Option<Protocol>,
    pub protocol_filter_cursor: usize,
    pub dev_filter_active: bool,
    pub dev_filter_ports: HashSet<u16>,
    pub scan_complete: bool,
    pub scan_tick: u8,
    pub scan_rx: Option<mpsc::Receiver<PortScanMessage>>,
    pub kill_rx: Option<mpsc::Receiver<KillMessage>>,
    pub kill_progress: usize,
    pub kill_total: usize,
    pub kill_current: String,
    pub kill_errors: Vec<String>,
}

impl PortsState {
    pub fn new() -> Self {
        let mut list_state = ListState::default();
        list_state.select(Some(0));
        Self {
            items: Vec::new(),
            filtered_indices: Vec::new(),
            selected: Vec::new(),
            list_state,
            sort_mode: PortsSortMode::PortAsc,
            filter_text: String::new(),
            protocol_filter: None,
            protocol_filter_cursor: 0,
            dev_filter_active: false,
            dev_filter_ports: HashSet::new(),
            scan_complete: false,
            scan_tick: 0,
            scan_rx: None,
            kill_rx: None,
            kill_progress: 0,
            kill_total: 0,
            kill_current: String::new(),
            kill_errors: Vec::new(),
        }
    }

    /// Start a port scan in a background thread.
    pub fn start_scan(&mut self, dev_filter: Option<HashSet<u16>>) {
        self.items.clear();
        self.filtered_indices.clear();
        self.selected.clear();
        self.scan_complete = false;

        let (tx, rx) = mpsc::channel();
        self.scan_rx = Some(rx);
        std::thread::spawn(move || scan_ports(tx, dev_filter));
    }

    /// Drain the scan channel non-blocking.
    pub fn poll_scan_results(&mut self) {
        let rx = match self.scan_rx.as_ref() {
            Some(rx) => rx,
            None => return,
        };

        loop {
            match rx.try_recv() {
                Ok(msg) => match msg {
                    PortScanMessage::Found(info) => {
                        self.items.push(info);
                        self.selected.push(false);
                    }
                    PortScanMessage::Complete => {
                        self.scan_complete = true;
                        self.scan_rx = None;
                        self.apply_filter();
                        return;
                    }
                    PortScanMessage::Error(_) => {}
                },
                Err(mpsc::TryRecvError::Empty) => break,
                Err(mpsc::TryRecvError::Disconnected) => {
                    self.scan_complete = true;
                    self.scan_rx = None;
                    self.apply_filter();
                    return;
                }
            }
        }
    }

    /// Return the item currently under the cursor.
    pub fn current_item(&self) -> Option<&PortInfo> {
        let idx = self.list_state.selected()?;
        let &item_idx = self.filtered_indices.get(idx)?;
        self.items.get(item_idx)
    }

    /// Check if a single item passes the current text and protocol filters.
    pub fn item_passes_filter(&self, info: &PortInfo) -> bool {
        if !self.filter_text.is_empty() {
            let lower = self.filter_text.to_lowercase();
            let port_str = info.port.to_string();
            let pid_str = info.pid.to_string();
            let name_lower = info.process_name.to_lowercase();
            if !port_str.contains(&lower)
                && !name_lower.contains(&lower)
                && !pid_str.contains(&lower)
            {
                return false;
            }
        }
        if let Some(proto) = self.protocol_filter {
            if info.protocol != proto {
                return false;
            }
        }
        true
    }

    /// Rebuild filtered_indices: filter then sort.
    pub fn apply_filter(&mut self) {
        let mut indices: Vec<usize> = self
            .items
            .iter()
            .enumerate()
            .filter(|(_, info)| self.item_passes_filter(info))
            .map(|(i, _)| i)
            .collect();

        match self.sort_mode {
            PortsSortMode::PortAsc => {
                indices.sort_unstable_by_key(|&i| self.items[i].port);
            }
            PortsSortMode::PortDesc => {
                indices.sort_unstable_by(|&a, &b| self.items[b].port.cmp(&self.items[a].port));
            }
            PortsSortMode::ProcessName => {
                indices.sort_unstable_by(|&a, &b| {
                    self.items[a].process_name.cmp(&self.items[b].process_name)
                });
            }
            PortsSortMode::PidAsc => {
                indices.sort_unstable_by_key(|&i| self.items[i].pid);
            }
        }

        self.filtered_indices = indices;

        // Clamp cursor
        if self.filtered_indices.is_empty() {
            self.list_state.select(Some(0));
        } else {
            let current = self.list_state.selected().unwrap_or(0);
            if current >= self.filtered_indices.len() {
                self.list_state
                    .select(Some(self.filtered_indices.len() - 1));
            }
        }
    }

    /// Toggle selection of the item at the given visible position.
    pub fn toggle_selection(&mut self, pos: usize) {
        if let Some(&item_idx) = self.filtered_indices.get(pos) {
            if item_idx < self.selected.len() {
                self.selected[item_idx] = !self.selected[item_idx];
            }
        }
    }

    /// Select all visible (filtered) items.
    pub fn select_all(&mut self) {
        for &idx in &self.filtered_indices {
            if idx < self.selected.len() {
                self.selected[idx] = true;
            }
        }
    }

    /// Invert selection of all visible (filtered) items.
    pub fn invert_selection(&mut self) {
        for &idx in &self.filtered_indices {
            if idx < self.selected.len() {
                self.selected[idx] = !self.selected[idx];
            }
        }
    }

    /// Count of selected items.
    pub fn selected_count(&self) -> usize {
        self.selected.iter().filter(|&&s| s).count()
    }

    /// Move cursor down.
    pub fn next(&mut self) {
        if self.filtered_indices.is_empty() {
            return;
        }
        let current = self.list_state.selected().unwrap_or(0);
        let next = (current + 1).min(self.filtered_indices.len() - 1);
        self.list_state.select(Some(next));
    }

    /// Move cursor up.
    pub fn previous(&mut self) {
        if self.filtered_indices.is_empty() {
            return;
        }
        let current = self.list_state.selected().unwrap_or(0);
        let prev = current.saturating_sub(1);
        self.list_state.select(Some(prev));
    }

    /// Jump to the top of the list.
    pub fn go_top(&mut self) {
        if !self.filtered_indices.is_empty() {
            self.list_state.select(Some(0));
        }
    }

    /// Jump to the bottom of the list.
    pub fn go_bottom(&mut self) {
        if !self.filtered_indices.is_empty() {
            let last = self.filtered_indices.len() - 1;
            self.list_state.select(Some(last));
        }
    }

    /// Cycle sort mode and re-apply filter.
    pub fn cycle_sort(&mut self) {
        self.sort_mode = self.sort_mode.next();
        self.apply_filter();
    }

    /// Return references to all selected items.
    pub fn selected_items(&self) -> Vec<&PortInfo> {
        self.items
            .iter()
            .enumerate()
            .filter(|(i, _)| self.selected.get(*i).copied().unwrap_or(false))
            .map(|(_, item)| item)
            .collect()
    }

    // ── Kill support ──────────────────────────────────────────────────────────

    /// Spawn a kill thread for all selected items.
    pub fn start_killing(&mut self) {
        let targets: Vec<PortInfo> = self
            .selected
            .iter()
            .enumerate()
            .filter(|(_, &sel)| sel)
            .map(|(i, _)| self.items[i].clone())
            .collect();

        if targets.is_empty() {
            return;
        }

        self.kill_total = targets.len();
        self.kill_progress = 0;
        self.kill_errors.clear();

        let (tx, rx) = mpsc::channel();
        self.kill_rx = Some(rx);
        std::thread::spawn(move || kill_ports(targets, tx));
    }

    /// Drain the kill channel. Returns `true` when kill is complete.
    pub fn poll_kill_results(&mut self) -> bool {
        let rx = match self.kill_rx.as_ref() {
            Some(rx) => rx,
            None => return false,
        };

        loop {
            match rx.try_recv() {
                Ok(msg) => match msg {
                    KillMessage::Killing { process, .. } => {
                        self.kill_current = process;
                    }
                    KillMessage::Killed { .. } => {
                        self.kill_progress += 1;
                    }
                    KillMessage::Error { error, .. } => {
                        self.kill_progress += 1;
                        self.kill_errors.push(error);
                    }
                    KillMessage::Complete => {
                        self.kill_rx = None;
                        // Trigger a rescan to reflect the killed processes
                        let filter = if self.dev_filter_active {
                            Some(self.dev_filter_ports.clone())
                        } else {
                            None
                        };
                        self.start_scan(filter);
                        return true;
                    }
                },
                Err(mpsc::TryRecvError::Empty) => break,
                Err(mpsc::TryRecvError::Disconnected) => {
                    self.kill_rx = None;
                    return true;
                }
            }
        }

        false
    }
}

// ── Kill logic ────────────────────────────────────────────────────────────────

/// Verify that `pid` still refers to `expected_name` by consulting `ps`.
fn verify_process(pid: u32, expected_name: &str) -> bool {
    let output = match std::process::Command::new("ps")
        .args(["-p", &pid.to_string(), "-o", "comm="])
        .output()
    {
        Ok(o) => o,
        Err(_) => return false,
    };
    let stdout = String::from_utf8_lossy(&output.stdout);
    let actual = stdout.trim();
    // ps may truncate the command name, so check if either string contains the other
    !actual.is_empty() && (actual.contains(expected_name) || expected_name.contains(actual))
}

/// Kill each target process with SIGTERM, wait 500 ms, then SIGKILL if still alive.
pub fn kill_ports(targets: Vec<PortInfo>, tx: mpsc::Sender<KillMessage>) {
    for target in &targets {
        let _ = tx.send(KillMessage::Killing {
            port: target.port,
            pid: target.pid,
            process: target.process_name.clone(),
        });

        let nix_pid = Pid::from_raw(target.pid as i32);

        // Send SIGTERM
        if let Err(e) = signal::kill(nix_pid, Signal::SIGTERM) {
            let _ = tx.send(KillMessage::Error {
                port: target.port,
                pid: target.pid,
                error: format!("SIGTERM failed: {e}"),
            });
            continue;
        }

        // Wait 500 ms for graceful shutdown
        std::thread::sleep(std::time::Duration::from_millis(500));

        // Check if still alive
        let still_alive = signal::kill(nix_pid, None).is_ok();
        if still_alive {
            if verify_process(target.pid, &target.process_name) {
                // Process is still alive and is indeed the expected process — use SIGKILL
                if let Err(e) = signal::kill(nix_pid, Signal::SIGKILL) {
                    let _ = tx.send(KillMessage::Error {
                        port: target.port,
                        pid: target.pid,
                        error: format!("SIGKILL failed: {e}"),
                    });
                    continue;
                }
            } else {
                // PID is alive but belongs to a different process — cannot safely kill
                let _ = tx.send(KillMessage::Error {
                    port: target.port,
                    pid: target.pid,
                    error: "Process survived SIGTERM but PID was reused".to_string(),
                });
                continue;
            }
        }

        let _ = tx.send(KillMessage::Killed {
            port: target.port,
            pid: target.pid,
        });
    }

    let _ = tx.send(KillMessage::Complete);
}

/// Internal struct used during lsof parsing, before deduplication.
#[derive(Debug, Clone)]
pub struct PortEntry {
    pub port: u16,
    pub protocol: Protocol,
    pub pid: u32,
    pub process_name: String,
    pub user: String,
    pub state: String,
}

/// Public struct representing a unique port with aggregated connection info.
#[derive(Debug, Clone)]
pub struct PortInfo {
    pub port: u16,
    pub protocol: Protocol,
    pub pid: u32,
    pub process_name: String,
    pub command: String,
    pub user: String,
    pub state: String,
    pub connections: usize,
}

pub enum PortScanMessage {
    Found(PortInfo),
    Complete,
    Error(String),
}

/// Parses the NAME column from an lsof line and returns `(port, state)`.
///
/// Handles formats:
/// - `*:3000 (LISTEN)`
/// - `*:5353`
/// - `127.0.0.1:8080->127.0.0.1:52341 (ESTABLISHED)`
/// - `[::1]:3000 (LISTEN)`
pub fn parse_port_from_name(name: &str) -> Option<(u16, String)> {
    // Extract optional trailing state like "(LISTEN)" or "(ESTABLISHED)"
    let (addr_part, state) = if let Some(idx) = name.rfind('(') {
        let state_raw = name[idx..]
            .trim_matches(|c| c == '(' || c == ')')
            .trim()
            .to_string();
        (name[..idx].trim(), state_raw)
    } else {
        (name.trim(), String::new())
    };

    // For connection lines like "src->dst", take the source part only
    let local_part = if let Some(arrow_idx) = addr_part.find("->") {
        &addr_part[..arrow_idx]
    } else {
        addr_part
    };

    // Find the last ':' to split host and port
    let colon_idx = local_part.rfind(':')?;
    let port_str = &local_part[colon_idx + 1..];
    let port: u16 = port_str.trim().parse().ok()?;

    Some((port, state))
}

/// Parses one line of `lsof -i -n -P +c 0` output into a `PortEntry`.
///
/// Expected columns (whitespace-separated):
/// COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
///
/// NODE is "TCP" or "UDP". Header lines and non-TCP/UDP lines are skipped.
pub fn parse_lsof_line(line: &str) -> Option<PortEntry> {
    let mut fields = line.split_whitespace();

    let process_name = fields.next()?.to_string();

    // Skip header line
    if process_name == "COMMAND" {
        return None;
    }

    let pid_str = fields.next()?;
    let pid: u32 = pid_str.parse().ok()?;

    let user = fields.next()?.to_string();
    let _fd = fields.next()?;
    let _type_field = fields.next()?;
    let _device = fields.next()?;
    let _size_off = fields.next()?;
    let node = fields.next()?;

    let protocol = match node.to_uppercase().as_str() {
        "TCP" => Protocol::Tcp,
        "UDP" => Protocol::Udp,
        _ => return None,
    };

    // Remaining tokens form the NAME column
    let name: String = fields.collect::<Vec<_>>().join(" ");
    if name.is_empty() {
        return None;
    }

    let (port, state) = parse_port_from_name(&name)?;

    Some(PortEntry {
        port,
        protocol,
        pid,
        process_name,
        user,
        state,
    })
}

/// Deduplicates `PortEntry` list by `(port, protocol)`.
///
/// Keeps the entry with the LISTEN state when available. Tracks total
/// connection count across all entries for the same (port, protocol) key.
pub fn dedup_port_entries(entries: Vec<PortEntry>) -> Vec<PortInfo> {
    let mut map: HashMap<(u16, Protocol), PortInfo> = HashMap::new();

    for entry in entries {
        let key = (entry.port, entry.protocol);
        match map.entry(key) {
            std::collections::hash_map::Entry::Vacant(v) => {
                v.insert(PortInfo {
                    port: entry.port,
                    protocol: entry.protocol,
                    pid: entry.pid,
                    process_name: entry.process_name,
                    command: String::new(),
                    user: entry.user,
                    state: entry.state,
                    connections: 1,
                });
            }
            std::collections::hash_map::Entry::Occupied(mut o) => {
                let existing = o.get_mut();
                existing.connections += 1;
                // Prefer the LISTEN state entry as the canonical one
                if entry.state == "LISTEN" && existing.state != "LISTEN" {
                    existing.pid = entry.pid;
                    existing.process_name = entry.process_name;
                    existing.user = entry.user;
                    existing.state = entry.state;
                }
            }
        }
    }

    map.into_values().collect()
}

/// Batch-fetches full command strings for the given PIDs via `ps`.
///
/// Runs `ps -p <pid,...> -o pid=,command=` and parses each output line.
pub fn fetch_commands(pids: &[u32]) -> HashMap<u32, String> {
    if pids.is_empty() {
        return HashMap::new();
    }

    let pid_list: Vec<String> = pids.iter().map(|p| p.to_string()).collect();
    let pid_arg = pid_list.join(",");

    let output = match std::process::Command::new("ps")
        .args(["-p", &pid_arg, "-o", "pid=,command="])
        .output()
    {
        Ok(o) => o,
        Err(_) => return HashMap::new(),
    };

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut result = HashMap::new();

    for line in stdout.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        // First token is PID, rest is the command
        if let Some(space_idx) = trimmed.find(char::is_whitespace) {
            let pid_str = &trimmed[..space_idx];
            let command = trimmed[space_idx..].trim().to_string();
            if let Ok(pid) = pid_str.parse::<u32>() {
                result.insert(pid, command);
            }
        }
    }

    result
}

/// Scans open ports by running `lsof -i -n -P +c 0`, parses, deduplicates,
/// optionally filters to a set of ports, fetches full commands, then sends
/// each `PortInfo` over the channel followed by `PortScanMessage::Complete`.
pub fn scan_ports(tx: mpsc::Sender<PortScanMessage>, dev_filter: Option<HashSet<u16>>) {
    let output = match std::process::Command::new("lsof")
        .args(["-i", "-n", "-P", "+c", "0"])
        .output()
    {
        Ok(o) => o,
        Err(e) => {
            let _ = tx.send(PortScanMessage::Error(format!("lsof failed: {e}")));
            return;
        }
    };

    let stdout = String::from_utf8_lossy(&output.stdout);

    let entries: Vec<PortEntry> = stdout.lines().filter_map(parse_lsof_line).collect();

    let mut port_infos = dedup_port_entries(entries);

    // Apply optional dev filter
    if let Some(ref filter) = dev_filter {
        port_infos.retain(|p| filter.contains(&p.port));
    }

    // Fetch full command strings for all unique PIDs
    let pids: Vec<u32> = port_infos.iter().map(|p| p.pid).collect();
    let commands = fetch_commands(&pids);

    for mut info in port_infos {
        if let Some(cmd) = commands.get(&info.pid) {
            info.command = cmd.clone();
        }
        let _ = tx.send(PortScanMessage::Found(info));
    }

    let _ = tx.send(PortScanMessage::Complete);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_lsof_listen_line() {
        let line = "node      12345 thibault   23u  IPv6 0xabc      0t0  TCP *:3000 (LISTEN)";
        let result = parse_lsof_line(line);
        assert!(result.is_some());
        let info = result.unwrap();
        assert_eq!(info.port, 3000);
        assert_eq!(info.pid, 12345);
        assert_eq!(info.process_name, "node");
        assert_eq!(info.user, "thibault");
        assert_eq!(info.protocol, Protocol::Tcp);
        assert_eq!(info.state, "LISTEN");
    }

    #[test]
    fn test_parse_lsof_udp_no_state() {
        let line = "mDNSRespo   123 _mdnsresponder   12u  IPv4 0xdef      0t0  UDP *:5353";
        let result = parse_lsof_line(line);
        assert!(result.is_some());
        let info = result.unwrap();
        assert_eq!(info.port, 5353);
        assert_eq!(info.protocol, Protocol::Udp);
        assert_eq!(info.state, "");
    }

    #[test]
    fn test_parse_lsof_skip_header() {
        let line = "COMMAND     PID   USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME";
        assert!(parse_lsof_line(line).is_none());
    }

    #[test]
    fn test_parse_lsof_established() {
        let line = "node      12345 thibault   24u  IPv6 0xabc      0t0  TCP 127.0.0.1:3000->127.0.0.1:52341 (ESTABLISHED)";
        let result = parse_lsof_line(line);
        assert!(result.is_some());
        let info = result.unwrap();
        assert_eq!(info.port, 3000);
        assert_eq!(info.state, "ESTABLISHED");
    }

    #[test]
    fn test_dedup_ports() {
        let entries = vec![
            PortEntry {
                port: 3000,
                protocol: Protocol::Tcp,
                pid: 123,
                process_name: "node".into(),
                user: "me".into(),
                state: "LISTEN".into(),
            },
            PortEntry {
                port: 3000,
                protocol: Protocol::Tcp,
                pid: 123,
                process_name: "node".into(),
                user: "me".into(),
                state: "ESTABLISHED".into(),
            },
            PortEntry {
                port: 3000,
                protocol: Protocol::Tcp,
                pid: 124,
                process_name: "node".into(),
                user: "me".into(),
                state: "ESTABLISHED".into(),
            },
        ];
        let deduped = dedup_port_entries(entries);
        assert_eq!(deduped.len(), 1);
        assert_eq!(deduped[0].state, "LISTEN");
        assert_eq!(deduped[0].connections, 3);
    }

    #[test]
    fn test_parse_port_from_name_column() {
        assert_eq!(
            parse_port_from_name("*:3000 (LISTEN)"),
            Some((3000, "LISTEN".to_string()))
        );
        assert_eq!(parse_port_from_name("*:5353"), Some((5353, "".to_string())));
        assert_eq!(
            parse_port_from_name("127.0.0.1:8080->127.0.0.1:52341 (ESTABLISHED)"),
            Some((8080, "ESTABLISHED".to_string()))
        );
        assert_eq!(
            parse_port_from_name("[::1]:3000 (LISTEN)"),
            Some((3000, "LISTEN".to_string()))
        );
    }

    #[test]
    fn test_dev_filter() {
        let filter: HashSet<u16> = (3000..=3009).collect();
        let entries = vec![
            PortInfo {
                port: 3000,
                protocol: Protocol::Tcp,
                pid: 1,
                process_name: "node".into(),
                command: "".into(),
                user: "me".into(),
                state: "LISTEN".into(),
                connections: 1,
            },
            PortInfo {
                port: 22,
                protocol: Protocol::Tcp,
                pid: 2,
                process_name: "sshd".into(),
                command: "".into(),
                user: "root".into(),
                state: "LISTEN".into(),
                connections: 1,
            },
        ];
        let filtered: Vec<_> = entries
            .into_iter()
            .filter(|p| filter.contains(&p.port))
            .collect();
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].port, 3000);
    }

    // ── PortsState tests ──────────────────────────────────────────────────────

    fn make_port_info(port: u16, process: &str) -> PortInfo {
        PortInfo {
            port,
            protocol: Protocol::Tcp,
            pid: port as u32,
            process_name: process.into(),
            command: String::new(),
            user: "test".into(),
            state: "LISTEN".into(),
            connections: 1,
        }
    }

    fn make_port_info_udp(port: u16, process: &str) -> PortInfo {
        PortInfo {
            port,
            protocol: Protocol::Udp,
            pid: port as u32,
            process_name: process.into(),
            command: String::new(),
            user: "test".into(),
            state: String::new(),
            connections: 1,
        }
    }

    #[test]
    fn test_ports_state_filter_text() {
        let mut state = PortsState::new();
        state.items = vec![make_port_info(3000, "node"), make_port_info(8080, "java")];
        state.selected = vec![false; 2];
        state.filter_text = "node".into();
        state.apply_filter();
        assert_eq!(state.filtered_indices.len(), 1);
        assert_eq!(state.items[state.filtered_indices[0]].port, 3000);
    }

    #[test]
    fn test_ports_state_sort_by_port() {
        let mut state = PortsState::new();
        state.items = vec![make_port_info(8080, "java"), make_port_info(3000, "node")];
        state.selected = vec![false; 2];
        state.sort_mode = PortsSortMode::PortAsc;
        state.apply_filter();
        assert_eq!(state.items[state.filtered_indices[0]].port, 3000);
        assert_eq!(state.items[state.filtered_indices[1]].port, 8080);
    }

    #[test]
    fn test_ports_state_protocol_filter() {
        let mut state = PortsState::new();
        state.items = vec![
            make_port_info(3000, "node"),
            make_port_info_udp(5353, "mDNSResponder"),
        ];
        state.selected = vec![false; 2];
        state.protocol_filter = Some(Protocol::Tcp);
        state.apply_filter();
        assert_eq!(state.filtered_indices.len(), 1);
    }

    #[test]
    fn test_ports_state_selection() {
        let mut state = PortsState::new();
        state.items = vec![make_port_info(3000, "node"), make_port_info(3001, "node")];
        state.selected = vec![false; 2];
        state.apply_filter();
        state.toggle_selection(0);
        assert!(state.selected[state.filtered_indices[0]]);
        assert_eq!(state.selected_count(), 1);
    }

    // ── Kill tests ────────────────────────────────────────────────────────────

    #[test]
    fn test_ports_state_has_own_scan_tick() {
        let mut state = PortsState::new();
        assert_eq!(state.scan_tick, 0);
        state.scan_tick = state.scan_tick.wrapping_add(1);
        assert_eq!(state.scan_tick, 1);
        // Verify wrapping at u8 boundary
        state.scan_tick = 255;
        state.scan_tick = state.scan_tick.wrapping_add(1);
        assert_eq!(state.scan_tick, 0);
    }

    #[test]
    fn test_ports_state_select_all() {
        let mut state = PortsState::new();
        state.items = vec![
            make_port_info(3000, "node"),
            make_port_info(3001, "node"),
            make_port_info(8080, "java"),
        ];
        state.selected = vec![false; 3];
        state.apply_filter();
        state.select_all();
        assert_eq!(state.selected_count(), 3);
    }

    #[test]
    fn test_ports_state_invert_selection() {
        let mut state = PortsState::new();
        state.items = vec![make_port_info(3000, "node"), make_port_info(3001, "node")];
        state.selected = vec![true, false];
        state.apply_filter();
        state.invert_selection();
        assert!(!state.selected[0]);
        assert!(state.selected[1]);
    }

    #[test]
    fn test_ports_state_navigation() {
        let mut state = PortsState::new();
        state.items = vec![
            make_port_info(3000, "node"),
            make_port_info(3001, "node"),
            make_port_info(3002, "node"),
        ];
        state.selected = vec![false; 3];
        state.apply_filter();

        assert_eq!(state.list_state.selected(), Some(0));
        state.next();
        assert_eq!(state.list_state.selected(), Some(1));
        state.next();
        assert_eq!(state.list_state.selected(), Some(2));
        // Should clamp at the end
        state.next();
        assert_eq!(state.list_state.selected(), Some(2));

        state.previous();
        assert_eq!(state.list_state.selected(), Some(1));
        state.go_top();
        assert_eq!(state.list_state.selected(), Some(0));
        state.go_bottom();
        assert_eq!(state.list_state.selected(), Some(2));
    }

    #[test]
    fn test_ports_state_cycle_sort() {
        let mut state = PortsState::new();
        assert_eq!(state.sort_mode, PortsSortMode::PortAsc);
        state.items = vec![make_port_info(3000, "node")];
        state.selected = vec![false];
        state.cycle_sort();
        assert_eq!(state.sort_mode, PortsSortMode::PortDesc);
        state.cycle_sort();
        assert_eq!(state.sort_mode, PortsSortMode::ProcessName);
        state.cycle_sort();
        assert_eq!(state.sort_mode, PortsSortMode::PidAsc);
        state.cycle_sort();
        assert_eq!(state.sort_mode, PortsSortMode::PortAsc);
    }

    #[test]
    fn test_kill_message_types() {
        let msg = KillMessage::Killing {
            port: 3000,
            pid: 123,
            process: "node".into(),
        };
        match msg {
            KillMessage::Killing { port, pid, .. } => {
                assert_eq!(port, 3000);
                assert_eq!(pid, 123);
            }
            _ => panic!("wrong variant"),
        }
    }
}