cflx 0.6.153

Conflux – a spec-driven parallel coding orchestrator that runs AI agents on git worktrees
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
//! Key event handlers for TUI
//!
//! This module contains helper functions to handle keyboard input in the TUI.

use crate::ai_command_runner::AiCommandRunner;
use crate::config::OrchestratorConfig;
use crate::error::Result;
use crate::tui::events::{LogEntry, OrchestratorEvent, TuiCommand};
use crate::tui::state::AppState;
use crate::tui::types::{AppMode, StopMode};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::DefaultTerminal;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use tracing::debug;

use super::terminal::{execute_worktree_command, suspend_terminal_and_execute_sync};
use super::worktrees::load_worktrees_with_conflict_check;

/// Context for key event handling containing necessary state and channels
pub struct KeyEventContext<'a> {
    pub app: &'a mut AppState,
    pub terminal: &'a mut DefaultTerminal,
    pub repo_root: &'a Path,
    pub config: &'a OrchestratorConfig,
    pub worktree_base_dir: &'a Path,
    pub tx: &'a mpsc::Sender<OrchestratorEvent>,
    pub cmd_tx: &'a mpsc::Sender<TuiCommand>,
    pub ai_runner: &'a AiCommandRunner,
    pub graceful_stop_flag: &'a Arc<AtomicBool>,
    pub orchestrator_cancel: &'a Option<CancellationToken>,
    pub orchestrator_handle: &'a Option<tokio::task::JoinHandle<Result<()>>>,
}

fn request_local_tui_quit(app: &mut AppState, orchestrator_cancel: &Option<CancellationToken>) {
    app.should_quit = true;
    if let Some(cancel) = orchestrator_cancel {
        cancel.cancel();
        app.add_log(LogEntry::warn(
            "Quit requested: cancelling local orchestration before TUI shutdown",
        ));
    }
}

/// Handle Tab key: Switch between Changes and Worktrees views
pub async fn handle_tab_key(ctx: &mut KeyEventContext<'_>) -> Result<()> {
    use crate::tui::types::ViewMode;
    let new_view = match ctx.app.view_mode {
        ViewMode::Changes => ViewMode::Worktrees,
        ViewMode::Worktrees => ViewMode::Changes,
    };

    // Load worktrees with conflict check when switching to Worktrees view
    if new_view == ViewMode::Worktrees {
        let load_tx = ctx.tx.clone();
        let load_repo_root = ctx.repo_root.to_path_buf();
        tokio::spawn(async move {
            match load_worktrees_with_conflict_check(&load_repo_root).await {
                Ok(worktrees) => {
                    let _ = load_tx
                        .send(OrchestratorEvent::WorktreesRefreshed { worktrees })
                        .await;
                }
                Err(e) => {
                    let _ = load_tx
                        .send(OrchestratorEvent::Log(LogEntry::error(format!(
                            "Failed to load worktrees: {}",
                            e
                        ))))
                        .await;
                }
            }
        });
    }

    ctx.app.view_mode = new_view;
    Ok(())
}

/// Handle cursor movement keys (Up/Down/k/j)
pub fn handle_cursor_movement(app: &mut AppState, is_up: bool) {
    use crate::tui::types::ViewMode;
    match app.view_mode {
        ViewMode::Changes => {
            if is_up {
                app.cursor_up()
            } else {
                app.cursor_down()
            }
        }
        ViewMode::Worktrees => {
            if is_up {
                app.worktree_cursor_up()
            } else {
                app.worktree_cursor_down()
            }
        }
    }
}

