zagens-cli 0.8.3

Zagens headless CLI + HTTP/SSE runtime sidecar (`zagens`, `zagens-runtime` binaries)
Documentation
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
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
//! Full-screen terminal UI (`zagens-tui`).

mod activity_strip;
mod api_key_cmd;
mod app;
mod approval_policy;
mod automation;
mod composer_editor;
mod composer_paste;
mod composer_paste_batch;
mod composer_paste_guard;
mod composer_slash;
mod display_format;
mod draw;
mod focus;
mod harness;
mod i18n;
mod inline_markdown;
mod input_thread;
pub(crate) mod inspector;
mod layout;
mod left_rail;
mod lht_mode;
mod locale_cmd;
mod markdown_table;
mod mcp_cmd;
mod onboarding;
mod overlay;
mod pending_input;
mod poll;
mod runtime_events;
mod session_host;
mod stderr_log;
mod submit_disposition;
mod task_graph;
mod terminal;
mod theme;
mod transcript;
mod transcript_filter;
mod transcript_history;
mod transcript_turn;

use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail};
use crossterm::event::{Event, KeyCode, KeyModifiers, MouseEventKind};

use self::app::AppState;
use self::app::ComposerEnterAction;
use self::composer_slash::SlashAction;
use self::focus::FocusRegion;
use self::input_thread::TerminalInput;
use self::layout::{InspectorTab, TuiLayoutPrefs};
use self::onboarding::{
    OnboardingPlan, handle_onboarding_key, onboarding_paste, should_show_onboarding,
};
use self::overlay::OnboardingUiState;
use self::session_host::TuiSessionHost;
use self::submit_disposition::{SubmitDisposition, decide as decide_submit_disposition};
use self::terminal::{TuiTerminal, enter_inserts_newline, is_ctrl_c, is_key_press};
use crate::cli::args::Cli;
use crate::cli::context::load_cli_context;
use crate::localization::{MessageId, tr};

/// Entry point for the `zagens-tui` binary.
pub async fn run_tui(cli: Cli) -> Result<()> {
    if cli.command.is_some() {
        bail!(
            "zagens-tui does not run CLI subcommands; use `zagens` for exec/serve/doctor, or run `zagens-tui` without a subcommand"
        );
    }

    let _ = crate::config::ensure_config_file_exists(cli.config.clone())
        .context("create default ~/.zagens/config.toml")?;
    let mut ctx = load_cli_context(&cli)?;
    let show_onboarding = should_show_onboarding(&cli, &ctx.config);
    let onboarding_plan = OnboardingPlan::build(&ctx.config);
    let mut host = TuiSessionHost::open(&mut ctx, &cli).await?;
    let resumed = cli.resume.is_some() || cli.continue_session || !cli.fresh;
    let initial_prompt = if show_onboarding {
        None
    } else {
        cli.prompt.clone()
    };

    let inline_mode = cli.no_alt_screen;
    let mouse_capture = resolve_mouse_capture(&cli);
    let mut app = AppState::new(TuiLayoutPrefs::load(), inline_mode, &host).await;
    if show_onboarding {
        app.show_onboarding = true;
        app.onboarding = OnboardingUiState::new(onboarding_plan.phases);
    }
    if resumed {
        app.seed_resume_banner();
    }
    app.schedule_next_poll();

    let mut tui = TuiTerminal::new(inline_mode, mouse_capture)?;
    terminal::sync_terminal_geometry(&mut tui.terminal, &mut app.layout)?;
    app.terminal_resized = true;
    let mut boot_paints_remaining = 1u8;
    let mut input = TerminalInput::spawn();
    let mut ctrl_c_streak = 0u8;
    let mut ctrl_c_last: Option<Instant> = None;
    let mut dirty = true;
    let mut anim_tick = tokio::time::interval(Duration::from_millis(120));
    anim_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
    let mut poll_wake = tokio::time::interval(Duration::from_secs(5));
    poll_wake.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
    poll_wake.reset();

    // Channel for RunShell automation actions: output arrives here from background
    // threads and is drained in the biased select! branch without blocking the loop.
    let (shell_tx, mut shell_rx) = tokio::sync::mpsc::unbounded_channel::<String>();

    // Fire SessionStart rules after TUI is up so push_system_line() is visible.
    if !resumed {
        let fired = app.automation_engine.notify_session_start();
        let ctx = automation::EventContext {
            session_id: host.thread_id().to_string(),
            ..Default::default()
        };
        for result in fired {
            for action in result.actions {
                fire_automation_action(&host, &mut app, action, &ctx, &shell_tx).await;
            }
        }
        dirty = true;
    }

    if let Some(prompt) = initial_prompt.filter(|p| !p.trim().is_empty()) {
        submit_prompt(&host, &mut app, &prompt).await;
        dirty = true;
    }

    loop {
        if dirty {
            if app.terminal_resized || boot_paints_remaining > 0 {
                tui.terminal.clear()?;
                app.terminal_resized = false;
            }
            tui.terminal.draw(|frame| {
                let area = frame.area();
                app.layout.last_terminal_width = area.width;
                app.layout.apply_auto_collapse(area.width);
                let regions = app.layout.regions(area);
                app.right_panel_height = regions.right.height.saturating_sub(2) as usize;
                let split = app
                    .layout
                    .split_right_pane(regions.right, app.lht_pane_visible());
                app.right_inspector_height = split.inspector.height.saturating_sub(2) as usize;
                app.right_lht_height = if split.lht_visible {
                    split.lht.height.saturating_sub(2) as usize
                } else {
                    0
                };
                draw::draw(frame, &mut app, &regions, &split);
            })?;
            if boot_paints_remaining > 0 {
                boot_paints_remaining -= 1;
                if boot_paints_remaining > 0 {
                    app.terminal_resized = true;
                }
                dirty = true;
                continue;
            }
            dirty = false;
        }

        // `biased;` guarantees branches are polled in declaration order.
        // Input is first — this ensures keyboard events (Tab, Esc, …) are processed
        // immediately even when the model is streaming heavily.
        tokio::select! {
            biased;

            // 1. Keyboard / mouse input — highest priority.
            maybe_event = input.recv() => {
                if let Some(event) = maybe_event {
                    let mut batch = vec![event];
                    while let Some(extra) = input.try_recv() {
                        batch.push(extra);
                    }
                    let mut quit = false;
                    if let Some(paste) = composer_paste_batch::try_coalesce_terminal_paste(&batch) {
                        if app.show_onboarding {
                            onboarding_paste(&mut app, &paste);
                        } else if app.layout.focus == FocusRegion::Chat {
                            if !app.composer_focus {
                                app.composer_focus = true;
                            }
                            app.handle_composer_paste(&paste);
                        }
                    } else {
                        for event in batch {
                            if handle_input_event(
                                &event,
                                &mut ctx,
                                &mut host,
                                &mut app,
                                &mut ctrl_c_streak,
                                &mut ctrl_c_last,
                                &shell_tx,
                            ).await? {
                                quit = true;
                                break;
                            }
                        }
                    }
                    if quit {
                        break;
                    }
                    dirty = true;
                }
            }
            // 2. RunShell output arriving from background tasks.
            Some(msg) = shell_rx.recv() => {
                app.push_system_line(msg);
                dirty = true;
            }
            // 3. Streaming / runtime events.
            delta = host.recv_runtime_ui_delta() => {
                let was_streaming = app.transcript.streaming;
                let had_events = !delta.events.is_empty();
                let had_checklist = delta.checklist.is_some() || delta.task_graph.is_some();
                let mut hook_results: Vec<automation::FiredResult> = Vec::new();
                for event in delta.events {
                    hook_results.extend(app.automation_engine.check_engine_event(&event));
                    app.apply_engine_event(event);
                }
                let session_id = app.thread_id.clone();
                for mut fired in hook_results {
                    fired.ctx.session_id = session_id.clone();
                    for action in fired.actions {
                        fire_automation_action(&host, &mut app, action, &fired.ctx, &shell_tx).await;
                    }
                }
                if let Some(graph) = delta.task_graph {
                    app.apply_task_graph_snapshot(graph);
                } else if let Some(checklist) = delta.checklist {
                    app.merge_checklist_snapshot(checklist);
                }
                if was_streaming && !app.transcript.streaming {
                    app.refresh_workspace_inspector(&host);
                    drain_prompt_queue(&host, &mut app).await;
                }
                let poll_ran = app.poll_due();
                if poll_ran {
                    app.refresh_panels(&host).await;
                    app.refresh_sessions(&host).await;
                }
                if had_events
                    || had_checklist
                    || was_streaming != app.transcript.streaming
                    || poll_ran
                {
                    dirty = true;
                }
                // After processing a potentially large delta batch (e.g. thinking tokens),
                // drain all buffered keyboard events so the user never experiences a
                // noticeable input delay even when thinking produces large token batches.
                let mut drain_quit = false;
                while let Some(event) = input.try_recv() {
                    match handle_input_event(
                        &event,
                        &mut ctx,
                        &mut host,
                        &mut app,
                        &mut ctrl_c_streak,
                        &mut ctrl_c_last,
                        &shell_tx,
                    )
                    .await
                    {
                        Ok(true) => {
                            drain_quit = true;
                            break;
                        }
                        Ok(false) => {
                            dirty = true;
                        }
                        Err(e) => return Err(e),
                    }
                }
                if drain_quit { break; }
            }
            // 4. Animation tick (streaming indicator / cursor blink).
            _ = anim_tick.tick(), if app.transcript.is_live_activity() || app.composer_shows_cursor() => {
                dirty = true;
            }
            // 5. Background poll (sessions / panels refresh).
            _ = poll_wake.tick() => {
                if app.poll_due() {
                    app.refresh_panels(&host).await;
                    app.refresh_sessions(&host).await;
                    dirty = true;
                }
            }
            // 6. Automation timer triggers — lowest priority.
            _ = tokio::time::sleep_until(app.automation_engine.next_wake_tokio()) => {
                let fired = app.automation_engine.poll_due();
                if !fired.is_empty() {
                    let session_id = app.thread_id.clone();
                    for mut result in fired {
                        result.ctx.session_id = session_id.clone();
                        for action in result.actions {
                            fire_automation_action(&host, &mut app, action, &result.ctx, &shell_tx).await;
                        }
                    }
                    dirty = true;
                }
            }
        }

        // ── Editor request ─────────────────────────────────────────────────
        // Pause the TUI, open $EDITOR / notepad, reload config, then resume.
        if let Some(path) = app.editor_request.take() {
            tui.shutdown()?;
            match open_in_editor(&path) {
                Ok(()) => {}
                Err(err) => {
                    eprintln!("[automation] editor error: {err}");
                }
            }
            let new_config = automation::AutomationConfig::load();
            app.automation_engine.update_config(new_config);
            tui = TuiTerminal::new(inline_mode, mouse_capture)?;
            terminal::sync_terminal_geometry(&mut tui.terminal, &mut app.layout)?;
            app.terminal_resized = true;
            dirty = true;
            app.push_system_line("automation: config reloaded from disk".to_string());
        }
    }

    app.layout.prefs.last_thread_id = Some(host.thread_id().to_string());
    app.layout.prefs.save().ok();
    tui.shutdown()?;
    Ok(())
}

