kdash 2.0.0

A fast and simple dashboard for Kubernetes
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
use std::{collections::HashSet, process::Stdio, sync::Arc, time::Duration};

use anyhow::anyhow;
use futures::AsyncBufReadExt;
use k8s_openapi::api::core::v1::Pod;
use kube::{
  api::{ListParams, LogParams},
  Api, Client,
};
use log::{debug, error, info, warn};
use tokio::{
  io::{AsyncBufReadExt as TokioAsyncBufReadExt, AsyncReadExt, BufReader},
  process::{ChildStderr, ChildStdout, Command},
  sync::Mutex,
  time::Instant,
};
use tokio_stream::StreamExt;

use super::refresh_kube_config;
use crate::app::port_forward::PortForwardStatus;
use crate::app::App;
use crate::cmd::port_forward::{prepare_port_forward, PortForwardTarget};
const BATCH_SIZE: usize = 50;
const BATCH_FLUSH_MS: u64 = 100;
const RECONNECT_OVERLAP_SECS: i64 = 5;
const MAX_RECONNECT_ATTEMPTS: u32 = 10;
const DEDUP_WINDOW: usize = 50;
const MAX_AGGREGATE_PODS: usize = 20;

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum IoStreamEvent {
  RefreshClient,
  GetPodLogs(bool),
  GetPreviousLogs,
  GetAggregateLogs {
    namespace: String,
    selector: String,
  },
  GetPodAllContainerLogs,
  StartPortForward {
    kind: String,
    namespace: String,
    name: String,
    local_port: u16,
    remote_port: u16,
  },
  StopPortForward {
    id: u64,
  },
}

#[derive(Clone)]
pub struct NetworkStream<'a> {
  pub client: Client,
  pub app: &'a Arc<Mutex<App>>,
}

impl<'a> NetworkStream<'a> {
  pub fn new(client: Client, app: &'a Arc<Mutex<App>>) -> Self {
    NetworkStream { client, app }
  }

  pub async fn refresh_client(&mut self) {
    let context = {
      let app = self.app.lock().await;
      app.data.selected.context.clone()
    };
    match refresh_kube_config(&context).await {
      Ok(client) => {
        self.client = client;
      }
      Err(e) => {
        self
          .handle_error(anyhow!("Failed to refresh client. {:}", e))
          .await
      }
    }
  }

  pub async fn handle_network_stream_event(&mut self, io_event: IoStreamEvent) {
    match io_event {
      IoStreamEvent::RefreshClient => {
        self.refresh_client().await;
      }
      IoStreamEvent::GetPodLogs(tail) => {
        self.stream_container_logs(tail).await;
      }
      IoStreamEvent::GetPreviousLogs => {
        self.fetch_previous_logs().await;
      }
      IoStreamEvent::GetAggregateLogs {
        namespace,
        selector,
      } => {
        self.stream_aggregate_logs(&namespace, &selector).await;
      }
      IoStreamEvent::GetPodAllContainerLogs => {
        self.stream_pod_all_container_logs().await;
      }
      IoStreamEvent::StartPortForward {
        kind,
        namespace,
        name,
        local_port,
        remote_port,
      } => {
        self
          .start_port_forward(kind, namespace, name, local_port, remote_port)
          .await;
      }
      IoStreamEvent::StopPortForward { id } => {
        self.stop_port_forward(id).await;
      }
    };

    let mut app = self.app.lock().await;
    app.loading_complete();
  }

  async fn handle_error(&self, e: anyhow::Error) {
    error!("{:?}", e);
    let mut app = self.app.lock().await;
    app.handle_error(e);
  }

