kdash 1.1.1

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
#![warn(rust_2018_idioms)]
#[deny(clippy::shadow_unrelated)]
mod app;
mod banner;
mod cmd;
mod config;
mod event;
mod handlers;
mod network;
mod ui;

use std::{
  fs::File,
  io::{self, stdout, Stdout},
  panic::{self, PanicHookInfo},
  sync::Arc,
};

use anyhow::{anyhow, Result};
use app::{key_binding::initialize_keybindings, App, DEFAULT_LOG_TAIL_LINES};
use banner::BANNER;
use chrono::{self};
use clap::{builder::PossibleValuesParser, Parser};
use cmd::{
  shell::{prepare_shell_exec, run_shell_exec, ShellExecTarget},
  CmdRunner, IoCmdEvent,
};
use config::load_config;
use crossterm::{
  event::{KeyEvent, MouseEvent},
  execute,
  terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use event::Key;
use log::{info, warn, LevelFilter, SetLoggerError};
use network::{
  get_client,
  stream::{IoStreamEvent, NetworkStream},
  IoEvent, Network,
};
use ratatui::{
  backend::{Backend, CrosstermBackend},
  Terminal,
};
use simplelog::{Config, WriteLogger};
use tokio::sync::{mpsc, Mutex};
use ui::theme::initialize_theme;

/// kdash CLI
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None, override_usage = "Press `?` while running the app to see keybindings", before_help = BANNER)]
pub struct Cli {
  /// Set the tick rate (milliseconds): the lower the number the higher the FPS.
  #[arg(short, long, value_parser, default_value_t = 250)]
  pub tick_rate: u64,
  /// Set the network call polling rate (milliseconds, should be multiples of tick-rate):
  /// the lower the number the higher the network calls.
  #[arg(short, long, value_parser, default_value_t = 5000)]
  pub poll_rate: u64,
  /// whether unicode symbols are used to improve the overall look of the app
  #[arg(short, long, value_parser, default_value_t = true)]
  pub enhanced_graphics: bool,
  /// Enables debug mode and writes logs to 'kdash-debug-<timestamp>.log' file in the current directory.
  /// Default behavior is to write INFO logs. Pass a log level to overwrite the default.
  #[arg(
    name = "debug",
    short,
    long,
    default_missing_value = "Info",
    require_equals = true,
    num_args = 0..=1,
    ignore_case = true,
    value_parser = PossibleValuesParser::new(&["info", "debug", "trace", "warn", "error"])
  )]
  pub debug: Option<String>,
  /// Set how many historical log lines to fetch before live streaming starts.
  #[arg(long, value_parser = clap::value_parser!(u32).range(1..))]
  pub log_tail_lines: Option<u32>,
}