async fn handle_input_event(
    event: &Event,
    ctx: &mut crate::cli::context::CliContext,
    host: &mut TuiSessionHost,
    app: &mut AppState,
    ctrl_c_streak: &mut u8,
    ctrl_c_last: &mut Option<Instant>,
    shell_tx: &tokio::sync::mpsc::UnboundedSender<String>,
) -> Result<bool> {
    match event {
        Event::Resize(width, _) => {
            app.layout.last_terminal_width = *width;
            app.layout.apply_auto_collapse(*width);
            app.terminal_resized = true;
        }
        Event::Paste(text) => {
            if app.show_onboarding {
                onboarding_paste(app, text);
                return Ok(false);
            }
            if app.show_mcp {
                mcp_cmd::mcp_paste(app, text);
                return Ok(false);
            }
            if app.layout.focus == FocusRegion::Chat {
                if !app.composer_focus {
                    app.composer_focus = true;
                }
                app.handle_composer_paste(text);
            }
        }
        Event::Mouse(mouse) => match mouse.kind {
            MouseEventKind::ScrollUp => handle_mouse_scroll(app, mouse.column, 3, true),
            MouseEventKind::ScrollDown => handle_mouse_scroll(app, mouse.column, 3, false),
            _ => {}
        },
        Event::Key(key) => {
            if !is_key_press(key) {
                return Ok(false);
            }
            // Keep idle-trigger timers fresh on every keystroke.
            app.automation_engine.notify_activity();
            if app.show_help && key.code == KeyCode::Char('?') {
                app.show_help = false;
                return Ok(false);
            }
            if app.show_help {
                app.show_help = false;
                return Ok(false);
            }

            // Onboarding overlay — intercept all keys while open.
            if app.show_onboarding {
                return handle_onboarding_key(*key, ctx, host, app).await;
            }

            // Automation overlay — intercept all keys while open.
            if app.show_automation {
                return handle_automation_key(*key, host, app).await;
            }

            // MCP config overlay — intercept all keys while open.
            if app.show_mcp {
                return mcp_cmd::handle_mcp_key(*key, host, app).await;
            }

            if let Some(pending) = app.pending_approval.clone() {
                return handle_approval_key(*key, host, app, &pending).await;
            }

            if key.code == KeyCode::Char('q') && key.modifiers.contains(KeyModifiers::CONTROL) {
                return Ok(true);
            }
            if is_ctrl_c(event) {
                let now = Instant::now();
                if ctrl_c_last.is_some_and(|t| now.duration_since(t) > Duration::from_millis(1500))
                {
                    *ctrl_c_streak = 0;
                }
                *ctrl_c_streak = ctrl_c_streak.saturating_add(1);
                *ctrl_c_last = Some(now);
                if *ctrl_c_streak >= 2 {
                    return Ok(true);
                }
                host.interrupt_turn().await?;
                app.transcript.close_open_turn();
                app.blocked_line = None;
                return Ok(false);
            }
            *ctrl_c_streak = 0;
            *ctrl_c_last = None;

            match key.code {
                KeyCode::Char('?') if composer_absorbs_text_keys(app) => {
                    app.handle_char('?');
                }
                KeyCode::Char('?') => {
                    app.show_help = !app.show_help;
                }
                KeyCode::Tab | KeyCode::BackTab if !app.approval_open() => {
                    if app.composer_paste_guard.paste_active() {
                        // Swallow Tab during multiline paste bursts (Windows conhost).
                    } else {
                        let shift = matches!(key.code, KeyCode::BackTab)
                            || key.modifiers.contains(KeyModifiers::SHIFT);
                        handle_tab_focus(app, shift);
                    }
                }
                KeyCode::Char('[') if composer_absorbs_text_keys(app) => {
                    app.handle_char('[');
                }
                KeyCode::Char('[') => app.layout.toggle_left(),
                KeyCode::Char(']') if composer_absorbs_text_keys(app) => {
                    app.handle_char(']');
                }
                KeyCode::Char(']') => app.layout.toggle_right(),
                KeyCode::Char('n')
                    if key.modifiers.contains(KeyModifiers::CONTROL)
                        && app.layout.focus == FocusRegion::Left =>
                {
                    host.new_session(ctx).await?;
                    app.reload_after_thread_switch(host).await;
                }
                KeyCode::Char('j')
                    if app.layout.focus == FocusRegion::Chat && composer_absorbs_text_keys(app) =>
                {
                    app.handle_char('j');
                }
                KeyCode::Char('k')
                    if app.layout.focus == FocusRegion::Chat && composer_absorbs_text_keys(app) =>
                {
                    app.handle_char('k');
                }
                KeyCode::Char('j') => {
                    enter_transcript_scroll_if_needed(app);
                    handle_j(app);
                }
                KeyCode::Char('k') => {
                    enter_transcript_scroll_if_needed(app);
                    handle_k(app);
                }
                KeyCode::Char('o')
                    if app.layout.focus == FocusRegion::Chat && !app.composer_focus =>
                {
                    if let Some(src) = app.transcript.last_mermaid_src() {
                        if let Some(url) = mermaid_live_url(src) {
                            let _ = open_url(&url);
                        }
                    } else if app.transcript.last_turn_has_harness() {
                        app.transcript.toggle_last_turn_harness();
                    } else {
                        app.transcript.toggle_last_turn_tools();
                    }
                }
                KeyCode::Char(n @ '1'..='5')
                    if app.layout.focus == FocusRegion::Left
                        || app.layout.focus == FocusRegion::Right =>
                {
                    if let Some(tab) = InspectorTab::from_index(n as u8 - b'0') {
                        app.switch_inspector_tab(tab);
                        app.focus_inspector_upper();
                    }
                }
                KeyCode::Char('l') if app.layout.focus == FocusRegion::Right => {
                    app.toggle_lht_pane();
                }
                KeyCode::Char('i') if app.layout.focus == FocusRegion::Right => {
                    app.focus_inspector_upper();
                }
                KeyCode::Enter if app.layout.focus == FocusRegion::Right => {
                    app.inspector_activate(&host.thread.workspace);
                }
                KeyCode::Esc if app.layout.focus == FocusRegion::Right => {
                    if app.inspector_ui.in_detail_view() || app.inspector_ui.mcp_expanded.is_some()
                    {
                        app.inspector_back();
                    }
                }
                KeyCode::Char('s')
                    if app.layout.focus == FocusRegion::Right
                        && app.layout.prefs.inspector_tab() == InspectorTab::Diff =>
                {
                    app.toggle_diff_staged(&host.thread.workspace);
                }
                KeyCode::Char('-') | KeyCode::Char('_')
                    if app.layout.focus == FocusRegion::Right =>
                {
                    app.layout.adjust_right_width(-2);
                }
                KeyCode::Char('=') | KeyCode::Char('+')
                    if app.layout.focus == FocusRegion::Right =>
                {
                    app.layout.adjust_right_width(2);
                }
                KeyCode::Esc if app.layout.focus == FocusRegion::Chat => {
                    if app.composer_focus && app.slash.open {
                        // Restore theme if the /theme picker was open in preview mode.
                        if let Some(original) = app.theme_picker_original.take() {
                            theme::install(theme::TuiTheme::resolve(original));
                        }
                        app.composer.clear();
                        app.slash.close();
                    } else {
                        app.composer_focus = !app.composer_focus;
                    }
                }
                KeyCode::Enter if app.layout.focus == FocusRegion::Left => {
                    if let Some(id) = app.sessions.selected_id()
                        && id != app.thread_id
                    {
                        host.switch_thread(id).await?;
                        app.reload_after_thread_switch(host).await;
                    }
                }
                KeyCode::Enter if app.layout.focus == FocusRegion::Chat => {
                    let force_steer = key.modifiers.contains(KeyModifiers::CONTROL)
                        && !key.modifiers.contains(KeyModifiers::SHIFT);
                    let newline = enter_inserts_newline(key) && !force_steer;
                    if app.composer_focus {
                        match app.handle_composer_enter(newline) {
                            ComposerEnterAction::Slash => {
                                if handle_slash_enter(ctx, host, app, shell_tx).await? {
                                    return Ok(false);
                                }
                            }
                            ComposerEnterAction::Send => {
                                if let Some(prompt) = app.take_composer_prompt() {
                                    submit_user_input(host, app, &prompt, force_steer).await;
                                }
                            }
                            ComposerEnterAction::Newline | ComposerEnterAction::None => {}
                        }
                    } else if newline {
                        app.focus_composer_newline();
                    } else {
                        app.transcript.toggle_last_turn_detail();
                    }
                }
                KeyCode::Left if app.layout.focus == FocusRegion::Chat && app.composer_focus => {
                    if key.modifiers.contains(KeyModifiers::CONTROL) {
                        app.composer.move_word_left();
                    } else {
                        app.composer.move_left();
                    }
                }
                KeyCode::Right if app.layout.focus == FocusRegion::Chat && app.composer_focus => {
                    app.composer.move_right();
                }
                KeyCode::Home if app.layout.focus == FocusRegion::Chat && app.composer_focus => {
                    app.composer.move_home();
                }
                KeyCode::End if app.layout.focus == FocusRegion::Chat && app.composer_focus => {
                    app.composer.move_end();
                }
                KeyCode::Char('w')
                    if key.modifiers.contains(KeyModifiers::CONTROL)
                        && app.layout.focus == FocusRegion::Chat
                        && app.composer_focus =>
                {
                    app.composer.delete_word_backward();
                    app.sync_slash_palette();
                }
                KeyCode::Char('u')
                    if key.modifiers.contains(KeyModifiers::CONTROL)
                        && app.layout.focus == FocusRegion::Chat
                        && app.composer_focus =>
                {
                    app.composer.delete_to_start();
                    app.sync_slash_palette();
                }
                KeyCode::Up
                    if app.layout.focus == FocusRegion::Chat
                        && app.composer_focus
                        && app.slash.open =>
                {
                    app.slash.move_up(app.composer.text(), &app.model_catalog);
                    preview_theme_selection(app);
                }
                KeyCode::Down
                    if app.layout.focus == FocusRegion::Chat
                        && app.composer_focus
                        && app.slash.open =>
                {
                    app.slash.move_down(app.composer.text(), &app.model_catalog);
                    preview_theme_selection(app);
                }
                KeyCode::Up
                    if app.layout.focus == FocusRegion::Chat
                        && app.composer_focus
                        && !app.slash.open =>
                {
                    // Multi-line: move cursor up within text; fall back to history at first line.
                    if !app.composer.move_up_line() {
                        if app.composer.is_empty()
                            && app.transcript.is_live_activity()
                            && app.pull_last_queued_into_composer()
                        {
                            // ↑ pulled last queued follow-up into composer
                        } else {
                            app.prompt_history.browse_up(&mut app.composer);
                        }
                        app.sync_slash_palette();
                    }
                }
                KeyCode::Down
                    if app.layout.focus == FocusRegion::Chat
                        && app.composer_focus
                        && !app.slash.open =>
                {
                    // Multi-line: move cursor down within text; fall back to history at last line.
                    if !app.composer.move_down_line() {
                        app.prompt_history.browse_down(&mut app.composer);
                        app.sync_slash_palette();
                    }
                }
                KeyCode::Up if app.layout.focus == FocusRegion::Chat => {
                    enter_transcript_scroll_if_needed(app);
                    app.transcript.scroll_up(1);
                }
                KeyCode::Down if app.layout.focus == FocusRegion::Chat => {
                    enter_transcript_scroll_if_needed(app);
                    app.transcript.scroll_down(1);
                }
                KeyCode::PageUp if app.layout.focus == FocusRegion::Chat => {
                    enter_transcript_scroll_if_needed(app);
                    app.transcript.scroll_up(5);
                }
                KeyCode::PageDown if app.layout.focus == FocusRegion::Chat => {
                    enter_transcript_scroll_if_needed(app);
                    app.transcript.scroll_down(5);
                }
                KeyCode::Char('a')
                    if key.modifiers.contains(KeyModifiers::CONTROL)
                        && app.layout.focus == FocusRegion::Chat
                        && app.approval_toggle_enabled =>
                {
                    host.cycle_approval_policy().await?;
                    app.sync_thread_meta(host);
                }
                KeyCode::Char('v') | KeyCode::Char('V')
                    if key.modifiers.contains(KeyModifiers::CONTROL)
                        && app.layout.focus == FocusRegion::Chat
                        && app.composer_focus =>
                {
                    app.paste_from_clipboard();
                }
                KeyCode::Insert
                    if key.modifiers.contains(KeyModifiers::SHIFT)
                        && app.layout.focus == FocusRegion::Chat
                        && app.composer_focus =>
                {
                    app.paste_from_clipboard();
                }
                KeyCode::Backspace => app.handle_backspace(),
                KeyCode::Delete if app.layout.focus == FocusRegion::Chat && app.composer_focus => {
                    app.composer.delete_forward();
                    app.sync_slash_palette();
                }
                KeyCode::Char(ch) => {
                    maybe_focus_composer_for_input(app, ch);
                    if app.composer_paste_guard.paste_active()
                        && app.layout.focus == FocusRegion::Chat
                    {
                        app.composer_focus = true;
                    }
                    app.handle_char(ch);
                }
                _ => {}
            }
        }
        _ => {}
    }
    Ok(false)
}