  pub async fn stream_container_logs(&self, tail: bool) {
    let (namespace, pod_name, cont_name, tail_lines, timestamps, cancel_rx) = {
      let app = self.app.lock().await;
      let ns = app
        .data
        .pods
        .get_selected_item_copy()
        .map(|p| p.namespace)
        .unwrap_or_else(|| std::env::var("NAMESPACE").unwrap_or_else(|_| "default".into()));
      let pod = app
        .data
        .pods
        .get_selected_item_copy()
        .map(|p| p.name)
        .unwrap_or_default();
      let cont = app.data.selected.container.clone().unwrap_or_default();
      let tail_lines = app.initial_log_tail_lines();
      let timestamps = app.log_timestamps;
      let rx = app.new_log_cancel_rx();
      (ns, pod, cont, tail_lines, timestamps, rx)
    };

    if pod_name.is_empty() || cont_name.is_empty() {
      return;
    }

    {
      let mut app = self.app.lock().await;
      app.is_streaming = true;
    }

    let api: Api<Pod> = Api::namespaced(self.client.clone(), &namespace);
    let mut since_seconds: Option<i64> = None;
    let mut reconnect_count: u32 = 0;

    loop {
      let lp = LogParams {
        container: Some(cont_name.clone()),
        follow: true,
        previous: false,
        tail_lines: if since_seconds.is_none() && tail {
          Some(tail_lines)
        } else {
          None
        },
        since_seconds,
        timestamps,
        ..Default::default()
      };

      match api.log_stream(&pod_name, &lp).await {
        Ok(logs) => {
          reconnect_count = 0;
          let mut lines_stream = logs.lines();
          let mut batch: Vec<String> = Vec::with_capacity(BATCH_SIZE);
          let mut last_flush = Instant::now();
          let mut cancel_rx = cancel_rx.clone();

          // Build dedup set from existing records
          let dedup_set: HashSet<String> = if since_seconds.is_some() {
            let app = self.app.lock().await;
            app
              .data
              .logs
              .last_n_records(DEDUP_WINDOW)
              .into_iter()
              .map(|s| s.to_string())
              .collect()
          } else {
            HashSet::new()
          };

          loop {
            let flush_deadline =
              tokio::time::sleep_until(last_flush + Duration::from_millis(BATCH_FLUSH_MS));

            tokio::select! {
              // Cancellation signal
              _ = cancel_rx.changed() => {
                if *cancel_rx.borrow() {
                  // Flush remaining batch before exiting
                  if !batch.is_empty() {
                    let mut app = self.app.lock().await;
                    app.data.logs.add_records(batch);
                  }
                  debug!("Log stream cancelled for {}/{}", pod_name, cont_name);
                  let mut app = self.app.lock().await;
                  app.is_streaming = false;
                  return;
                }
              }
              // Next log line
              line = lines_stream.next() => {
                match line {
                  Some(Ok(line)) => {
                    let line = line.trim().to_string();
                    if !line.is_empty() {
                      // Skip duplicates on reconnect
                      if since_seconds.is_some() && dedup_set.contains(&line) {
                        continue;
                      }
                      batch.push(line);

                      if batch.len() >= BATCH_SIZE {
                        let mut app = self.app.lock().await;
                        app.data.logs.add_records(std::mem::replace(
                          &mut batch,
                          Vec::with_capacity(BATCH_SIZE),
                        ));
                        last_flush = Instant::now();
                      }
                    }
                  }
                  Some(Err(e)) => {
                    warn!("Log stream read error for {}/{}: {}", pod_name, cont_name, e);
                    break; // Break inner loop to reconnect
                  }
                  None => {
                    debug!("Log stream ended for {}/{}", pod_name, cont_name);
                    break; // Break inner loop to reconnect
                  }
                }
              }
              // Flush timer
              _ = flush_deadline => {
                if !batch.is_empty() {
                  let mut app = self.app.lock().await;
                  app.data.logs.add_records(std::mem::replace(
                    &mut batch,
                    Vec::with_capacity(BATCH_SIZE),
                  ));
                  last_flush = Instant::now();
                }
              }
            }
          }

          // Flush any remaining lines after inner loop break
          if !batch.is_empty() {
            let mut app = self.app.lock().await;
            app.data.logs.add_records(batch);
          }
        }
        Err(e) => {
          warn!(
            "Failed to open log stream for {}/{}: {}",
            pod_name, cont_name, e
          );
          reconnect_count += 1;
          if reconnect_count >= MAX_RECONNECT_ATTEMPTS {
            self
              .handle_error(anyhow!(
                "Failed to stream logs after {} attempts: {}",
                MAX_RECONNECT_ATTEMPTS,
                e
              ))
              .await;
            break;
          }
        }
      }

      // Check cancellation before reconnecting
      if *cancel_rx.borrow() {
        break;
      }

      // Ask Kubernetes for a small overlap window so reconnects only refetch recent logs.
      since_seconds = Some(RECONNECT_OVERLAP_SECS);

      // Backoff before reconnecting
      let backoff = Duration::from_millis(500 * (reconnect_count as u64).min(4));
      debug!(
        "Reconnecting log stream for {}/{} (attempt {}, backoff {:?})",
        pod_name, cont_name, reconnect_count, backoff
      );
      tokio::time::sleep(backoff).await;
    }

    let mut app = self.app.lock().await;
    app.is_streaming = false;
  }