#[tokio::main]
async fn main() -> Result<()> {
  // SAFETY: safe as this is called once at startup before spawning threads
  unsafe { openssl_probe::try_init_openssl_env_vars() };
  panic::set_hook(Box::new(|info| {
    panic_hook(info);
  }));

  // parse CLI arguments
  let cli = Cli::parse();

  // Setup logging if debug flag is set
  if cli.debug.is_some() {
    setup_logging(cli.debug.clone())?;
    info!(
      "Debug mode is enabled. Level: {}, KDash version: {}",
      cli.debug.clone().unwrap(),
      env!("CARGO_PKG_VERSION")
    );
  }

  if cli.tick_rate >= 1000 {
    panic!("Tick rate must be below 1000");
  }
  if (cli.poll_rate % cli.tick_rate) > 0u64 {
    panic!("Poll rate must be multiple of tick-rate");
  }

  // channels for communication between network/cmd threads & UI thread
  let (sync_io_tx, sync_io_rx) = mpsc::channel::<IoEvent>(500);
  let (sync_io_stream_tx, sync_io_stream_rx) = mpsc::channel::<IoStreamEvent>(500);
  let (sync_io_cmd_tx, sync_io_cmd_rx) = mpsc::channel::<IoCmdEvent>(500);
  let loaded_config = load_config();
  let log_tail_lines = resolve_log_tail_lines(cli.log_tail_lines, &loaded_config.config);
  let mut config_warnings = vec![];
  if let Some(warning) = loaded_config.warning.clone() {
    config_warnings.push(warning);
  }
  config_warnings.extend(initialize_keybindings(&loaded_config.config));
  config_warnings.extend(initialize_theme(&loaded_config.config));

  // Initialize app state
  let app = Arc::new(Mutex::new(App::new(
    sync_io_tx,
    sync_io_stream_tx,
    sync_io_cmd_tx,
    cli.enhanced_graphics,
    cli.poll_rate / cli.tick_rate,
    log_tail_lines,
    loaded_config.config,
  )));

  {
    let app = app.lock().await;
    if app.config.keybindings.is_some() || app.config.theme.is_some() {
      info!("Loaded config overrides from file");
    }
  }

  if !config_warnings.is_empty() {
    let mut app = app.lock().await;
    app.handle_error(anyhow!(config_warnings.join(" | ")));
  }

  // Launch network, stream, and cmd tasks on a dedicated tokio runtime running
  // on its own OS thread.  This keeps all network I/O off the main runtime so
  // the UI loop is never starved of CPU time by long-running API calls.
  let app_nw = Arc::clone(&app);
  let app_stream = Arc::clone(&app);
  let app_cli = Arc::clone(&app);

  std::thread::spawn(move || {
    let rt = tokio::runtime::Builder::new_multi_thread()
      .enable_all()
      .thread_name("kdash-network")
      .build()
      .expect("Failed to create network runtime");

    rt.block_on(async move {
      tokio::spawn(async move {
        info!("Starting network task");
        start_network(sync_io_rx, &app_nw).await;
      });

      tokio::spawn(async move {
        info!("Starting network stream task");
        start_stream_network(sync_io_stream_rx, &app_stream).await;
      });

      tokio::spawn(async move {
        info!("Starting cmd runner task");
        start_cmd_runner(sync_io_cmd_rx, &app_cli).await;
      });

      // Keep this runtime alive until all tasks complete.
      // When the UI exits and drops the channel senders, recv() returns None
      // and the tasks finish naturally.
      tokio::signal::ctrl_c()
        .await
        .expect("Failed to listen for ctrl_c");
    });
  });

  // Launch the UI on the main runtime — it owns the terminal and must run here
  start_ui(cli, &app).await?;

  Ok(())
}

async fn start_network(mut io_rx: mpsc::Receiver<IoEvent>, app: &Arc<Mutex<App>>) {
  match get_client(None).await {
    Ok(client) => {
      let mut network = Network::new(client, app);

      while let Some(io_event) = io_rx.recv().await {
        info!("Network event received: {:?}", io_event);
        network.handle_network_event(io_event).await;
      }
    }
    Err(e) => {
      let mut app = app.lock().await;
      app.handle_error(anyhow!("Unable to obtain Kubernetes client. {}", e));
    }
  }
}

fn resolve_log_tail_lines(cli_value: Option<u32>, config: &config::KdashConfig) -> u32 {
  cli_value
    .or(config.log_tail_lines)
    .unwrap_or(DEFAULT_LOG_TAIL_LINES)
}

async fn start_stream_network(mut io_rx: mpsc::Receiver<IoStreamEvent>, app: &Arc<Mutex<App>>) {
  match get_client(None).await {
    Ok(client) => {
      let mut network = NetworkStream::new(client, app);

      while let Some(io_event) = io_rx.recv().await {
        info!("Network stream event received: {:?}", io_event);
        network.handle_network_stream_event(io_event).await;
      }
    }
    Err(e) => {
      let mut app = app.lock().await;
      app.handle_error(anyhow!("Unable to obtain Kubernetes client. {}", e));
    }
  }
}

async fn start_cmd_runner(mut io_rx: mpsc::Receiver<IoCmdEvent>, app: &Arc<Mutex<App>>) {
  let mut cmd = CmdRunner::new(app);

  while let Some(io_event) = io_rx.recv().await {
    info!("Cmd event received: {:?}", io_event);
    cmd.handle_cmd_event(io_event).await;
  }
}

/// Process a single UI event.  Returns `true` when the app should exit (Ctrl+C).
async fn process_event(
  app: &mut App,
  ev: event::Event<KeyEvent, MouseEvent>,
  is_first_render: &mut bool,
  tick_seen: &mut bool,
) -> bool {
  match ev {
    event::Event::Input(key_event) => {
      let key = Key::from(key_event);
      if key == Key::Ctrl('c') {
        true
      } else {
        handlers::handle_key_events(key, key_event, app).await;
        false
      }
    }
    event::Event::MouseInput(mouse) => {
      handlers::handle_mouse_events(mouse, app).await;
      false
    }
    event::Event::Tick => {
      app.on_tick(*is_first_render).await;
      *is_first_render = false;
      *tick_seen = true;
      false
    }
    event::Event::KubeConfigChange => {
      info!("Kubeconfig change detected, reloading");
      app.dispatch(IoEvent::GetKubeConfig).await;
      false
    }
  }
}