/// Handle 'e' key: Launch editor for change or worktree
pub async fn handle_editor_launch(ctx: &mut KeyEventContext<'_>) -> Result<()> {
    use crate::tui::types::ViewMode;

    let view_mode = ctx.app.view_mode;
    let change_id = if !ctx.app.changes.is_empty() && ctx.app.cursor_index < ctx.app.changes.len() {
        Some(ctx.app.changes[ctx.app.cursor_index].id.clone())
    } else {
        None
    };
    let worktree_path = ctx.app.get_selected_worktree_path();
    if view_mode == ViewMode::Worktrees && ctx.app.suppress_if_selected_worktree_deleting() {
        ctx.app.add_log(LogEntry::warn(
            "Editor ignored: worktree is already being deleted",
        ));
        return Ok(());
    }

    suspend_terminal_and_execute_sync(ctx.terminal, || {
        // Launch editor based on view mode
        match view_mode {
            ViewMode::Changes => {
                if let Some(id) = change_id {
                    if let Err(e) = crate::tui::utils::launch_editor_for_change(&id) {
                        eprintln!("Failed to launch editor: {}", e);
                    }
                }
            }
            ViewMode::Worktrees => {
                if let Some(path) = worktree_path {
                    if let Err(e) = crate::tui::utils::launch_editor_in_dir(&path) {
                        eprintln!("Failed to launch editor: {}", e);
                    }
                }
            }
        }
        Ok(())
    })
}

/// Handle 'M' key: Merge operations (resolve in Changes view, merge in Worktrees view)
pub async fn handle_merge_key(ctx: &mut KeyEventContext<'_>) -> Result<()> {
    use crate::tui::types::ViewMode;

    debug!("M key pressed: view_mode={:?}", ctx.app.view_mode);

    match ctx.app.view_mode {
        ViewMode::Changes => {
            // Changes view: resolve deferred merge
            debug!("M key (Changes view): attempting resolve_merge");
            if let Some(cmd) = ctx.app.resolve_merge() {
                debug!("M key (Changes view): sending command {:?}", cmd);
                let _ = ctx.cmd_tx.send(cmd).await;
            } else {
                debug!("M key (Changes view): resolve_merge returned None");
            }
        }
        ViewMode::Worktrees => {
            // Worktrees view: merge branch to base
            debug!("M key (Worktrees view): attempting request_merge_worktree_branch");
            if let Some(cmd) = ctx.app.request_merge_worktree_branch() {
                debug!("M key (Worktrees view): sending command {:?}", cmd);
                let _ = ctx.cmd_tx.send(cmd).await;
            } else {
                debug!("M key (Worktrees view): request_merge_worktree_branch returned None");
            }
        }
    }
    Ok(())
}

/// Handle Esc key: Graceful stop or force stop
pub fn handle_esc_key(ctx: &mut KeyEventContext<'_>) {
    // Handle stop in Running or Stopping mode
    match ctx.app.mode {
        AppMode::Running => {
            // First Esc: Graceful stop
            ctx.app.stop_mode = StopMode::GracefulPending;
            ctx.graceful_stop_flag.store(true, Ordering::SeqCst);
            ctx.app.mode = AppMode::Stopping;
            ctx.app
                .add_log(LogEntry::warn("Stopping after current change completes..."));
        }
        AppMode::Stopping => {
            // Second Esc: Force stop
            ctx.app.stop_mode = StopMode::ForceStopped;
            if let Some(cancel) = ctx.orchestrator_cancel {
                cancel.cancel();
            }
            // Use OrchestratorEvent::Stopped to properly reset queue status
            // and preserve execution marks (same as graceful stop)
            ctx.app
                .handle_orchestrator_event(OrchestratorEvent::Stopped);
            ctx.app.current_change = None;
            ctx.app.add_log(LogEntry::warn("Force stopped"));
        }
        _ => {}
    }
}

fn handle_start_key_inner(
    app: &mut AppState,
    graceful_stop_flag: &AtomicBool,
    orchestrator_handle: &Option<tokio::task::JoinHandle<Result<()>>>,
) -> Option<TuiCommand> {
    // Handle the configured start key in Stopping mode to cancel graceful stop.
    if app.mode == AppMode::Stopping {
        // Check if orchestrator is still running.
        if orchestrator_handle
            .as_ref()
            .is_some_and(|h| !h.is_finished())
        {
            // Cancel graceful stop and return to Running mode.
            graceful_stop_flag.store(false, Ordering::SeqCst);
            app.stop_mode = StopMode::None;
            app.mode = AppMode::Running;
            app.add_log(LogEntry::info("Stop canceled, continuing..."));
        } else {
            // Already stopped, cannot cancel.
            app.add_log(LogEntry::warn(
                "Cannot cancel stop: processing already completed",
            ));
        }
        return None;
    }

    // The configured start key is a cursor-independent orchestration control.
    // It must not inspect the selected row for MergeWait/ResolveWait and must
    // not resolve cursor-local merge waits; Changes-view M is the cursor-local
    // resolve-intent key.
    if app.mode == AppMode::Error {
        app.retry_error_changes()
    } else if app.mode == AppMode::Stopped {
        app.resume_processing()
    } else {
        app.start_processing()
    }
}