  /// Fetch the previous (terminated) container instance's logs in one shot.
  /// Unlike live logs this does not follow — a crashed/restarted container's
  /// last instance is static. Absence of a prior instance is surfaced in the
  /// log view rather than as a hard error.
  pub async fn fetch_previous_logs(&self) {
    let (namespace, pod_name, cont_name, tail_lines, timestamps) = {
      let app = self.app.lock().await;
      let ns = app
        .data
        .pods
        .get_selected_item_copy()
        .map(|p| p.namespace)
        .unwrap_or_else(|| std::env::var("NAMESPACE").unwrap_or_else(|_| "default".into()));
      let pod = app
        .data
        .pods
        .get_selected_item_copy()
        .map(|p| p.name)
        .unwrap_or_default();
      let cont = app.data.selected.container.clone().unwrap_or_default();
      let tail_lines = app.initial_log_tail_lines();
      (ns, pod, cont, tail_lines, app.log_timestamps)
    };

    if pod_name.is_empty() || cont_name.is_empty() {
      return;
    }

    let api: Api<Pod> = Api::namespaced(self.client.clone(), &namespace);
    let lp = LogParams {
      container: Some(cont_name.clone()),
      previous: true,
      follow: false,
      tail_lines: Some(tail_lines),
      timestamps,
      ..Default::default()
    };

    match api.logs(&pod_name, &lp).await {
      Ok(logs) => {
        let lines: Vec<String> = logs.lines().map(|line| line.to_string()).collect();
        let mut app = self.app.lock().await;
        if lines.is_empty() {
          app.data.logs.add_records(vec![format!(
            "[kdash] No previous logs for container {} (it has not restarted)",
            cont_name
          )]);
        } else {
          app.data.logs.add_records(lines);
        }
      }
      Err(e) => {
        warn!(
          "Failed to fetch previous logs for {}/{}: {}",
          pod_name, cont_name, e
        );
        let mut app = self.app.lock().await;
        app.data.logs.add_records(vec![format!(
          "[kdash] No previous logs available for {} (the container has no prior terminated instance)",
          cont_name
        )]);
      }
    }
  }