async fn start_ui(cli: Cli, app: &Arc<Mutex<App>>) -> Result<()> {
  info!("Starting UI");
  // see https://docs.rs/crossterm/0.17.7/crossterm/terminal/#raw-mode
  enable_raw_mode()?;
  // Terminal initialization
  let mut stdout = stdout();
  // not capturing mouse to make text select/copy possible
  execute!(stdout, EnterAlternateScreen)?;
  // terminal backend for cross platform support
  let backend = CrosstermBackend::new(stdout);
  let mut terminal = Terminal::new(backend)?;
  terminal.clear()?;
  terminal.hide_cursor()?;
  // custom events
  let mut events = event::Events::new(cli.tick_rate);
  let mut is_first_render = true;
  // Perform initial draw so the user sees the UI immediately
  {
    let mut app = app.lock().await;
    if let Ok(size) = terminal.backend().size() {
      app.size.width = size.width;
      app.size.height = size.height;
    }
    terminal.draw(|f| ui::draw(f, &mut app))?;
  }
  // main UI loop
  loop {
    // Wait for the next event BEFORE acquiring the lock.
    // This is the blocking call — no reason to hold the mutex while waiting.
    let event = events.next()?;

    let (pending_shell_exec, should_quit) = {
      let mut app = app.lock().await;

      // Handle events BEFORE drawing so the frame always reflects
      // the latest state, eliminating the 1-event visual lag.

      // Process the blocking event
      let mut tick_seen = false;
      let mut should_break =
        process_event(&mut app, event, &mut is_first_render, &mut tick_seen).await;

      // Drain any pending events so rapid key-presses are batched into a
      // single render pass instead of each triggering a stale redraw.
      // Cap at 20 to bound worst-case lock hold under input flood.
      // Coalesce Ticks: after one Tick fires `on_tick`, drop the rest in
      // this batch so a stall doesn't replay the backlog as a poll burst.
      if !should_break {
        for _ in 0..20 {
          match events.try_next() {
            Some(event::Event::Tick) if tick_seen => continue,
            Some(ev) => {
              should_break =
                process_event(&mut app, ev, &mut is_first_render, &mut tick_seen).await;
              if should_break {
                break;
              }
            }
            None => break,
          }
        }
      }

      if should_break {
        break;
      }

      // Get the size of the screen on each loop to account for resize events
      if let Ok(size) = terminal.backend().size() {
        if app.refresh || app.size.as_size() != size {
          app.size.width = size.width;
          app.size.height = size.height;
        }
      }

      // Draw the UI layout AFTER processing events so the frame is up-to-date
      terminal.draw(|f| ui::draw(f, &mut app))?;

      let pending_shell_exec = app.take_pending_shell_exec();
      let should_quit = app.should_quit;
      (pending_shell_exec, should_quit)
    };

    if let Some(request) = pending_shell_exec {
      drop(events);
      execute_pending_shell_exec(app, &mut terminal, request).await?;
      events = event::Events::new(cli.tick_rate);
    }

    if should_quit {
      break;
    }
  }

  terminal.show_cursor()?;
  shutdown(terminal)?;
  Ok(())
}

// shutdown the CLI and show terminal
fn shutdown(mut terminal: Terminal<CrosstermBackend<Stdout>>) -> Result<()> {
  info!("Shutting down");
  disable_raw_mode()?;
  execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
  terminal.show_cursor()?;
  Ok(())
}

fn suspend_terminal(terminal: &mut Terminal<CrosstermBackend<Stdout>>) -> Result<()> {
  disable_raw_mode()?;
  execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
  terminal.show_cursor()?;
  Ok(())
}

fn restore_terminal(terminal: &mut Terminal<CrosstermBackend<Stdout>>) -> Result<()> {
  enable_raw_mode()?;
  execute!(terminal.backend_mut(), EnterAlternateScreen)?;
  terminal.hide_cursor()?;
  terminal.clear()?;
  Ok(())
}

trait ShellTerminal {
  fn suspend(&mut self) -> Result<()>;
  fn restore(&mut self) -> Result<()>;
}

impl ShellTerminal for Terminal<CrosstermBackend<Stdout>> {
  fn suspend(&mut self) -> Result<()> {
    suspend_terminal(self)
  }