fn composer_absorbs_text_keys(app: &AppState) -> bool {
    (app.layout.focus == FocusRegion::Chat && app.composer_focus)
        || app.composer_paste_guard.paste_active()
}

/// During live activity, restore composer edit mode when the user starts typing.
fn maybe_focus_composer_for_input(app: &mut AppState, ch: char) {
    if app.layout.focus != FocusRegion::Chat || app.composer_focus {
        return;
    }
    if app.transcript.is_live_activity() && !ch.is_control() {
        app.composer_focus = true;
    }
}

fn enter_transcript_scroll_if_needed(app: &mut AppState) {
    if app.layout.focus == FocusRegion::Chat && app.composer_focus {
        app.composer_focus = false;
    }
}

fn handle_tab_focus(app: &mut AppState, shift: bool) {
    let sidebars = app.layout.left_rail_available() || app.layout.right_rail_available();
    if app.layout.focus == FocusRegion::Chat {
        if !sidebars {
            app.composer_focus = !app.composer_focus;
            return;
        }
        if !shift && app.composer_focus {
            app.composer_focus = false;
            return;
        }
        if shift && !app.composer_focus {
            app.composer_focus = true;
            return;
        }
    }
    let prev_focus = app.layout.focus;
    app.layout.focus = if shift {
        app.layout.focus_prev_visible()
    } else {
        app.layout.focus_next_visible()
    };
    if app.layout.focus == FocusRegion::Right && prev_focus != FocusRegion::Right {
        app.focus_inspector_upper();
    }
    if app.layout.focus == FocusRegion::Chat {
        app.composer_focus = !shift;
    }
}