/// Handle the configured start key: start, resume, or retry orchestration; or cancel stop.
pub fn handle_start_key(ctx: &mut KeyEventContext<'_>) -> Option<TuiCommand> {
    handle_start_key_inner(ctx.app, ctx.graceful_stop_flag, ctx.orchestrator_handle)
}

/// Handle Enter key: Execute worktree command in selected worktree
pub async fn handle_enter_key(ctx: &mut KeyEventContext<'_>) -> Result<()> {
    use crate::tui::types::ViewMode;

    if ctx.app.view_mode != ViewMode::Worktrees {
        ctx.app
            .add_log(LogEntry::warn("Enter ignored: not in Worktrees view"));
        return Ok(());
    }

    let Some(worktree_path_str) = ctx.app.get_selected_worktree_path() else {
        ctx.app
            .add_log(LogEntry::warn("Enter ignored: no worktree selected"));
        return Ok(());
    };

    if ctx.app.suppress_if_selected_worktree_deleting() {
        ctx.app.add_log(LogEntry::warn(
            "Enter ignored: worktree is already being deleted",
        ));
        return Ok(());
    }

    let Some(template) = ctx.config.get_worktree_command().map(str::to_string) else {
        ctx.app.add_log(LogEntry::warn(
            "Enter ignored: worktree_command not configured",
        ));
        return Ok(());
    };

    let Some(repo_root_str) = ctx.repo_root.to_str() else {
        ctx.app.add_log(LogEntry::error(
            "Failed to resolve repo root path".to_string(),
        ));
        return Ok(());
    };

    let command =
        OrchestratorConfig::expand_worktree_command(&template, &worktree_path_str, repo_root_str);

    ctx.app.add_log(LogEntry::info(format!(
        "Running worktree command in {}",
        worktree_path_str
    )));

    let worktree_path = Path::new(&worktree_path_str);
    execute_worktree_command(
        ctx.terminal,
        &command,
        worktree_path,
        ctx.ai_runner,
        ctx.app,
    )
    .await
}