  fn restore(&mut self) -> Result<()> {
    restore_terminal(self)
  }
}

async fn execute_pending_shell_exec(
  app: &Arc<Mutex<App>>,
  terminal: &mut Terminal<CrosstermBackend<Stdout>>,
  request: app::PendingShellExec,
) -> Result<()> {
  execute_pending_shell_exec_with(app, terminal, request, |request| {
    let target = ShellExecTarget {
      namespace: request.namespace,
      pod: request.pod,
      container: request.container,
    };
    let command = prepare_shell_exec(&target).map_err(|error| anyhow!(error.to_string()))?;
    let shell = command.shell.clone();
    run_shell_exec(&command).map_err(|error| anyhow!(error.to_string()))?;
    Ok(shell)
  })
  .await
}

async fn execute_pending_shell_exec_with<F, T>(
  app: &Arc<Mutex<App>>,
  terminal: &mut T,
  request: app::PendingShellExec,
  run_shell: F,
) -> Result<()>
where
  F: FnOnce(app::PendingShellExec) -> Result<String>,
  T: ShellTerminal,
{
  terminal.suspend()?;
  let shell_result = run_shell(request.clone());
  let restore_result = terminal.restore();

  let mut app = app.lock().await;

  if let Err(error) = restore_result {
    app.handle_error(anyhow!(
      "Unable to restore terminal after shell exec: {}",
      error
    ));
    return Err(error);
  }

  match shell_result {
    Ok(shell) => {
      app.set_status_message(format!(
        "Closed {} shell for {}/{}",
        shell, request.pod, request.container
      ));
      Ok(())
    }
    Err(error) => {
      app.handle_error(anyhow!(
        "Unable to open shell for {}/{}: {}",
        request.pod,
        request.container,
        error
      ));
      Ok(())
    }
  }
}

fn setup_logging(debug: Option<String>) -> Result<(), SetLoggerError> {
  let log_file = format!(
    "./kdash-debug-{}.log",
    chrono::Local::now().format("%Y%m%d%H%M%S")
  );
  let log_level = debug
    .map(|level| match level.to_lowercase().as_str() {
      "debug" => LevelFilter::Debug,
      "trace" => LevelFilter::Trace,
      "warn" => LevelFilter::Warn,
      "error" => LevelFilter::Error,
      _ => LevelFilter::Info,
    })
    .unwrap_or_else(|| LevelFilter::Info);

  WriteLogger::init(
    log_level,
    Config::default(),
    File::create(log_file).unwrap(),
  )
}

#[cfg(debug_assertions)]
fn panic_hook(info: &PanicHookInfo<'_>) {
  use backtrace::Backtrace;
  use crossterm::style::Print;

  let (msg, location) = get_panic_info(info);

  let stacktrace: String = format!("{:?}", Backtrace::new()).replace('\n', "\n\r");

  disable_raw_mode().unwrap();
  execute!(
    io::stdout(),
    LeaveAlternateScreen,
    Print(format!(
      "thread '<unnamed>' panicked at '{}', {}\n\r{}",
      msg, location, stacktrace
    )),
  )
  .unwrap();
}

#[cfg(not(debug_assertions))]
fn panic_hook(info: &PanicHookInfo<'_>) {
  use backtrace::Backtrace;
  use crossterm::style::Print;
  use human_panic::{handle_dump, print_msg, Metadata};
  use log::error;

  let meta = Metadata::new(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"))
    .authors(env!("CARGO_PKG_AUTHORS").replace(':', ", "))
    .homepage(env!("CARGO_PKG_HOMEPAGE"));

  let file_path = handle_dump(&meta, info);
  let (msg, location) = get_panic_info(info);
  let stacktrace: String = format!("{:?}", Backtrace::new()).replace('\n', "\n\r");

  error!(
    "thread '<unnamed>' panicked at '{}', {}\n\r{}",
    msg, location, stacktrace
  );

  disable_raw_mode().unwrap();
  execute!(
    io::stdout(),
    LeaveAlternateScreen,
    Print(format!("Error: '{}' at {}\n", msg, location)),
  )
  .unwrap();
  print_msg(file_path, &meta).expect("human-panic: printing error message to console failed");
}

fn get_panic_info(info: &PanicHookInfo<'_>) -> (String, String) {
  let location = info.location().unwrap();

  let msg = match info.payload().downcast_ref::<&'static str>() {
    Some(s) => *s,
    None => match info.payload().downcast_ref::<String>() {
      Some(s) => &s[..],
      None => "Box<Any>",
    },
  };

  (msg.to_string(), format!("{}", location))
}