fn handle_j(app: &mut AppState) {
    match app.layout.focus {
        FocusRegion::Left => app.sessions.move_down(),
        FocusRegion::Chat if !app.composer_focus => app.transcript.scroll_up(1),
        FocusRegion::Right => {
            let ws = app.workspace.clone();
            app.right_rail_scroll_down(&ws);
        }
        _ => {}
    }
}

fn handle_k(app: &mut AppState) {
    match app.layout.focus {
        FocusRegion::Left => app.sessions.move_up(),
        FocusRegion::Chat if !app.composer_focus => app.transcript.scroll_down(1),
        FocusRegion::Right => {
            let ws = app.workspace.clone();
            app.right_rail_scroll_up(&ws);
        }
        _ => {}
    }
}

/// Route a mouse-wheel scroll to whichever pane contains column `x`.
/// `up=true` means wheel-up (scroll toward older/top content).
/// `lines` is how many lines to scroll per tick.
fn handle_mouse_scroll(app: &mut AppState, x: u16, lines: usize, up: bool) {
    let total = app.layout.last_terminal_width;
    let left_w = app.layout.left_width();
    let right_w = app.layout.right_width();

    if left_w > 0 && x < left_w {
        // Left rail — session list: 1 session per tick to avoid skipping entries.
        if up {
            app.sessions.move_up();
        } else {
            app.sessions.move_down();
        }
    } else if right_w > 0 && x + right_w >= total {
        // Right rail — file tree / inspector: 1 line per tick so sub-directory
        // items don't jump when the tree is expanded.
        let ws = app.workspace.clone();
        if up {
            app.right_rail_scroll_up(&ws);
        } else {
            app.right_rail_scroll_down(&ws);
        }
    } else {
        // Center column — transcript: 3 lines per tick for comfortable reading.
        if up {
            app.transcript.scroll_up(lines);
        } else {
            app.transcript.scroll_down(lines);
        }
    }
}