  /// Stream logs from all containers of the selected pod concurrently.
  pub async fn stream_pod_all_container_logs(&self) {
    let (namespace, pod_name, container_names, tail_lines, timestamps, cancel_rx) = {
      let app = self.app.lock().await;
      let pod = app.data.pods.get_selected_item_copy();
      let ns = pod
        .as_ref()
        .map(|p| p.namespace.clone())
        .unwrap_or_else(|| std::env::var("NAMESPACE").unwrap_or_else(|_| "default".into()));
      let name = pod.as_ref().map(|p| p.name.clone()).unwrap_or_default();
      let containers: Vec<String> = pod
        .as_ref()
        .map(|p| p.containers.iter().map(|c| c.name.clone()).collect())
        .unwrap_or_default();
      let tail_lines = app.initial_log_tail_lines();
      let rx = app.new_log_cancel_rx();
      (ns, name, containers, tail_lines, app.log_timestamps, rx)
    };

    if pod_name.is_empty() || container_names.is_empty() {
      return;
    }

    // Single container — delegate to the standard single-container stream
    if container_names.len() == 1 {
      {
        let mut app = self.app.lock().await;
        app.data.selected.container = Some(container_names[0].clone());
      }
      self.stream_container_logs(true).await;
      return;
    }

    {
      let mut app = self.app.lock().await;
      app.is_streaming = true;
    }

    let (tx, mut rx) = tokio::sync::mpsc::channel::<String>(256);

    let mut join_set = tokio::task::JoinSet::new();
    for cont_name in container_names {
      let client = self.client.clone();
      let ns = namespace.clone();
      let pod = pod_name.clone();
      let tx = tx.clone();
      let cancel_rx = cancel_rx.clone();

      join_set.spawn(async move {
        stream_single_pod_for_aggregate(
          client,
          AggregateStreamTarget {
            namespace: ns,
            pod_name: pod,
            container_name: cont_name.clone(),
            short_name: cont_name,
          },
          tail_lines,
          timestamps,
          tx,
          cancel_rx,
        )
        .await;
      });
    }

    drop(tx);

    let mut batch: Vec<String> = Vec::with_capacity(BATCH_SIZE);
    let mut last_flush = Instant::now();
    let mut cancel_rx_collector = cancel_rx.clone();

    loop {
      let flush_deadline =
        tokio::time::sleep_until(last_flush + Duration::from_millis(BATCH_FLUSH_MS));

      tokio::select! {
        _ = cancel_rx_collector.changed() => {
          if *cancel_rx_collector.borrow() {
            if !batch.is_empty() {
              let mut app = self.app.lock().await;
              app.data.logs.add_records(batch);
            }
            break;
          }
        }
        line = rx.recv() => {
          match line {
            Some(line) => {
              batch.push(line);
              if batch.len() >= BATCH_SIZE {
                let mut app = self.app.lock().await;
                app.data.logs.add_records(std::mem::replace(
                  &mut batch,
                  Vec::with_capacity(BATCH_SIZE),
                ));
                last_flush = Instant::now();
              }
            }
            None => {
              if !batch.is_empty() {
                let mut app = self.app.lock().await;
                app.data.logs.add_records(batch);
              }
              break;
            }
          }
        }
        _ = flush_deadline => {
          if !batch.is_empty() {
            let mut app = self.app.lock().await;
            app.data.logs.add_records(std::mem::replace(
              &mut batch,
              Vec::with_capacity(BATCH_SIZE),
            ));
            last_flush = Instant::now();
          }
        }
      }
    }

    join_set.shutdown().await;
    let mut app = self.app.lock().await;
    app.is_streaming = false;
  }