#[cfg(test)]
mod tests {
  use super::{execute_pending_shell_exec_with, process_event, resolve_log_tail_lines};
  use crate::{app::App, config::KdashConfig, event};
  use anyhow::anyhow;
  use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
  use std::sync::Arc;
  use tokio::sync::Mutex;

  struct StubTerminal;

  impl super::ShellTerminal for StubTerminal {
    fn suspend(&mut self) -> anyhow::Result<()> {
      Ok(())
    }

    fn restore(&mut self) -> anyhow::Result<()> {
      Ok(())
    }
  }

  #[test]
  fn test_resolve_log_tail_lines_uses_default() {
    assert_eq!(resolve_log_tail_lines(None, &KdashConfig::default()), 100);
  }

  #[test]
  fn test_resolve_log_tail_lines_uses_config_when_cli_missing() {
    let config = KdashConfig {
      log_tail_lines: Some(250),
      ..KdashConfig::default()
    };

    assert_eq!(resolve_log_tail_lines(None, &config), 250);
  }

  #[test]
  fn test_resolve_log_tail_lines_prefers_cli() {
    let config = KdashConfig {
      log_tail_lines: Some(250),
      ..KdashConfig::default()
    };

    assert_eq!(resolve_log_tail_lines(Some(500), &config), 500);
  }

  #[tokio::test]
  async fn test_execute_pending_shell_exec_with_sets_success_status_and_clears_request() {
    let app = Arc::new(Mutex::new(App::default()));
    let mut terminal = StubTerminal;

    let result = execute_pending_shell_exec_with(
      &app,
      &mut terminal,
      crate::app::PendingShellExec {
        namespace: "default".into(),
        pod: "api-123".into(),
        container: "web".into(),
      },
      |_| Ok("/bin/sh".into()),
    )
    .await;

    assert!(result.is_ok());

    let app = app.lock().await;
    assert!(app.api_error.is_empty());
    assert_eq!(
      app.status_message.text(),
      "Closed /bin/sh shell for api-123/web"
    );
    assert!(app.pending_shell_exec().is_none());
  }

  #[tokio::test]
  async fn test_execute_pending_shell_exec_with_reports_shell_errors_after_restoring_terminal() {
    let app = Arc::new(Mutex::new(App::default()));
    let mut terminal = StubTerminal;

    let result = execute_pending_shell_exec_with(
      &app,
      &mut terminal,
      crate::app::PendingShellExec {
        namespace: "default".into(),
        pod: "api-123".into(),
        container: "web".into(),
      },
      |_| Err(anyhow!("probe failed")),
    )
    .await;

    assert!(result.is_ok());

    let app = app.lock().await;
    assert_eq!(
      app.api_error,
      "Unable to open shell for api-123/web: probe failed"
    );
    assert!(app.status_message.is_empty());
  }

  #[tokio::test]
  async fn test_process_event_tick_advances_state_and_sets_tick_seen() {
    let mut app = App::default();
    let mut is_first_render = true;
    let mut tick_seen = false;

    let exit = process_event(
      &mut app,
      event::Event::Tick,
      &mut is_first_render,
      &mut tick_seen,
    )
    .await;

    assert!(!exit);
    assert!(
      tick_seen,
      "Tick should set tick_seen so the drain can coalesce"
    );
    assert!(!is_first_render, "Tick should flip the first-render flag");
    assert_eq!(app.tick_count, 1);
  }

  #[tokio::test]
  async fn test_process_event_input_does_not_flip_first_render_or_tick_seen() {
    let mut app = App::default();
    let mut is_first_render = true;
    let mut tick_seen = false;

    let exit = process_event(
      &mut app,
      event::Event::Input(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)),
      &mut is_first_render,
      &mut tick_seen,
    )
    .await;

    assert!(!exit);
    assert!(
      is_first_render,
      "non-Tick events must not consume the first-render gate"
    );
    assert!(
      !tick_seen,
      "non-Tick events must not mark a tick as processed"
    );
    assert_eq!(app.tick_count, 0);
  }

  #[tokio::test]
  async fn test_process_event_ctrl_c_signals_exit() {
    let mut app = App::default();
    let mut is_first_render = true;
    let mut tick_seen = false;

    let exit = process_event(
      &mut app,
      event::Event::Input(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)),
      &mut is_first_render,
      &mut tick_seen,
    )
    .await;

    assert!(exit);
  }
}