/// Handle '+' key: Create new worktree and execute worktree command
pub async fn handle_plus_key(ctx: &mut KeyEventContext<'_>) -> Result<()> {
    use crate::tui::types::ViewMode;

    // Only work in Worktrees view
    if ctx.app.view_mode != ViewMode::Worktrees {
        return Ok(());
    }

    let Some(template) = ctx.config.get_worktree_command().map(str::to_string) else {
        return Ok(());
    };

    let is_git_repo = match crate::vcs::git::commands::check_git_repo(ctx.repo_root).await {
        Ok(is_repo) => is_repo,
        Err(err) => {
            ctx.app.add_log(LogEntry::error(format!(
                "Failed to check git repo: {}",
                err
            )));
            return Ok(());
        }
    };

    if !super::worktrees::should_trigger_worktree_command(ctx.config, is_git_repo) {
        return Ok(());
    }

    if let Err(err) = std::fs::create_dir_all(ctx.worktree_base_dir) {
        ctx.app.add_log(LogEntry::error(format!(
            "Failed to prepare worktree base dir: {}",
            err
        )));
        return Ok(());
    }

    let worktree_path = super::worktrees::build_worktree_path(ctx.worktree_base_dir);
    let Some(worktree_path_str) = worktree_path.to_str() else {
        ctx.app.add_log(LogEntry::error(
            "Failed to resolve worktree path".to_string(),
        ));
        return Ok(());
    };
    let Some(repo_root_str) = ctx.repo_root.to_str() else {
        ctx.app.add_log(LogEntry::error(
            "Failed to resolve repo root path".to_string(),
        ));
        return Ok(());
    };

    // Generate unique branch name with format: ws-session-<timestamp>
    let branch_name = match crate::vcs::git::commands::generate_unique_branch_name(
        ctx.repo_root,
        "ws-session",
        10,
    )
    .await
    {
        Ok(name) => name,
        Err(err) => {
            ctx.app.add_log(LogEntry::error(format!(
                "Failed to generate unique branch name: {}",
                err
            )));
            return Ok(());
        }
    };

    // Create worktree with branch instead of detached HEAD
    if let Err(err) = crate::vcs::git::commands::worktree_add(
        ctx.repo_root,
        worktree_path_str,
        &branch_name,
        "HEAD",
    )
    .await
    {
        ctx.app.add_log(LogEntry::error(format!(
            "Failed to create worktree: {}",
            err
        )));
        return Ok(());
    }

    ctx.app.add_log(LogEntry::info(format!(
        "Created worktree with branch '{}'",
        branch_name
    )));

    // Execute setup script if it exists
    if let Err(err) =
        crate::vcs::git::commands::run_worktree_setup(ctx.repo_root, &worktree_path).await
    {
        ctx.app.add_log(LogEntry::error(format!(
            "Failed to run worktree setup: {}",
            err
        )));
        // Don't continue - setup failure is considered an error
        // but the worktree was already created, so we should clean it up
        if let Err(cleanup_err) = crate::vcs::git::commands::worktree_remove_with_options(
            ctx.repo_root,
            worktree_path_str,
            crate::vcs::git::commands::WorktreeRemoveOptions {
                skip_teardown: true,
            },
        )
        .await
        {
            ctx.app.add_log(LogEntry::error(format!(
                "Failed to cleanup worktree after setup failure: {}",
                cleanup_err
            )));
        }
        return Ok(());
    }

    let command =
        OrchestratorConfig::expand_worktree_command(&template, worktree_path_str, repo_root_str);
    ctx.app.add_log(LogEntry::info(format!(
        "Running worktree command in {}",
        worktree_path_str
    )));

    execute_worktree_command(
        ctx.terminal,
        &command,
        &worktree_path,
        ctx.ai_runner,
        ctx.app,
    )
    .await
}

pub(crate) fn handle_warning_popup_key(app: &mut AppState, key: KeyEvent) -> bool {
    if app.warning_popup.is_none() {
        return false;
    }

    match key.code {
        KeyCode::Esc => {
            app.clear_warning_popup();
        }
        KeyCode::Up | KeyCode::Char('k') => {
            app.scroll_warning_popup(-1);
        }
        KeyCode::Down | KeyCode::Char('j') => {
            app.scroll_warning_popup(1);
        }
        KeyCode::PageUp => {
            app.scroll_warning_popup(-5);
        }
        KeyCode::PageDown => {
            app.scroll_warning_popup(5);
        }
        _ => {}
    }

    true
}