  /// Stream logs from all pods matching a label selector concurrently.
  /// Lines are prefixed with the pod name for disambiguation.
  pub async fn stream_aggregate_logs(&self, namespace: &str, selector: &str) {
    let (tail_lines, timestamps, cancel_rx) = {
      let app = self.app.lock().await;
      (
        app.initial_log_tail_lines(),
        app.log_timestamps,
        app.new_log_cancel_rx(),
      )
    };

    // Fetch pods matching the selector
    let api: Api<Pod> = Api::namespaced(self.client.clone(), namespace);
    let lp = ListParams::default().labels(selector);
    let pods = match api.list(&lp).await {
      Ok(list) => list.items,
      Err(e) => {
        self
          .handle_error(anyhow!(
            "Failed to list pods for selector '{}': {}",
            selector,
            e
          ))
          .await;
        return;
      }
    };

    if pods.is_empty() {
      let mut app = self.app.lock().await;
      app
        .data
        .logs
        .add_records(vec!["[kdash] No pods found for this resource".to_string()]);
      return;
    }

    let total_pods = pods.len();
    let pods: Vec<Pod> = pods.into_iter().take(MAX_AGGREGATE_PODS).collect();
    let streaming_count = pods.len();

    if total_pods > MAX_AGGREGATE_PODS {
      let mut app = self.app.lock().await;
      app.data.logs.add_records(vec![format!(
        "[kdash] Showing logs from {} of {} pods",
        MAX_AGGREGATE_PODS, total_pods
      )]);
    }

    {
      let mut app = self.app.lock().await;
      app.is_streaming = true;
    }

    let pod_info = collect_pod_container_info(&pods);

    info!(
      "Starting aggregate log stream for {} container streams (selector: {})",
      pod_info.len(),
      selector
    );

    // Use a channel to collect lines from all pod streams
    let (tx, mut rx) = tokio::sync::mpsc::channel::<String>(256);

    // Spawn a task per container
    let mut join_set = tokio::task::JoinSet::new();
    for (pod_name, cont_name, prefix) in pod_info {
      let client = self.client.clone();
      let ns = namespace.to_string();
      let tx = tx.clone();
      let cancel_rx = cancel_rx.clone();

      join_set.spawn(async move {
        stream_single_pod_for_aggregate(
          client,
          AggregateStreamTarget {
            namespace: ns,
            pod_name,
            container_name: cont_name,
            short_name: prefix,
          },
          tail_lines,
          timestamps,
          tx,
          cancel_rx,
        )
        .await;
      });
    }

    // Drop our copy of tx so rx will close when all tasks finish
    drop(tx);

    // Collector loop: read from channel, batch-flush to app.data.logs
    let mut batch: Vec<String> = Vec::with_capacity(BATCH_SIZE);
    let mut last_flush = Instant::now();
    let mut cancel_rx_collector = cancel_rx.clone();

    loop {
      let flush_deadline =
        tokio::time::sleep_until(last_flush + Duration::from_millis(BATCH_FLUSH_MS));

      tokio::select! {
        _ = cancel_rx_collector.changed() => {
          if *cancel_rx_collector.borrow() {
            if !batch.is_empty() {
              let mut app = self.app.lock().await;
              app.data.logs.add_records(batch);
            }
            debug!("Aggregate log stream cancelled (selector: {})", selector);
            break;
          }
        }
        line = rx.recv() => {
          match line {
            Some(line) => {
              batch.push(line);
              if batch.len() >= BATCH_SIZE {
                let mut app = self.app.lock().await;
                app.data.logs.add_records(std::mem::replace(
                  &mut batch,
                  Vec::with_capacity(BATCH_SIZE),
                ));
                last_flush = Instant::now();
              }
            }
            None => {
              // All senders dropped — all pod streams finished
              if !batch.is_empty() {
                let mut app = self.app.lock().await;
                app.data.logs.add_records(batch);
              }
              break;
            }
          }
        }
        _ = flush_deadline => {
          if !batch.is_empty() {
            let mut app = self.app.lock().await;
            app.data.logs.add_records(std::mem::replace(
              &mut batch,
              Vec::with_capacity(BATCH_SIZE),
            ));
            last_flush = Instant::now();
          }
        }
      }
    }

    // Wait for all spawned tasks to finish
    join_set.abort_all();

    let mut app = self.app.lock().await;
    app.is_streaming = false;
    info!(
      "Aggregate log stream ended for {} pods (selector: {})",
      streaming_count, selector
    );
  }