async fn handle_approval_key(
    key: crossterm::event::KeyEvent,
    host: &mut TuiSessionHost,
    app: &mut AppState,
    pending: &overlay::PendingApproval,
) -> Result<bool> {
    match key.code {
        KeyCode::Char('y') | KeyCode::Enter => {
            host.approve_tool(&pending.id, false).await?;
            app.clear_approval();
        }
        KeyCode::Char('a') => {
            host.approve_tool(&pending.id, true).await?;
            app.clear_approval();
        }
        KeyCode::Char('v') => {
            if let Some(p) = app.pending_approval.as_mut() {
                p.show_detail = !p.show_detail;
            }
        }
        KeyCode::Char('n') | KeyCode::Esc => {
            host.deny_tool(&pending.id).await?;
            app.clear_approval();
        }
        _ => {}
    }
    Ok(false)
}

// ── Automation overlay key handler ─────────────────────────────────────────

async fn handle_automation_key(
    key: crossterm::event::KeyEvent,
    host: &mut TuiSessionHost,
    app: &mut AppState,
) -> Result<bool> {
    let _ = host;

    if app.automation_ui.edit_mode {
        // ── Edit mode ──────────────────────────────────────────────────────
        match key.code {
            KeyCode::Esc => {
                app.automation_ui.cancel_edit();
            }
            KeyCode::Enter => {
                save_automation_edit(app);
            }
            KeyCode::Tab => {
                app.automation_ui.next_field();
            }
            KeyCode::BackTab => {
                app.automation_ui.prev_field();
            }
            KeyCode::Left => {
                if !app.automation_ui.edit_field.is_text_input() {
                    app.automation_ui.cycle_selector(false);
                }
            }
            KeyCode::Right => {
                if !app.automation_ui.edit_field.is_text_input() {
                    app.automation_ui.cycle_selector(true);
                }
            }
            KeyCode::Up => {
                if !app.automation_ui.edit_field.is_text_input() {
                    app.automation_ui.cycle_selector(false);
                }
            }
            KeyCode::Down => {
                if !app.automation_ui.edit_field.is_text_input() {
                    app.automation_ui.cycle_selector(true);
                }
            }
            KeyCode::Backspace => {
                app.automation_ui.backspace();
            }
            KeyCode::Char(ch) => {
                app.automation_ui.input_char(ch);
            }
            _ => {}
        }
    } else {
        // ── List mode ──────────────────────────────────────────────────────
        let len = app.automation_engine.config.rules.len();
        match key.code {
            KeyCode::Esc => {
                app.show_automation = false;
            }
            KeyCode::Char('j') | KeyCode::Down => {
                app.automation_ui.move_down(len);
            }
            KeyCode::Char('k') | KeyCode::Up => {
                app.automation_ui.move_up();
            }
            KeyCode::Char(' ') => {
                toggle_automation_rule(app);
            }
            KeyCode::Char('n') => {
                app.automation_ui.start_new();
            }
            KeyCode::Enter => {
                let idx = app.automation_ui.list_selected;
                if let Some(rule) = app.automation_engine.config.rules.get(idx) {
                    let rule = rule.clone();
                    app.automation_ui.start_edit(&rule);
                }
            }
            KeyCode::Char('d') | KeyCode::Delete => {
                delete_automation_rule(app);
            }
            // Open the TOML config file in $EDITOR / notepad.
            KeyCode::Char('e') => {
                if let Some(path) = automation::AutomationConfig::path() {
                    // Ensure the file exists before opening.
                    if !path.exists() {
                        let _ = automation::AutomationConfig::default().save();
                    }
                    app.editor_request = Some(path);
                    app.show_automation = false;
                } else {
                    app.push_system_line("automation: could not resolve config path".to_string());
                }
            }
            _ => {}
        }
    }
    Ok(false)
}

fn save_automation_edit(app: &mut AppState) {
    let editing_id = app.automation_ui.editing_id;
    let built_rule_for_new;
    let built_rule_for_update;

    if let Some(id) = editing_id {
        built_rule_for_update = app.automation_ui.build_rule(id);
        built_rule_for_new = None;
    } else {
        let id = app.automation_engine.config.alloc_id();
        built_rule_for_new = app.automation_ui.build_rule(id);
        built_rule_for_update = None;
    }

    if let Some(id) = editing_id {
        if let Some(rule) = built_rule_for_update
            && let Some(existing) = app
                .automation_engine
                .config
                .rules
                .iter_mut()
                .find(|r| r.id == id)
        {
            existing.name = rule.name;
            existing.trigger = rule.trigger;
            // Preserve extra actions the user may have added via direct TOML
            // editing; only overwrite the first (primary) action.
            if !rule.actions.is_empty() {
                if existing.actions.is_empty() {
                    existing.actions = rule.actions;
                } else {
                    existing.actions[0] = rule.actions.into_iter().next().unwrap();
                }
            }
        }
    } else if let Some(rule) = built_rule_for_new {
        app.automation_engine.config.rules.push(rule);
    }

    app.automation_engine.save();
    app.automation_engine
        .reset_timers(std::time::Instant::now());
    app.automation_ui.edit_mode = false;
    let len = app.automation_engine.config.rules.len();
    app.automation_ui.clamp_selection(len);
}

fn toggle_automation_rule(app: &mut AppState) {
    let idx = app.automation_ui.list_selected;
    if let Some(rule) = app.automation_engine.config.rules.get_mut(idx) {
        rule.enabled = !rule.enabled;
    }
    app.automation_engine.save();
    app.automation_engine
        .reset_timers(std::time::Instant::now());
}