/// Handle main key events
///
/// Returns Some(TuiCommand) if the key event should trigger the configured start control
pub async fn handle_key_event(
    key: KeyEvent,
    ctx: &mut KeyEventContext<'_>,
) -> Result<Option<TuiCommand>> {
    let had_warning_message = ctx.app.warning_message.is_some();

    if handle_warning_popup_key(ctx.app, key) {
        ctx.app.warning_message = None;
        return Ok(None);
    }

    // Handle QrPopup mode - any key closes the popup
    if ctx.app.mode == AppMode::QrPopup {
        ctx.app.hide_qr_popup();
        return Ok(None);
    }

    // Handle force-kill confirmation mode
    if let AppMode::ConfirmForceKill { ref change_id } = ctx.app.mode {
        let cid = change_id.clone();
        match (key.code, key.modifiers) {
            (KeyCode::Char('y'), _) | (KeyCode::Char('Y'), _) => {
                ctx.app.mode = AppMode::Running;
                ctx.app
                    .add_log(LogEntry::info(format!("Force-kill confirmed: {}", cid)));
                let _ = ctx.cmd_tx.send(TuiCommand::DequeueChange(cid)).await;
            }
            (KeyCode::Char('n'), _) | (KeyCode::Char('N'), _) | (KeyCode::Esc, _) => {
                ctx.app.mode = AppMode::Running;
                ctx.app
                    .add_log(LogEntry::info("Force-kill canceled".to_string()));
            }
            _ => {}
        }
        return Ok(None);
    }

    // Handle worktree delete confirmation
    if ctx.app.mode == AppMode::ConfirmWorktreeDelete {
        match (key.code, key.modifiers) {
            (KeyCode::Char('y'), _) | (KeyCode::Char('Y'), _) => {
                if let Some(cmd) = ctx.app.confirm_worktree_action_delete() {
                    let _ = ctx.cmd_tx.send(cmd).await;
                }
            }
            (KeyCode::Char('n'), _) | (KeyCode::Char('N'), _) | (KeyCode::Esc, _) => {
                ctx.app.cancel_worktree_action();
            }
            (KeyCode::Char('s'), _) | (KeyCode::Char('S'), _) => {
                if let Some(cmd) = ctx.app.confirm_worktree_action_delete_with_options(true) {
                    let _ = ctx.cmd_tx.send(cmd).await;
                }
            }
            _ => {}
        }
        return Ok(None);
    }

    let mut cmd_to_start: Option<TuiCommand> = None;

    match (key.code, key.modifiers) {
        (KeyCode::Char('c'), KeyModifiers::CONTROL) => {
            request_local_tui_quit(ctx.app, ctx.orchestrator_cancel);
        }
        (KeyCode::Tab, _) => {
            handle_tab_key(ctx).await?;
        }
        (KeyCode::Up, _) | (KeyCode::Char('k'), _) => {
            handle_cursor_movement(ctx.app, true);
        }
        (KeyCode::Down, _) | (KeyCode::Char('j'), _) => {
            handle_cursor_movement(ctx.app, false);
        }
        (KeyCode::Char(' '), _) => {
            if let Some(cmd) = ctx.app.toggle_selection() {
                let _ = ctx.cmd_tx.send(cmd).await;
            }
        }
        (KeyCode::Char('x'), _) => {
            // Toggle all marks in Changes view.
            // Eligibility and mode constraints are enforced in AppState::toggle_all_marks.
            // In Running mode, queue commands (AddToQueue/RemoveFromQueue) are emitted
            // for eligible NotQueued/Queued rows, matching single-row Space semantics.
            use crate::tui::types::ViewMode;
            if ctx.app.view_mode == ViewMode::Changes {
                let commands = ctx.app.toggle_all_marks();
                for cmd in commands {
                    let _ = ctx.cmd_tx.send(cmd).await;
                }
            }
        }

        (KeyCode::Char('e'), _) => {
            handle_editor_launch(ctx).await?;
        }
        (KeyCode::Char('m'), _) | (KeyCode::Char('M'), _) => {
            handle_merge_key(ctx).await?;
        }
        (KeyCode::Char('d'), _) | (KeyCode::Char('D'), _) => {
            use crate::tui::types::ViewMode;
            if ctx.app.view_mode == ViewMode::Worktrees {
                // Worktree view: delete selected worktree
                ctx.app.request_worktree_delete_from_list();
            }
            // Note: D key removed from Changes view as per spec
        }
        (KeyCode::Esc, _) => {
            handle_esc_key(ctx);
        }
        _ if ctx.app.tui_config.matches_start_key(&key) => {
            cmd_to_start = handle_start_key(ctx);
        }
        (KeyCode::PageUp, _) => {
            // Scroll logs up (show older entries)
            ctx.app.scroll_logs_up(5);
        }
        (KeyCode::PageDown, _) => {
            // Scroll logs down (show newer entries)
            ctx.app.scroll_logs_down(5);
        }
        (KeyCode::Home, _) => {
            // Jump to oldest log entry
            ctx.app.scroll_logs_to_top();
        }
        (KeyCode::End, _) => {
            // Jump to newest log entry and re-enable auto-scroll
            ctx.app.scroll_logs_to_bottom();
        }
        (KeyCode::Char('='), _) => {
            // Toggle parallel mode (only if git is available)
            ctx.app.toggle_parallel_mode();
        }
        (KeyCode::Enter, _) => {
            handle_enter_key(ctx).await?;
        }
        (KeyCode::Char('+'), _) => {
            handle_plus_key(ctx).await?;
        }
        (KeyCode::Char('w'), _) if ctx.app.web_url.is_some() => {
            // Show QR code popup (only if web_url is set)
            ctx.app.show_qr_popup();
        }
        (KeyCode::Char('l'), _) => {
            // Toggle log panel visibility (only in Changes view)
            use crate::tui::types::ViewMode;
            if ctx.app.view_mode == ViewMode::Changes {
                ctx.app.toggle_logs_panel();
            }
        }
        (KeyCode::Char('K'), _) => {
            // Enter force-kill confirmation for active changes in Running mode
            use crate::tui::types::ViewMode;
            if ctx.app.view_mode == ViewMode::Changes
                && ctx.app.mode == AppMode::Running
                && !ctx.app.changes.is_empty()
                && ctx.app.cursor_index < ctx.app.changes.len()
            {
                let change = &ctx.app.changes[ctx.app.cursor_index];
                if matches!(
                    change.display_status_cache.as_str(),
                    "applying" | "accepting" | "archiving" | "resolving"
                ) {
                    let cid = change.id.clone();
                    ctx.app.mode = AppMode::ConfirmForceKill {
                        change_id: cid.clone(),
                    };
                    ctx.app.add_log(LogEntry::warn(format!(
                        "Confirm force-kill for '{}': press Y to confirm, N/Esc to cancel",
                        cid
                    )));
                }
            }
        }
        _ => {}
    }

    // Clear legacy one-line warning message on any key press.
    if had_warning_message {
        ctx.app.warning_message = None;
    }

    Ok(cmd_to_start)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::openspec::{Change, ProposalMetadata};
    use crate::tui::config::TuiConfig;
    use crossterm::event::KeyCode;

    fn create_test_change(id: &str) -> Change {
        Change {
            id: id.to_string(),
            completed_tasks: 0,
            total_tasks: 1,
            last_modified: "now".to_string(),
            dependencies: Vec::new(),
            metadata: ProposalMetadata::default(),
        }
    }

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn inert_stop_flag() -> Arc<AtomicBool> {
        Arc::new(AtomicBool::new(false))
    }

    #[test]
    fn log_navigation_state_methods_preserve_existing_key_semantics() {
        let mut app = AppState::new(vec![create_test_change("change-a")]);
        for index in 0..12 {
            app.add_log(LogEntry::info(format!("log {index}")));
        }
        assert_eq!(app.log_scroll_offset, 0);
        assert!(app.log_auto_scroll);

        app.scroll_logs_up(5);
        assert_eq!(app.log_scroll_offset, 5);
        assert!(!app.log_auto_scroll);

        app.scroll_logs_down(5);
        assert_eq!(app.log_scroll_offset, 0);
        assert!(app.log_auto_scroll);

        app.scroll_logs_to_top();
        assert_eq!(app.log_scroll_offset, 11);
        assert!(!app.log_auto_scroll);

        app.scroll_logs_to_bottom();
        assert_eq!(app.log_scroll_offset, 0);
        assert!(app.log_auto_scroll);

        assert!(app.logs_panel_enabled);
        app.toggle_logs_panel();
        assert!(!app.logs_panel_enabled);
        app.toggle_logs_panel();
        assert!(app.logs_panel_enabled);
    }

    #[test]
    fn configured_start_key_matches_default_and_custom_bindings() {
        let mut app = AppState::new(vec![create_test_change("run-me")]);
        app.changes[0].selected = true;

        assert!(app.tui_config.matches_start_key(&key(KeyCode::F(5))));
        assert!(app.tui_config.matches_start_key(&key(KeyCode::Char('!'))));

        let custom = TuiConfig::parse_jsonc(
            r#"{"keybindings":{"start":["F5","!"]}}"#,
            std::path::Path::new("/tmp/tui.jsonc"),
        )
        .unwrap();
        app.set_tui_config(custom);

        assert!(app.tui_config.matches_start_key(&key(KeyCode::F(5))));
        assert!(app.tui_config.matches_start_key(&key(KeyCode::Char('!'))));
        assert!(!app.tui_config.matches_start_key(&key(KeyCode::Char('x'))));
    }

    #[test]
    fn configured_start_key_triggers_same_command_as_f5() {
        let graceful_stop = inert_stop_flag();
        let handle = None;
        let custom = TuiConfig::parse_jsonc(
            r#"{"keybindings":{"start":["F5","!"]}}"#,
            std::path::Path::new("/tmp/tui.jsonc"),
        )
        .unwrap();

        let mut f5_app = AppState::new(vec![create_test_change("run-me")]);
        f5_app.set_tui_config(custom.clone());
        f5_app.changes[0].selected = true;
        let f5_command = if f5_app.tui_config.matches_start_key(&key(KeyCode::F(5))) {
            handle_start_key_inner(&mut f5_app, &graceful_stop, &handle)
        } else {
            None
        };

        let mut bang_app = AppState::new(vec![create_test_change("run-me")]);
        bang_app.set_tui_config(custom);
        bang_app.changes[0].selected = true;
        let bang_command = if bang_app
            .tui_config
            .matches_start_key(&key(KeyCode::Char('!')))
        {
            handle_start_key_inner(&mut bang_app, &graceful_stop, &handle)
        } else {
            None
        };

        assert_eq!(format!("{:?}", f5_command), format!("{:?}", bang_command));
        assert!(matches!(
            bang_command,
            Some(TuiCommand::StartProcessing(ids)) if ids == vec!["run-me".to_string()]
        ));
    }

    #[test]
    fn f5_on_merge_wait_row_does_not_emit_resolve_merge() {
        let mut app = AppState::new(vec![
            create_test_change("merge-wait"),
            create_test_change("run-me"),
        ]);
        app.mode = AppMode::Select;
        app.cursor_index = 0;
        app.changes[0].display_status_cache = "merge wait".to_string();
        app.changes[1].selected = true;
        let graceful_stop = inert_stop_flag();
        let handle = None;

        let command = handle_start_key_inner(&mut app, &graceful_stop, &handle);

        assert!(
            !matches!(command, Some(TuiCommand::ResolveMerge(_))),
            "F5 must not dispatch cursor-local ResolveMerge for MergeWait rows"
        );
        assert!(matches!(
            command,
            Some(TuiCommand::StartProcessing(ids)) if ids == vec!["run-me".to_string()]
        ));
        assert_eq!(app.changes[0].display_status_cache, "merge wait");
        assert_eq!(app.changes[1].display_status_cache, "queued");
    }

    #[test]
    fn f5_delegates_start_resume_and_retry_while_resolving() {
        let graceful_stop = inert_stop_flag();
        let handle = None;

        let mut select_app = AppState::new(vec![create_test_change("select-a")]);
        select_app.mode = AppMode::Select;
        select_app.is_resolving = true;
        select_app.changes[0].selected = true;
        let command = handle_start_key_inner(&mut select_app, &graceful_stop, &handle);
        assert!(matches!(
            command,
            Some(TuiCommand::StartProcessing(ids)) if ids == vec!["select-a".to_string()]
        ));
        assert!(select_app.warning_message.is_none());

        let mut stopped_app = AppState::new(vec![create_test_change("stopped-a")]);
        stopped_app.mode = AppMode::Stopped;
        stopped_app.is_resolving = true;
        stopped_app.changes[0].selected = true;
        let command = handle_start_key_inner(&mut stopped_app, &graceful_stop, &handle);
        assert!(matches!(
            command,
            Some(TuiCommand::StartProcessing(ids)) if ids == vec!["stopped-a".to_string()]
        ));
        assert!(stopped_app.warning_message.is_none());

        let mut errobang_app = AppState::new(vec![create_test_change("error-a")]);
        errobang_app.mode = AppMode::Error;
        errobang_app.is_resolving = true;
        errobang_app.changes[0].set_error_message_cache("boom".to_string());
        errobang_app.changes[0].selected = true;
        let shared = std::sync::Arc::new(tokio::sync::RwLock::new(
            crate::orchestration::state::OrchestratorState::new(vec!["error-a".to_string()], 0),
        ));
        shared.blocking_write().apply_execution_event(
            &crate::events::ExecutionEvent::ProcessingError {
                id: "error-a".to_string(),
                error: "boom".to_string(),
            },
        );
        errobang_app.set_shared_state(shared);
        let command = handle_start_key_inner(&mut errobang_app, &graceful_stop, &handle);
        assert!(matches!(
            command,
            Some(TuiCommand::StartProcessing(ids)) if ids == vec!["error-a".to_string()]
        ));
        assert!(errobang_app.warning_message.is_none());
    }

    #[test]
    fn f5_on_merge_wait_with_no_runnable_work_is_noop_not_resolve() {
        let mut app = AppState::new(vec![create_test_change("merge-wait")]);
        app.mode = AppMode::Select;
        app.cursor_index = 0;
        app.changes[0].display_status_cache = "merge wait".to_string();
        let graceful_stop = inert_stop_flag();
        let handle = None;

        let command = handle_start_key_inner(&mut app, &graceful_stop, &handle);

        assert!(command.is_none());
        assert_eq!(app.changes[0].display_status_cache, "merge wait");
        assert_eq!(app.warning_message.as_deref(), Some("No changes selected"));
    }

    #[test]
    fn warning_popup_scroll_keys_do_not_move_underlying_cursor_or_close_popup() {
        let mut app = AppState::new(vec![create_test_change("a"), create_test_change("b")]);
        app.show_warning_popup("warning", "line 1\nline 2\nline 3");
        let cursor_before = app.cursor_index;

        assert!(handle_warning_popup_key(&mut app, key(KeyCode::Down)));

        assert_eq!(app.cursor_index, cursor_before);
        assert_eq!(app.warning_popup_scroll, 1);
        assert!(app.warning_popup.is_some());
    }

    #[test]
    fn warning_popup_close_key_clears_popup_and_resets_scroll() {
        let mut app = AppState::new(vec![create_test_change("a")]);
        app.show_warning_popup("warning", "diagnostic");
        app.warning_popup_scroll = 7;

        assert!(handle_warning_popup_key(&mut app, key(KeyCode::Esc)));

        assert!(app.warning_popup.is_none());
        assert_eq!(app.warning_popup_scroll, 0);
    }

    #[test]
    fn warning_popup_ignores_non_popup_keys_without_underlying_action() {
        let mut app = AppState::new(vec![create_test_change("a"), create_test_change("b")]);
        app.show_warning_popup("warning", "diagnostic");
        let cursor_before = app.cursor_index;

        assert!(handle_warning_popup_key(&mut app, key(KeyCode::Char('x'))));

        assert_eq!(app.cursor_index, cursor_before);
        assert_eq!(app.warning_popup_scroll, 0);
        assert!(app.warning_popup.is_some());
    }
    #[test]
    fn ctrl_c_quit_cancels_local_orchestrator_token() {
        let mut app = AppState::new(vec![create_test_change("change-a")]);
        let token = CancellationToken::new();

        request_local_tui_quit(&mut app, &Some(token.clone()));

        assert!(app.should_quit);
        assert!(token.is_cancelled());
        assert!(app
            .logs
            .iter()
            .any(|entry| entry.message.contains("cancelling local orchestration")));
    }

    #[test]
    fn ctrl_c_quit_without_local_orchestrator_only_sets_quit() {
        let mut app = AppState::new(vec![create_test_change("change-a")]);

        request_local_tui_quit(&mut app, &None);

        assert!(app.should_quit);
    }
}