  /// Spawn a background `kubectl port-forward` child, track it in app state, and
  /// watch its output for readiness/failure. The TUI stays up (unlike the
  /// foreground shell-exec/edit actions).
  pub async fn start_port_forward(
    &self,
    kind: String,
    namespace: String,
    name: String,
    local_port: u16,
    remote_port: u16,
  ) {
    let target = PortForwardTarget {
      kind,
      namespace,
      name,
      local_port,
      remote_port,
    };
    let command = match prepare_port_forward(&target) {
      Ok(command) => command,
      Err(error) => {
        self.handle_error(anyhow!(error.to_string())).await;
        return;
      }
    };

    let mut child = match Command::new(&command.program)
      .args(&command.args)
      .stdin(Stdio::null())
      .stdout(Stdio::piped())
      .stderr(Stdio::piped())
      .kill_on_drop(true)
      .spawn()
    {
      Ok(child) => child,
      Err(error) => {
        self
          .handle_error(anyhow!(
            "Unable to start kubectl port-forward (is kubectl installed?): {}",
            error
          ))
          .await;
        return;
      }
    };

    let stdout = child.stdout.take();
    let stderr = child.stderr.take();

    let id = {
      let mut app = self.app.lock().await;
      app.add_port_forward(
        target.kind,
        target.namespace,
        target.name,
        local_port,
        remote_port,
        child,
      )
    };

    if let (Some(stdout), Some(stderr)) = (stdout, stderr) {
      let app = Arc::clone(self.app);
      tokio::spawn(async move {
        watch_port_forward(app, id, stdout, stderr).await;
      });
    }
  }

  /// Stop a tracked forward: remove it from app state and kill+reap the child on
  /// the runtime that owns it.
  pub async fn stop_port_forward(&self, id: u64) {
    let child = {
      let mut app = self.app.lock().await;
      app.remove_port_forward(id)
    };
    if let Some(mut child) = child {
      let _ = child.kill().await;
    }
    let mut app = self.app.lock().await;
    app.set_status_message("Stopped port-forward");
  }
}

/// Read a forward's kubectl output until it exits. The first
/// "Forwarding from …" line on stdout marks it active; an early exit (or any
/// exit) reads stderr for the reason and marks it failed. Updates are no-ops if
/// the forward was already removed (e.g. user stop).
async fn watch_port_forward(
  app: Arc<Mutex<App>>,
  id: u64,
  stdout: ChildStdout,
  stderr: ChildStderr,
) {
  let mut lines = BufReader::new(stdout).lines();
  let mut active = false;

  // Reads until EOF/error (kubectl exited or was killed). Other lines ("Handling
  // connection for …") are drained so the pipe never fills and blocks kubectl.
  while let Ok(Some(line)) = lines.next_line().await {
    if !active && line.contains("Forwarding from") {
      active = true;
      let mut app = app.lock().await;
      app.set_port_forward_status(id, PortForwardStatus::Active);
    }
  }

  if active {
    // Was forwarding and the process ended on its own (pod died, etc.).
    let mut app = app.lock().await;
    app.set_port_forward_status(id, PortForwardStatus::Failed("connection closed".into()));
  } else {
    let reason = read_port_forward_error(stderr).await;
    let mut app = app.lock().await;
    app.set_port_forward_status(id, PortForwardStatus::Failed(reason));
  }
}

/// Read kubectl's stderr after an early exit and extract a short failure reason.
async fn read_port_forward_error(stderr: ChildStderr) -> String {
  let mut buf = String::new();
  let _ = BufReader::new(stderr).read_to_string(&mut buf).await;
  summarize_port_forward_error(&buf)
}

/// First non-empty stderr line, truncated to keep the toast/list line short.
fn summarize_port_forward_error(stderr: &str) -> String {
  let reason = stderr
    .lines()
    .map(str::trim)
    .find(|line| !line.is_empty())
    .unwrap_or("port-forward exited");
  if reason.chars().count() > 80 {
    reason.chars().take(77).collect::<String>() + "..."
  } else {
    reason.to_string()
  }
}

/// Extract a short pod name suffix for log prefixes.
/// e.g., "myapp-deploy-abc123" → "abc123"
fn short_pod_name(name: &str) -> String {
  name.rsplit('-').next().unwrap_or(name).to_string()
}