fn delete_automation_rule(app: &mut AppState) {
    let idx = app.automation_ui.list_selected;
    if idx < app.automation_engine.config.rules.len() {
        app.automation_engine.config.rules.remove(idx);
    }
    app.automation_engine.save();
    app.automation_engine
        .reset_timers(std::time::Instant::now());
    let len = app.automation_engine.config.rules.len();
    app.automation_ui.clamp_selection(len);
}

/// Fire a single automation action with an optional event context for template substitution.
async fn fire_automation_action(
    host: &TuiSessionHost,
    app: &mut AppState,
    action: automation::ActionKind,
    ctx: &automation::EventContext,
    shell_tx: &tokio::sync::mpsc::UnboundedSender<String>,
) {
    match action {
        automation::ActionKind::SendPrompt { text } => {
            let resolved = ctx.apply(&text);
            submit_prompt(host, app, &resolved).await;
        }
        automation::ActionKind::SlashRun { cmd } => {
            let resolved = ctx.apply(&cmd);
            let with_slash = if resolved.starts_with('/') {
                resolved.clone()
            } else {
                format!("/{resolved}")
            };
            let ws = app.workspace.clone();
            if let Some(slash_action) = composer_slash::try_parse_action(&with_slash, &ws) {
                app.push_system_line(format!("[auto] {with_slash}"));
                let _ = execute_slash_noop(app, slash_action);
            } else {
                app.push_system_line(format!("[auto] slash '{with_slash}' — not dispatched (needs host context, use SendPrompt instead)"));
            }
        }
        automation::ActionKind::RunShell { cmd } => {
            let resolved = ctx.apply(&cmd);
            app.push_system_line(format!("[auto] $ {resolved}"));
            // Fire-and-forget: run in a thread-pool thread, send output back
            // via the shell_tx channel without blocking the TUI event loop.
            let tool_name_s = ctx.tool_name.clone().unwrap_or_default();
            let session_id_s = ctx.session_id.clone();
            let error_msg_s = ctx.error_message.clone().unwrap_or_default();
            let tx = shell_tx.clone();
            tokio::task::spawn_blocking(move || {
                match run_shell_cmd_sync(&resolved, &tool_name_s, &session_id_s, &error_msg_s) {
                    Ok(out) if !out.is_empty() => {
                        let _ = tx.send(format!("[auto output] {out}"));
                    }
                    Err(err) => {
                        let _ = tx.send(format!("[auto error] {err}"));
                    }
                    _ => {}
                }
            });
            // Note: we do NOT await the handle — the task runs in the background.
        }
        automation::ActionKind::Notify { message } => {
            let resolved = ctx.apply(&message);
            app.push_system_line(format!("[notify] {resolved}"));
        }
    }
}

/// Dispatch slash actions that do not require live `host`/`ctx` access.
/// Returns `true` if the action was handled, `false` if it needs host context.
fn execute_slash_noop(app: &mut AppState, action: SlashAction) -> bool {
    match action {
        SlashAction::ShowHelp => {
            app.show_help = true;
            true
        }
        SlashAction::ShowAutomation => {
            app.show_automation = true;
            app.automation_ui.edit_mode = false;
            let len = app.automation_engine.config.rules.len();
            app.automation_ui.clamp_selection(len);
            true
        }
        SlashAction::ShowMcp => false,
        SlashAction::SwitchTheme(id) => {
            apply_theme_change(app, id);
            true
        }
        SlashAction::CycleTheme => {
            let next = theme::current_id().cycle();
            apply_theme_change(app, next);
            true
        }
        SlashAction::SetLhtMode(mode) => {
            apply_lht_mode_change(app, mode);
            true
        }
        SlashAction::CycleLhtMode => {
            let next = lht_mode::load_lht_composer_mode().cycle();
            apply_lht_mode_change(app, next);
            true
        }
        SlashAction::ClearComposer => {
            app.composer.clear();
            true
        }
        // These need host context — caller should use SendPrompt or RunShell instead.
        SlashAction::NewSession
        | SlashAction::SwitchModel(_)
        | SlashAction::SwitchWorkspace(_)
        | SlashAction::SetLocale(_)
        | SlashAction::CycleLocale
        | SlashAction::SaveApiKey(_)
        | SlashAction::ClearApiKey
        | SlashAction::ShowApiKeyUsage
        | SlashAction::SetApprovalPolicy(_)
        | SlashAction::CycleApprovalPolicy => false,
    }
}

/// Spawn a shell command in a blocking context and return trimmed output (≤ 500 chars).
/// Has an implicit OS timeout via the process itself; callers should wrap in
/// `tokio::task::spawn_blocking` + `tokio::time::timeout` for hard bounds.
fn run_shell_cmd_sync(
    cmd: &str,
    tool_name: &str,
    session_id: &str,
    error_msg: &str,
) -> std::io::Result<String> {
    #[cfg(target_os = "windows")]
    let child = std::process::Command::new("cmd")
        .args(["/c", cmd])
        .env("ZAGENS_TOOL_NAME", tool_name)
        .env("ZAGENS_SESSION_ID", session_id)
        .env("ZAGENS_ERROR_MSG", error_msg)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()?;

    #[cfg(not(target_os = "windows"))]
    let child = std::process::Command::new("sh")
        .args(["-c", cmd])
        .env("ZAGENS_TOOL_NAME", tool_name)
        .env("ZAGENS_SESSION_ID", session_id)
        .env("ZAGENS_ERROR_MSG", error_msg)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()?;

    let output = child.wait_with_output()?;
    let raw = if output.stdout.is_empty() {
        output.stderr
    } else {
        output.stdout
    };
    let text = String::from_utf8_lossy(&raw);
    let trimmed = text.trim();
    if trimmed.len() > 500 {
        Ok(format!("{}", &trimmed[..500]))
    } else {
        Ok(trimmed.to_string())
    }
}

/// Open a file path in the user's `$EDITOR` (Unix) or `notepad` / `$EDITOR` (Windows)
/// and block until the editor exits.
fn open_in_editor(path: &std::path::Path) -> Result<()> {
    #[cfg(target_os = "windows")]
    let editor = std::env::var("EDITOR").unwrap_or_else(|_| "notepad".to_string());
    #[cfg(not(target_os = "windows"))]
    let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vi".to_string());

    std::process::Command::new(&editor)
        .arg(path)
        .status()
        .map_err(|e| anyhow::anyhow!("failed to launch editor '{editor}': {e}"))?;
    Ok(())
}