/// Collect (pod_name, container_name, log_line_prefix) for every container in every pod.
/// When a pod has multiple containers, the prefix includes both pod suffix and container name.
fn collect_pod_container_info(pods: &[Pod]) -> Vec<(String, String, String)> {
  pods
    .iter()
    .filter_map(|pod| {
      let name = pod.metadata.name.clone().unwrap_or_default();
      let containers: Vec<String> = pod
        .spec
        .as_ref()
        .map(|s| s.containers.iter().map(|c| c.name.clone()).collect())
        .unwrap_or_default();
      if name.is_empty() || containers.is_empty() {
        None
      } else {
        let short = short_pod_name(&name);
        let multi = containers.len() > 1;
        Some(
          containers
            .into_iter()
            .map(move |c| {
              let prefix = if multi {
                format!("{}:{}", short, c)
              } else {
                short.clone()
              };
              (name.clone(), c, prefix)
            })
            .collect::<Vec<_>>(),
        )
      }
    })
    .flatten()
    .collect()
}

struct AggregateStreamTarget {
  namespace: String,
  pod_name: String,
  container_name: String,
  short_name: String,
}

/// Stream logs from a single pod, prefixing each line and sending to the channel.
async fn stream_single_pod_for_aggregate(
  client: Client,
  stream_target: AggregateStreamTarget,
  tail_lines: i64,
  timestamps: bool,
  tx: tokio::sync::mpsc::Sender<String>,
  cancel_rx: tokio::sync::watch::Receiver<bool>,
) {
  let AggregateStreamTarget {
    namespace,
    pod_name,
    container_name,
    short_name,
  } = stream_target;
  let api: Api<Pod> = Api::namespaced(client, &namespace);
  let lp = LogParams {
    container: Some(container_name.clone()),
    follow: true,
    previous: false,
    tail_lines: Some(tail_lines),
    timestamps,
    ..Default::default()
  };

  match api.log_stream(&pod_name, &lp).await {
    Ok(logs) => {
      let mut lines_stream = logs.lines();
      let mut cancel_rx = cancel_rx;

      loop {
        tokio::select! {
          _ = cancel_rx.changed() => {
            if *cancel_rx.borrow() {
              return;
            }
          }
          line = lines_stream.next() => {
            match line {
              Some(Ok(line)) => {
                let line = line.trim().to_string();
                if !line.is_empty() {
                  let prefixed = format!("[{}] {}", short_name, line);
                  if tx.send(prefixed).await.is_err() {
                    return; // Receiver dropped
                  }
                }
              }
              Some(Err(e)) => {
                warn!(
                  "Aggregate stream error for {}/{}: {}",
                  pod_name, container_name, e
                );
                return;
              }
              None => {
                debug!("Aggregate stream ended for {}/{}", pod_name, container_name);
                return;
              }
            }
          }
        }
      }
    }
    Err(e) => {
      warn!(
        "Failed to open aggregate log stream for {}/{}: {}",
        pod_name, container_name, e
      );
      let _ = tx
        .send(format!(
          "[{}] Error: failed to stream logs: {}",
          short_name, e
        ))
        .await;
    }
  }
}

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

  #[test]
  fn test_short_pod_name_extracts_suffix() {
    assert_eq!(short_pod_name("myapp-deploy-abc123"), "abc123");
  }

  #[test]
  fn test_short_pod_name_single_segment() {
    assert_eq!(short_pod_name("mypod"), "mypod");
  }

  #[test]
  fn test_short_pod_name_empty() {
    assert_eq!(short_pod_name(""), "");
  }

  #[test]
  fn test_short_pod_name_trailing_dash() {
    assert_eq!(short_pod_name("nginx-"), "");
  }

  #[test]
  fn test_io_stream_event_variants() {
    let event = IoStreamEvent::GetAggregateLogs {
      namespace: "default".into(),
      selector: "app=nginx".into(),
    };
    assert_eq!(
      event,
      IoStreamEvent::GetAggregateLogs {
        namespace: "default".into(),
        selector: "app=nginx".into(),
      }
    );
  }

  #[test]
  fn test_port_forward_stream_events_round_trip() {
    let start = IoStreamEvent::StartPortForward {
      kind: "pods".into(),
      namespace: "default".into(),
      name: "web".into(),
      local_port: 8080,
      remote_port: 80,
    };
    assert_eq!(start.clone(), start);
    assert_eq!(
      IoStreamEvent::StopPortForward { id: 3 },
      IoStreamEvent::StopPortForward { id: 3 }
    );
  }

  #[test]
  fn test_summarize_port_forward_error_picks_first_line_and_truncates() {
    assert_eq!(
      summarize_port_forward_error(
        "\n  Unable to listen on port 8080: bind: address already in use\nmore"
      ),
      "Unable to listen on port 8080: bind: address already in use"
    );
    assert_eq!(
      summarize_port_forward_error("   \n  "),
      "port-forward exited"
    );

    let long = "x".repeat(200);
    let summary = summarize_port_forward_error(&long);
    assert_eq!(summary.chars().count(), 80);
    assert!(summary.ends_with("..."));
  }

  fn make_pod(name: &str, containers: &[&str]) -> Pod {
    use k8s_openapi::api::core::v1::{Container, PodSpec};
    Pod {
      metadata: k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta {
        name: Some(name.into()),
        ..Default::default()
      },
      spec: Some(PodSpec {
        containers: containers
          .iter()
          .map(|c| Container {
            name: c.to_string(),
            ..Default::default()
          })
          .collect(),
        ..Default::default()
      }),
      ..Default::default()
    }
  }

  #[test]
  fn test_collect_pod_container_info_single_container() {
    let pods = vec![make_pod("myapp-deploy-abc123", &["web"])];
    let info = collect_pod_container_info(&pods);

    assert_eq!(info.len(), 1);
    assert_eq!(info[0].0, "myapp-deploy-abc123");
    assert_eq!(info[0].1, "web");
    // single container: prefix is just the short pod name
    assert_eq!(info[0].2, "abc123");
  }

  #[test]
  fn test_collect_pod_container_info_multi_container() {
    let pods = vec![make_pod("myapp-deploy-abc123", &["web", "sidecar"])];
    let info = collect_pod_container_info(&pods);

    assert_eq!(info.len(), 2);
    assert_eq!(
      info[0],
      (
        "myapp-deploy-abc123".into(),
        "web".into(),
        "abc123:web".into()
      )
    );
    assert_eq!(
      info[1],
      (
        "myapp-deploy-abc123".into(),
        "sidecar".into(),
        "abc123:sidecar".into()
      )
    );
  }

  #[test]
  fn test_collect_pod_container_info_multiple_pods() {
    let pods = vec![
      make_pod("app-abc12", &["main"]),
      make_pod("app-def34", &["main", "logging"]),
    ];
    let info = collect_pod_container_info(&pods);

    assert_eq!(info.len(), 3);
    // first pod: single container
    assert_eq!(info[0], ("app-abc12".into(), "main".into(), "abc12".into()));
    // second pod: multi container
    assert_eq!(
      info[1],
      ("app-def34".into(), "main".into(), "def34:main".into())
    );
    assert_eq!(
      info[2],
      ("app-def34".into(), "logging".into(), "def34:logging".into())
    );
  }

  #[test]
  fn test_collect_pod_container_info_skips_empty_name() {
    let pods = vec![make_pod("", &["web"])];
    let info = collect_pod_container_info(&pods);
    assert!(info.is_empty());
  }

  #[test]
  fn test_collect_pod_container_info_skips_no_containers() {
    let pods = vec![make_pod("myapp-abc123", &[])];
    let info = collect_pod_container_info(&pods);
    assert!(info.is_empty());
  }

  #[test]
  fn test_collect_pod_container_info_skips_no_spec() {
    let pod = Pod {
      metadata: k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta {
        name: Some("myapp".into()),
        ..Default::default()
      },
      spec: None,
      ..Default::default()
    };
    let info = collect_pod_container_info(&[pod]);
    assert!(info.is_empty());
  }
}