async fn handle_slash_enter(
    ctx: &mut crate::cli::context::CliContext,
    host: &mut TuiSessionHost,
    app: &mut AppState,
    shell_tx: &tokio::sync::mpsc::UnboundedSender<String>,
) -> Result<bool> {
    let current_ws = host.thread.workspace.clone();
    if composer_slash::locale_picker_active(app.composer.text())
        && app.slash.open
        && let Some(tag) = composer_slash::selected_locale(app.composer.text(), app.slash.selected)
    {
        app.composer.clear();
        app.slash.close();
        execute_slash_action(ctx, host, app, SlashAction::SetLocale(tag), shell_tx).await?;
        return Ok(true);
    }
    if composer_slash::theme_picker_active(app.composer.text())
        && app.slash.open
        && let Some(theme_id) =
            composer_slash::selected_theme(app.composer.text(), app.slash.selected)
    {
        app.composer.clear();
        app.slash.close();
        // Theme is already applied via preview; just persist the choice.
        app.theme_picker_original = None;
        execute_slash_action(ctx, host, app, SlashAction::SwitchTheme(theme_id), shell_tx).await?;
        return Ok(true);
    }
    if composer_slash::lht_picker_active(app.composer.text())
        && app.slash.open
        && let Some(mode) =
            composer_slash::selected_lht_mode(app.composer.text(), app.slash.selected)
    {
        app.composer.clear();
        app.slash.close();
        execute_slash_action(ctx, host, app, SlashAction::SetLhtMode(mode), shell_tx).await?;
        return Ok(true);
    }
    if composer_slash::approval_picker_active(app.composer.text())
        && app.slash.open
        && let Some(policy) =
            composer_slash::selected_approval_policy(app.composer.text(), app.slash.selected)
    {
        app.composer.clear();
        app.slash.close();
        execute_slash_action(
            ctx,
            host,
            app,
            SlashAction::SetApprovalPolicy(policy.to_string()),
            shell_tx,
        )
        .await?;
        return Ok(true);
    }
    if composer_slash::model_picker_active(app.composer.text())
        && app.slash.open
        && let Some(model) = composer_slash::selected_model(
            app.composer.text(),
            app.slash.selected,
            &app.model_catalog,
        )
    {
        app.composer.clear();
        app.slash.close();
        execute_slash_action(ctx, host, app, SlashAction::SwitchModel(model), shell_tx).await?;
        return Ok(true);
    }
    if let Some(action) = composer_slash::try_parse_action(app.composer.text(), &current_ws) {
        app.composer.clear();
        app.slash.close();
        execute_slash_action(ctx, host, app, action, shell_tx).await?;
        return Ok(true);
    }

    if let Some((name, arg)) = composer_slash::split_command_line(app.composer.text())
        && !arg.is_empty()
        && composer_slash::is_workspace_command(name)
    {
        match composer_slash::resolve_workspace_path(arg, &current_ws) {
            Ok(path) => {
                app.composer.clear();
                app.slash.close();
                execute_slash_action(ctx, host, app, SlashAction::SwitchWorkspace(path), shell_tx)
                    .await?;
            }
            Err(err) => {
                app.push_system_line(format!("workspace: {err:#}"));
            }
        }
        return Ok(true);
    }

    if app.slash.open {
        if let Some(cmd) = composer_slash::selected_command(app.composer.text(), app.slash.selected)
        {
            if cmd.takes_arg {
                let arg_empty = composer_slash::split_command_line(app.composer.text())
                    .is_none_or(|(_, arg)| arg.is_empty());
                if arg_empty {
                    composer_slash::apply_palette_selection(&mut app.composer, cmd);
                    app.sync_slash_palette();
                }
            } else {
                app.composer.clear();
                app.slash.close();
                let action = match cmd.action {
                    composer_slash::SlashActionKind::New => SlashAction::NewSession,
                    composer_slash::SlashActionKind::Help => SlashAction::ShowHelp,
                    composer_slash::SlashActionKind::Automation => SlashAction::ShowAutomation,
                    composer_slash::SlashActionKind::Mcp => SlashAction::ShowMcp,
                    composer_slash::SlashActionKind::Clear => SlashAction::ClearComposer,
                    composer_slash::SlashActionKind::Logout => SlashAction::ClearApiKey,
                    composer_slash::SlashActionKind::Workspace
                    | composer_slash::SlashActionKind::Model
                    | composer_slash::SlashActionKind::Lht
                    | composer_slash::SlashActionKind::Theme
                    | composer_slash::SlashActionKind::Locale
                    | composer_slash::SlashActionKind::ApiKey
                    | composer_slash::SlashActionKind::Login
                    | composer_slash::SlashActionKind::Approve => {
                        return Ok(true);
                    }
                };
                execute_slash_action(ctx, host, app, action, shell_tx).await?;
            }
        }
        return Ok(true);
    }
    Ok(false)
}

async fn execute_slash_action(
    ctx: &mut crate::cli::context::CliContext,
    host: &mut TuiSessionHost,
    app: &mut AppState,
    action: SlashAction,
    shell_tx: &tokio::sync::mpsc::UnboundedSender<String>,
) -> Result<()> {
    match action {
        SlashAction::SwitchModel(model) => {
            if app.transcript.is_live_activity() {
                app.push_system_line("model: wait for current turn to finish".to_string());
            } else {
                host.switch_model(model.clone()).await?;
                app.sync_thread_meta(host);
                app.push_system_line(format!("model: {model}"));
            }
        }
        SlashAction::SwitchWorkspace(path) => {
            host.switch_workspace(path.clone()).await?;
            ctx.workspace = path.clone();
            app.reload_after_thread_switch(host).await;
            app.push_system_line(format!(
                "workspace: {}",
                crate::cli::context::display_path(&path)
            ));
        }
        SlashAction::SetLhtMode(mode) => {
            apply_lht_mode_change(app, mode);
        }
        SlashAction::CycleLhtMode => {
            let next = lht_mode::load_lht_composer_mode().cycle();
            apply_lht_mode_change(app, next);
        }
        SlashAction::SwitchTheme(id) => {
            apply_theme_change(app, id);
        }
        SlashAction::CycleTheme => {
            let next = theme::current_id().cycle();
            apply_theme_change(app, next);
        }
        SlashAction::SetLocale(tag) => {
            if let Err(err) = locale_cmd::apply_locale_change(app, host, &tag).await {
                app.push_system_line(format!("locale: {err:#}"));
            }
        }
        SlashAction::CycleLocale => {
            let next = locale_cmd::cycle_locale_storage(&locale_cmd::read_locale_storage());
            if let Err(err) = locale_cmd::apply_locale_change(app, host, next).await {
                app.push_system_line(format!("locale: {err:#}"));
            }
        }
        SlashAction::NewSession => {
            host.new_session(ctx).await?;
            app.reload_after_thread_switch(host).await;
            let fired = app.automation_engine.notify_session_start();
            let session_id = app.thread_id.clone();
            let event_ctx = automation::EventContext {
                session_id,
                ..Default::default()
            };
            for result in fired {
                for action in result.actions {
                    fire_automation_action(host, &mut *app, action, &event_ctx, shell_tx).await;
                }
            }
            app.push_system_line("new session".to_string());
        }
        SlashAction::ShowHelp => {
            app.show_help = true;
        }
        SlashAction::ShowAutomation => {
            app.show_automation = true;
            app.automation_ui.edit_mode = false;
            let len = app.automation_engine.config.rules.len();
            app.automation_ui.clamp_selection(len);
        }
        SlashAction::ShowMcp => {
            mcp_cmd::open_mcp_overlay(app, host.config());
        }
        SlashAction::ClearComposer => {}
        SlashAction::SaveApiKey(key) => {
            api_key_cmd::apply_save_api_key(ctx, host, app, &key).await?;
        }
        SlashAction::ClearApiKey => {
            api_key_cmd::apply_clear_api_key(ctx, host, app).await?;
        }
        SlashAction::ShowApiKeyUsage => {
            app.push_system_line(tr(app.locale, MessageId::TuiApiKeyUsage).to_string());
        }
        SlashAction::SetApprovalPolicy(policy) => {
            if let Err(err) = host.set_approval_policy(&policy).await {
                app.push_system_line(format!("approve: {err:#}"));
            } else {
                app.sync_thread_meta(host);
                app.push_system_line(format!("approve: {}", app.approval_display));
            }
        }
        SlashAction::CycleApprovalPolicy => {
            if let Err(err) = host.cycle_approval_policy().await {
                app.push_system_line(format!("approve: {err:#}"));
            } else {
                app.sync_thread_meta(host);
                app.push_system_line(format!("approve: {}", app.approval_display));
            }
        }
    }
    Ok(())
}

fn apply_lht_mode_change(app: &mut AppState, mode: zagens_config::LhtComposerMode) {
    match lht_mode::persist_lht_composer_mode(mode) {
        Ok(()) => {
            app.sync_lht_mode();
            app.push_system_line(format!(
                "lht: {} (applies on next turn)",
                lht_mode::format_lht_mode_label(mode)
            ));
        }
        Err(err) => {
            app.push_system_line(format!("lht: failed to save settings — {err}"));
        }
    }
}

fn apply_theme_change(app: &mut AppState, id: theme::TuiThemeId) {
    theme::install(theme::TuiTheme::resolve(id));
    app.layout.prefs.tui_theme = Some(id.as_str().to_string());
    app.push_system_line(format!("theme: {}", id.label()));
}

/// Called after each Up/Down move while the /theme picker is open.
/// Saves the original theme (first time) and applies the highlighted theme for live preview.
fn preview_theme_selection(app: &mut AppState) {
    if !composer_slash::theme_picker_active(app.composer.text()) || !app.slash.open {
        return;
    }
    // Record the theme that was active before the picker opened (only once).
    if app.theme_picker_original.is_none() {
        app.theme_picker_original = Some(theme::current_id());
    }
    if let Some(id) = composer_slash::selected_theme(app.composer.text(), app.slash.selected) {
        theme::install(theme::TuiTheme::resolve(id));
    }
}

async fn submit_user_input(
    host: &TuiSessionHost,
    app: &mut AppState,
    prompt: &str,
    force_steer: bool,
) {
    let prompt = prompt.trim();
    if prompt.is_empty() {
        return;
    }

    match decide_submit_disposition(&app.transcript, force_steer) {
        SubmitDisposition::Immediate => {
            app.prompt_history.push_sent(prompt);
            app.push_user_message(prompt.to_string());
            app.transcript.streaming = true;
            app.blocked_line = None;
            if let Err(err) = host.send_prompt(prompt).await {
                app.transcript.streaming = false;
                app.transcript.close_open_turn();
                app.push_system_line(format!("Failed to start turn: {err:#}"));
            }
        }
        SubmitDisposition::Queue => {
            app.prompt_queue.push_back(prompt.to_string());
        }
        SubmitDisposition::Steer => {
            app.prompt_history.push_sent(prompt);
            match host.steer_prompt(prompt).await {
                Ok(()) => {
                    app.push_steer_message(prompt);
                    app.push_system_line(tr(app.locale, MessageId::TuiSteerInjected).to_string());
                }
                Err(err) => {
                    app.prompt_queue.push_back(prompt.to_string());
                    app.push_system_line(format!("steer failed ({err:#}) — queued"));
                }
            }
        }
    }
}

async fn submit_prompt(host: &TuiSessionHost, app: &mut AppState, prompt: &str) {
    submit_user_input(host, app, prompt, false).await;
}

async fn drain_prompt_queue(host: &TuiSessionHost, app: &mut AppState) {
    while !app.transcript.is_live_activity() {
        let Some(next) = app.prompt_queue.pop_front() else {
            break;
        };
        submit_user_input(host, app, &next, false).await;
        if app.transcript.is_live_activity() {
            break;
        }
    }
}

fn resolve_mouse_capture(cli: &Cli) -> bool {
    // Mouse capture is ON by default so scroll-wheel works out of the box.
    // Pass --no-mouse-capture to disable (e.g. when copying text with the mouse).
    if cli.no_mouse_capture {
        return false;
    }
    true
}

// ── Mermaid browser-open helpers ──────────────────────────────────────────

/// Build a `mermaid.live` URL that pre-loads the given mermaid source.
///
/// Uses the `#base64:` state format (legacy, no pako required) where the
/// payload is a JSON object `{"code":"...","mermaid":{"theme":"default"}}`.
fn mermaid_live_url(src: &str) -> Option<String> {
    use base64::{Engine as _, engine::general_purpose::STANDARD};
    let json = format!(
        r#"{{"code":{code},"mermaid":{{"theme":"default"}}}}"#,
        code = serde_json::to_string(src).ok()?
    );
    let encoded = STANDARD.encode(json.as_bytes());
    Some(format!("https://mermaid.live/edit#base64:{encoded}"))
}

/// Open a URL in the default system browser.
/// Returns an error only if spawning the OS command fails; browser errors are
/// silently ignored because we cannot read them back in a TUI context.
fn open_url(url: &str) -> std::io::Result<()> {
    #[cfg(target_os = "windows")]
    {
        std::process::Command::new("cmd")
            .args(["/c", "start", "", url])
            .spawn()?;
    }
    #[cfg(target_os = "macos")]
    {
        std::process::Command::new("open").arg(url).spawn()?;
    }
    #[cfg(not(any(target_os = "windows", target_os = "macos")))]
    {
        std::process::Command::new("xdg-open").arg(url).spawn()?;
    }
    Ok(())
}