supercode-harness 0.5.45

The optional native Volter Harness agent and tool harness
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
//! P5-4 (§2 module 30): the TESTABLE view-model core — a pure `handle_key`
//! (keypress → intended [`Action`]s) plus `apply` (mutate [`TuiState`] for
//! ANY action, whether it came from a keypress or from an interactive
//! handler's request landing on the bridge channels — see
//! [`crate::tui::handlers`]). Neither function touches a terminal; every
//! test in this module drives the whole thing by hand.

use std::collections::VecDeque;

use crate::mcp::{ElicitationAction, ElicitationResponse};
use crate::permissions::ApprovalOutcome;

use super::bridge::{
    PendingApprovalRequest, PendingChildApproval, PendingElicitation, PendingOAuthDisplay,
};
use super::history::PromptHistory;
use super::key::{Key, KeyEvent};
use super::keymap::{Keymap, KeymapAction};
use super::theme::Theme;

/// Who said one transcript line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Role {
    /// The human operator.
    User,
    /// The model's own text.
    Assistant,
    /// A tool call/result rendered as chrome (not model-authored text).
    Tool,
    /// A TUI-local notice (a resolved approval, a mode change, …) — never
    /// sent to the model, purely for the human's own record.
    System,
}

/// One line (or block) in the scrollback transcript.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TranscriptEntry {
    /// Who said it.
    pub role: Role,
    /// The line's text.
    pub text: String,
}

/// Vim-emulation sub-mode (only consulted when [`TuiState::vim_enabled`] is
/// `true` — see that field's doc comment for the deliberately-basic scope:
/// `hjkl` motion, `i`/`a`/`o` mode entry, `x`/`dd` deletion. This is NOT a
/// full vim emulation (no registers, no visual mode, no `.`-repeat, no
/// counts) — a shippable-complete BASIC modal editor, with full vim cited
/// as a follow-up rather than half-built. See the crate-level `tui` module
/// doc comment's "shippable vs staged" note.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VimMode {
    /// Every key inserts/edits (the default when vim emulation is off, or
    /// the sub-mode `i`/`a`/`o` enter).
    #[default]
    Insert,
    /// Motion/command keys (`h`/`l`/`x`/`d`/…) — the mode `Esc` returns to.
    Normal,
}

/// What the input composer is showing right now.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum InputFocus {
    /// The normal text-entry composer.
    #[default]
    Composer,
    /// Ctrl+R cross-session prompt-history search is live.
    HistorySearch,
}

/// Cross-session prompt-history search state (Ctrl+R), live while
/// [`TuiState::input_focus`] is [`InputFocus::HistorySearch`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HistorySearchState {
    /// What the user has typed to narrow the search.
    pub query: String,
    /// Index into the CURRENT `history.search(query)` result list — `0` is
    /// the most recent match.
    pub selected: usize,
}

/// An interactive modal covering the composer — at most one at a time
/// (§2.28: approval / elicitation / child-approval / OAuth-code-display).
/// A later request queues behind the earlier one still on screen (see
/// `TuiState::modal_queue`) rather than clobbering it.
#[derive(Debug)]
pub enum Modal {
    /// P5-1's `Ask`-tier decision, surfaced interactively (closes the
    /// deferred `tui`-implements-the-ask-UI chain).
    Approval(PendingApprovalRequest),
    /// P5-3 §2.2 C6's queued child approval, now answerable (closes that
    /// deferred chain).
    ChildApproval(PendingChildApproval),
    /// P5-2's MCP `elicitation/create`, with the free-text answer buffer
    /// the (deliberately basic — see the crate doc comment) form widget
    /// accumulates.
    Elicitation {
        /// The server's request (message + schema) plus reply channel.
        request: PendingElicitation,
        /// The free-text answer typed into the modal so far.
        answer: String,
    },
    /// P5-2's OAuth device-code display — no reply, dismiss-only.
    OAuthDeviceCode(PendingOAuthDisplay),
}

/// The status line's contents — deliberately minimal (a renderer decorates
/// this, doesn't reinterpret it).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StatusLine {
    /// The active model's display label.
    pub model_label: String,
    /// Whether a turn is currently in flight.
    pub turn_active: bool,
    /// A one-shot notice (e.g. "press Ctrl+C again to exit") — cleared by
    /// the NEXT keypress that doesn't re-arm it, so it never lingers stale.
    pub notice: Option<String>,
}

/// A pure description of a state transition — the output of
/// [`TuiState::handle_key`] and the input to [`TuiState::apply`]. Not
/// `Clone`/`PartialEq`-derived as a whole: the `Show*Modal` variants embed
/// a one-shot reply channel ([`std::sync::mpsc::Sender`]/
/// `tokio::sync::oneshot::Sender`, neither of which is `PartialEq`) — tests
/// assert on the resulting [`TuiState`], not on raw `Action` equality.
#[derive(Debug)]
pub enum Action {
    /// Insert one character at the cursor.
    InsertChar(char),
    /// Delete the character before the cursor.
    Backspace,
    /// Delete the character at (after) the cursor.
    DeleteForward,
    /// Move the cursor one character left.
    MoveLeft,
    /// Move the cursor one character right.
    MoveRight,
    /// Move the cursor to the start of the composer.
    MoveHome,
    /// Move the cursor to the end of the composer.
    MoveEnd,
    /// Insert a newline without submitting (multi-line composing).
    Newline,
    /// Clear the composer buffer without submitting (non-empty-line
    /// Ctrl+C, and vim `dd`).
    ClearComposerLine,
    /// The composer's contents were submitted — `apply` clears the
    /// composer, appends the text to history + the transcript. The CLI
    /// event loop is the one that actually calls `agent.send(text)`; it
    /// sees this variant in `handle_key`'s returned `Vec<Action>` BEFORE
    /// calling `apply` (see the module doc comment on the render layer).
    Submit(String),
    /// Scroll the transcript up one page.
    ScrollUp,
    /// Scroll the transcript down one page.
    ScrollDown,
    /// Toggle the dark/light theme.
    ToggleTheme,
    /// Enter Ctrl+R cross-session prompt-history search.
    OpenHistorySearch,
    /// Type one character into the history-search query.
    HistorySearchType(char),
    /// Delete the last character of the history-search query.
    HistorySearchBackspace,
    /// Select the next (older) matching history entry.
    HistorySearchNext,
    /// Select the previous (more recent) matching history entry.
    HistorySearchPrev,
    /// Accept the selected history entry into the composer.
    HistorySearchConfirm,
    /// Leave history search without changing the composer.
    HistorySearchCancel,
    /// Switch vim sub-mode (Normal/Insert).
    VimSetMode(VimMode),
    /// Vim `h` — move left.
    VimMoveLeft,
    /// Vim `l` — move right.
    VimMoveRight,
    /// Vim `0` — move to line start.
    VimMoveHome,
    /// Vim `$` — move to line end.
    VimMoveEnd,
    /// Vim `x` — delete the character under the cursor.
    VimDeleteChar,
    /// Vim `dd` (approximated as one keystroke — see [`VimMode`]'s doc
    /// comment) — clear the composer line.
    VimDeleteLine,
    /// The CLI layer should shell out to `$EDITOR` — `apply` only flips a
    /// flag ([`TuiState::external_editor_requested`]); the actual process
    /// spawn is terminal I/O, out of the view-model's scope.
    RequestExternalEditor,
    /// The CLI layer's `$EDITOR` invocation finished — replaces the
    /// composer with the edited text.
    ExternalEditorResult(String),
    /// F9 (Fable-5 adversarial review — LOW): the CLI layer's `$EDITOR`
    /// invocation failed to spawn (editor not found, exec error, …) —
    /// clears [`TuiState::external_editor_requested`] (same as
    /// `ExternalEditorResult`, so `run_loop` doesn't keep retrying it
    /// every tick) WITHOUT touching the composer, and surfaces `message`
    /// as a system transcript notice so the session stays alive and the
    /// user actually sees why nothing happened, instead of the whole TUI
    /// process exiting out from under them.
    ExternalEditorFailed(String),
    /// An image was pasted/attached (path or a data reference) — appended
    /// to the composer as a placeholder token and recorded in
    /// [`TuiState::pending_images`] for the CLI layer to route into the
    /// multimodal read path.
    PasteImage(String),
    /// A new top-level `Ask`-tier approval request arrived — show (or
    /// queue) it as a modal.
    ShowApprovalModal(PendingApprovalRequest),
    /// The user resolved the active approval modal.
    ResolveApproval(ApprovalOutcome),
    /// A new background-child approval request arrived — show (or queue)
    /// it as a modal.
    ShowChildApprovalModal(PendingChildApproval),
    /// The user resolved the active child-approval modal.
    ResolveChildApproval(ApprovalOutcome),
    /// A new MCP elicitation request arrived — show (or queue) it as a
    /// modal.
    ShowElicitationModal(PendingElicitation),
    /// Type one character into the elicitation answer buffer.
    ElicitationType(char),
    /// Delete the last character of the elicitation answer buffer.
    ElicitationBackspace,
    /// Accept the elicitation with the typed answer.
    ResolveElicitationAccept,
    /// Decline the elicitation.
    ResolveElicitationDecline,
    /// Cancel/dismiss the elicitation without a decision.
    ResolveElicitationCancel,
    /// A new OAuth device-code display arrived — show (or queue) it.
    ShowOAuthModal(PendingOAuthDisplay),
    /// Dismiss the OAuth device-code modal (no reply — see
    /// [`PendingOAuthDisplay`]'s doc comment).
    DismissOAuthModal,
    /// A chunk of streaming assistant text arrived.
    AppendStreamingDelta(String),
    /// The in-progress streaming turn is done — move it into the
    /// transcript.
    FinalizeStreaming,
    /// Append one entry directly to the transcript (tool events, system
    /// notices raised outside a modal resolution).
    PushTranscript(TranscriptEntry),
    /// Update the status line's model label.
    SetModelLabel(String),
    /// Update the status line's turn-in-flight indicator.
    SetTurnActive(bool),
    /// First Ctrl+C on an empty, non-modal composer — arms the "press
    /// again to exit" notice without quitting yet.
    ArmQuit,
    /// Second consecutive Ctrl+C — actually quit.
    Quit,
    /// A key the current focus/modal doesn't bind to anything — carries no
    /// mutation; `apply` is a no-op for it. `handle_key` prefers returning
    /// an empty `Vec` over this where possible; it exists for the rare
    /// case a caller wants an explicit "nothing happened" marker (e.g. a
    /// disabled modal option).
    Noop,
}

/// The whole TUI view-model — see the module doc comment. Constructed
/// fresh per TUI session by the CLI render layer; every mutation goes
/// through [`Self::apply`].
#[derive(Debug)]
pub struct TuiState {
    /// The composer's current text.
    pub input: String,
    /// Byte offset into `input` — always on a `char` boundary.
    pub cursor: usize,
    /// The scrollback transcript, oldest first.
    pub transcript: Vec<TranscriptEntry>,
    /// In-progress assistant text (streaming) — `None` when no turn is
    /// mid-flight.
    pub streaming: Option<String>,
    /// The currently-showing modal, if any.
    pub modal: Option<Modal>,
    /// Requests that arrived while a modal was already showing — FIFO,
    /// drained into `modal` by [`Self::dequeue_modal`] once the current one
    /// resolves.
    modal_queue: VecDeque<Modal>,
    /// The active display theme.
    pub theme: Theme,
    /// The resolved (default + overrides) keybinding table.
    pub keymap: Keymap,
    /// D8 "vim" — whether modal editing is active at all
    /// ([`crate::Config::tui_vim_mode`]). `false` (the default): every key
    /// is a plain insert/navigate, [`VimMode`] is never consulted.
    pub vim_enabled: bool,
    /// The current vim sub-mode (only meaningful when `vim_enabled`).
    pub vim_mode: VimMode,
    /// The cross-session prompt history.
    pub history: PromptHistory,
    /// Live Ctrl+R search state, if [`Self::input_focus`] is
    /// [`InputFocus::HistorySearch`].
    pub history_search: Option<HistorySearchState>,
    /// What the composer area is currently showing.
    pub input_focus: InputFocus,
    /// The status line's contents.
    pub status: StatusLine,
    /// Current transcript scroll offset (pages back from the bottom).
    pub scroll: usize,
    /// Set once the user has asked to quit — the render loop's exit
    /// signal.
    pub should_quit: bool,
    /// Whether the FIRST of a double-Ctrl+C-to-quit has already landed.
    quit_armed: bool,
    /// Set while the CLI layer's `$EDITOR` invocation is in flight.
    pub external_editor_requested: bool,
    /// Image references pasted into the composer, in submission order —
    /// drained by the CLI layer once it reads [`Action::Submit`].
    pub pending_images: Vec<String>,
    /// Set by `apply(Action::Submit(text))` to `Some(text)` — the CLI event
    /// loop's ONE polling point for "a turn needs to be sent": call
    /// [`Self::take_submission`] after every [`Self::on_key`] (or manual
    /// `apply`) to both read and clear it in one step, so a submission is
    /// never double-sent.
    pub last_submission: Option<String>,
}

impl TuiState {
    /// A fresh, empty state — `theme`/`vim_enabled`/`keymap` typically come
    /// from the resolved [`crate::Config`] (`tui_theme`/`tui_vim_mode`/
    /// `tui_keymap`), `history` from [`PromptHistory::load_from_file`].
    pub fn new(theme: Theme, keymap: Keymap, vim_enabled: bool, history: PromptHistory) -> Self {
        TuiState {
            input: String::new(),
            cursor: 0,
            transcript: Vec::new(),
            streaming: None,
            modal: None,
            modal_queue: VecDeque::new(),
            theme,
            keymap,
            vim_enabled,
            vim_mode: if vim_enabled {
                VimMode::Normal
            } else {
                VimMode::Insert
            },
            history,
            history_search: None,
            input_focus: InputFocus::Composer,
            status: StatusLine::default(),
            scroll: 0,
            should_quit: false,
            quit_armed: false,
            external_editor_requested: false,
            pending_images: Vec::new(),
            last_submission: None,
        }
    }

    /// Convenience for a caller that doesn't need `Default::default()`-style
    /// construction control — plain-mode, dark theme, default keymap, empty
    /// history. Handy for tests and the render layer's smoke-test harness.
    pub fn new_default() -> Self {
        TuiState::new(
            Theme::default(),
            Keymap::default(),
            false,
            PromptHistory::new(),
        )
    }

    /// Translate one keypress into the [`Action`]s it produces — READS
    /// state (to be context-sensitive: a modal open, history-search
    /// active, vim normal-mode all change what a key means) but never
    /// mutates it. Call [`Self::apply`] on each returned action (in order)
    /// to actually realize the transition — the render layer's `on_key`
    /// convenience does exactly that.
    pub fn handle_key(&self, key: KeyEvent) -> Vec<Action> {
        if let Some(modal) = &self.modal {
            return self.handle_key_in_modal(modal, key);
        }
        match self.input_focus {
            InputFocus::HistorySearch => self.handle_key_in_history_search(key),
            InputFocus::Composer => self.handle_key_in_composer(key),
        }
    }

    fn handle_key_in_composer(&self, key: KeyEvent) -> Vec<Action> {
        let km = &self.keymap;
        if key == km.key_for(KeymapAction::Quit) {
            return if self.input.is_empty() {
                if self.quit_armed {
                    vec![Action::Quit]
                } else {
                    vec![Action::ArmQuit]
                }
            } else {
                // Non-empty composer: Ctrl+C clears the line (matches the
                // pre-P5-4 REPL's own "a lone idle Ctrl-C only clears the
                // current line" convention — see `crates/cli/src/main.rs`
                // `chat()`'s doc comment).
                vec![Action::MoveHome, Action::ClearComposerLine]
            };
        }
        if key == km.key_for(KeymapAction::HistorySearch) {
            return vec![Action::OpenHistorySearch];
        }
        if key == km.key_for(KeymapAction::ToggleTheme) {
            return vec![Action::ToggleTheme];
        }
        if key == km.key_for(KeymapAction::ScrollUp) {
            return vec![Action::ScrollUp];
        }
        if key == km.key_for(KeymapAction::ScrollDown) {
            return vec![Action::ScrollDown];
        }
        if key == km.key_for(KeymapAction::ExternalEditor) {
            return vec![Action::RequestExternalEditor];
        }
        if key == km.key_for(KeymapAction::Newline) {
            return vec![Action::Newline];
        }
        if self.vim_enabled && self.vim_mode == VimMode::Normal {
            return self.handle_key_vim_normal(key);
        }
        if key == km.key_for(KeymapAction::Submit) {
            if self.input.is_empty() {
                return vec![];
            }
            return vec![Action::Submit(self.input.clone())];
        }
        match key.key {
            Key::Char(c) if !key.ctrl && !key.alt => vec![Action::InsertChar(c)],
            Key::Backspace => vec![Action::Backspace],
            Key::Delete => vec![Action::DeleteForward],
            Key::Left => vec![Action::MoveLeft],
            Key::Right => vec![Action::MoveRight],
            Key::Home => vec![Action::MoveHome],
            Key::End => vec![Action::MoveEnd],
            Key::Escape if self.vim_enabled => vec![Action::VimSetMode(VimMode::Normal)],
            _ => vec![],
        }
    }

    fn handle_key_vim_normal(&self, key: KeyEvent) -> Vec<Action> {
        if key.ctrl || key.alt {
            return vec![];
        }
        match key.key {
            Key::Char('i') => vec![Action::VimSetMode(VimMode::Insert)],
            Key::Char('a') => vec![Action::VimMoveRight, Action::VimSetMode(VimMode::Insert)],
            Key::Char('o') => vec![
                Action::VimMoveEnd,
                Action::Newline,
                Action::VimSetMode(VimMode::Insert),
            ],
            Key::Char('h') => vec![Action::VimMoveLeft],
            Key::Char('l') => vec![Action::VimMoveRight],
            Key::Char('0') => vec![Action::VimMoveHome],
            Key::Char('$') => vec![Action::VimMoveEnd],
            Key::Char('x') => vec![Action::VimDeleteChar],
            // `dd` (delete the whole composer line) is approximated as a
            // single `d` press — see the crate doc comment's "basic, not
            // full vim" scope note (no two-keystroke command buffering).
            Key::Char('d') => vec![Action::VimDeleteLine],
            Key::Enter if self.input.is_empty() => vec![],
            Key::Enter => vec![Action::Submit(self.input.clone())],
            _ => vec![],
        }
    }

    fn handle_key_in_history_search(&self, key: KeyEvent) -> Vec<Action> {
        match key.key {
            Key::Escape => vec![Action::HistorySearchCancel],
            Key::Enter => vec![Action::HistorySearchConfirm],
            Key::Up => vec![Action::HistorySearchPrev],
            Key::Down => vec![Action::HistorySearchNext],
            _ if key == self.keymap.key_for(KeymapAction::HistorySearch) => {
                vec![Action::HistorySearchNext]
            }
            Key::Backspace => vec![Action::HistorySearchBackspace],
            Key::Char(c) if !key.ctrl && !key.alt => vec![Action::HistorySearchType(c)],
            _ => vec![],
        }
    }

    fn handle_key_in_modal(&self, modal: &Modal, key: KeyEvent) -> Vec<Action> {
        match modal {
            // F3 (Fable-5 adversarial review — MEDIUM): both approval
            // arms below now guard on `!key.ctrl && !key.alt`, matching
            // the elicitation arm's own `Key::Char(c) if !key.ctrl &&
            // !key.alt` guard further down — WITHOUT it, Ctrl+A (a common
            // "select all"/readline chord in plenty of other programs)
            // resolved `Allow`, and Ctrl+S resolved `AllowForSession`, on
            // a modal whose whole POINT is a deliberate human decision;
            // a reflexive chord muscle-memoried from another program must
            // never resolve one.
            Modal::Approval(_) if !key.ctrl && !key.alt => match key.key {
                Key::Char('y') | Key::Char('a') => {
                    vec![Action::ResolveApproval(ApprovalOutcome::Allow)]
                }
                Key::Char('s') => vec![Action::ResolveApproval(ApprovalOutcome::AllowForSession)],
                Key::Char('n') | Key::Char('d') | Key::Escape => {
                    vec![Action::ResolveApproval(ApprovalOutcome::Deny)]
                }
                _ => vec![],
            },
            Modal::Approval(_) => vec![],
            Modal::ChildApproval(_) if !key.ctrl && !key.alt => match key.key {
                Key::Char('y') | Key::Char('a') => {
                    vec![Action::ResolveChildApproval(ApprovalOutcome::Allow)]
                }
                Key::Char('s') => vec![Action::ResolveChildApproval(
                    ApprovalOutcome::AllowForSession,
                )],
                Key::Char('n') | Key::Char('d') | Key::Escape => {
                    vec![Action::ResolveChildApproval(ApprovalOutcome::Deny)]
                }
                _ => vec![],
            },
            Modal::ChildApproval(_) => vec![],
            Modal::Elicitation { .. } => match key.key {
                Key::Enter => vec![Action::ResolveElicitationAccept],
                Key::Escape => vec![Action::ResolveElicitationCancel],
                Key::F(2) => vec![Action::ResolveElicitationDecline],
                Key::Backspace => vec![Action::ElicitationBackspace],
                Key::Char(c) if !key.ctrl && !key.alt => vec![Action::ElicitationType(c)],
                _ => vec![],
            },
            Modal::OAuthDeviceCode(_) => match key.key {
                Key::Enter | Key::Escape => vec![Action::DismissOAuthModal],
                _ => vec![],
            },
        }
    }

    /// Apply one [`Action`] — the only place [`TuiState`] mutates. Any key
    /// OTHER than the one that just armed `Self::quit_armed` disarms it
    /// (so "Ctrl+C, type something, Ctrl+C" does NOT quit — only two
    /// CONSECUTIVE Ctrl+C presses do), except `ArmQuit`/`Quit` themselves.
    pub fn apply(&mut self, action: Action) {
        if !matches!(action, Action::ArmQuit | Action::Quit) {
            if self.quit_armed {
                self.status.notice = None;
            }
            self.quit_armed = false;
        }
        match action {
            Action::InsertChar(c) => {
                self.input.insert(self.cursor, c);
                self.cursor += c.len_utf8();
            }
            Action::Backspace => {
                if self.cursor > 0 {
                    let mut idx = self.cursor - 1;
                    while !self.input.is_char_boundary(idx) {
                        idx -= 1;
                    }
                    self.input.remove(idx);
                    self.cursor = idx;
                }
            }
            Action::DeleteForward => {
                if self.cursor < self.input.len() {
                    self.input.remove(self.cursor);
                }
            }
            Action::MoveLeft => {
                if self.cursor > 0 {
                    let mut idx = self.cursor - 1;
                    while !self.input.is_char_boundary(idx) {
                        idx -= 1;
                    }
                    self.cursor = idx;
                }
            }
            Action::MoveRight => {
                if self.cursor < self.input.len() {
                    let mut idx = self.cursor + 1;
                    while idx < self.input.len() && !self.input.is_char_boundary(idx) {
                        idx += 1;
                    }
                    self.cursor = idx;
                }
            }
            Action::MoveHome => self.cursor = 0,
            Action::MoveEnd => self.cursor = self.input.len(),
            Action::Newline => {
                self.input.insert(self.cursor, '\n');
                self.cursor += 1;
            }
            Action::ClearComposerLine => {
                self.input.clear();
                self.cursor = 0;
            }
            Action::Submit(text) => {
                self.history.push(text.clone());
                self.transcript.push(TranscriptEntry {
                    role: Role::User,
                    text: text.clone(),
                });
                self.input.clear();
                self.cursor = 0;
                // F5 (Fable-5 adversarial review): this used to clear
                // `pending_images` right here — BEFORE the CLI layer's
                // render loop ever gets a chance to read `last_submission`
                // (that only happens on the NEXT tick, via
                // `Self::take_submission`). A pasted image's path was
                // gone by the time anything could route it into the turn
                // — the model only ever saw the literal `[image: …]`
                // placeholder text. `pending_images` now stays put until
                // [`Self::take_pending_images`] drains it — see that
                // method's doc comment for the paired contract.
                self.last_submission = Some(text);
            }
            Action::ScrollUp => self.scroll = self.scroll.saturating_add(1),
            Action::ScrollDown => self.scroll = self.scroll.saturating_sub(1),
            Action::ToggleTheme => self.theme = self.theme.toggled(),
            Action::OpenHistorySearch => {
                self.input_focus = InputFocus::HistorySearch;
                self.history_search = Some(HistorySearchState::default());
            }
            Action::HistorySearchType(c) => {
                if let Some(s) = &mut self.history_search {
                    s.query.push(c);
                    s.selected = 0;
                }
            }
            Action::HistorySearchBackspace => {
                if let Some(s) = &mut self.history_search {
                    s.query.pop();
                    s.selected = 0;
                }
            }
            Action::HistorySearchNext => {
                if let Some(s) = &mut self.history_search {
                    let n = self.history.search(&s.query).len();
                    if n > 0 {
                        s.selected = (s.selected + 1) % n;
                    }
                }
            }
            Action::HistorySearchPrev => {
                if let Some(s) = &mut self.history_search {
                    let n = self.history.search(&s.query).len();
                    if n > 0 {
                        s.selected = (s.selected + n - 1) % n;
                    }
                }
            }
            Action::HistorySearchConfirm => {
                if let Some(s) = self.history_search.take() {
                    if let Some(&hit) = self.history.search(&s.query).get(s.selected) {
                        self.input = hit.to_string();
                        self.cursor = self.input.len();
                    }
                }
                self.input_focus = InputFocus::Composer;
            }
            Action::HistorySearchCancel => {
                self.history_search = None;
                self.input_focus = InputFocus::Composer;
            }
            Action::VimSetMode(mode) => self.vim_mode = mode,
            Action::VimMoveLeft => self.apply(Action::MoveLeft),
            Action::VimMoveRight => self.apply(Action::MoveRight),
            Action::VimMoveHome => self.apply(Action::MoveHome),
            Action::VimMoveEnd => self.apply(Action::MoveEnd),
            Action::VimDeleteChar => self.apply(Action::DeleteForward),
            Action::VimDeleteLine => self.apply(Action::ClearComposerLine),
            Action::RequestExternalEditor => self.external_editor_requested = true,
            Action::ExternalEditorResult(text) => {
                self.external_editor_requested = false;
                self.input = text;
                self.cursor = self.input.len();
            }
            Action::ExternalEditorFailed(message) => {
                self.external_editor_requested = false;
                self.transcript.push(TranscriptEntry {
                    role: Role::System,
                    text: format!("$EDITOR failed: {message}"),
                });
            }
            Action::PasteImage(reference) => {
                self.pending_images.push(reference.clone());
                let token = format!("[image: {reference}]");
                self.input.insert_str(self.cursor, &token);
                self.cursor += token.len();
            }
            Action::ShowApprovalModal(req) => self.enqueue_or_show(Modal::Approval(req)),
            Action::ResolveApproval(outcome) => {
                if let Some(Modal::Approval(req)) =
                    self.take_modal_if(|m| matches!(m, Modal::Approval(_)))
                {
                    let note = approval_note(&req.tool, req.subject.as_deref(), outcome);
                    let _ = req.reply_tx.send(outcome);
                    self.transcript.push(TranscriptEntry {
                        role: Role::System,
                        text: note,
                    });
                }
                self.dequeue_modal();
            }
            Action::ShowChildApprovalModal(req) => self.enqueue_or_show(Modal::ChildApproval(req)),
            Action::ResolveChildApproval(outcome) => {
                if let Some(Modal::ChildApproval(req)) =
                    self.take_modal_if(|m| matches!(m, Modal::ChildApproval(_)))
                {
                    let note = format!(
                        "child `{}` {}",
                        req.child_agent_id,
                        approval_note(&req.tool, req.subject.as_deref(), outcome)
                    );
                    let _ = req.reply_tx.send(outcome);
                    self.transcript.push(TranscriptEntry {
                        role: Role::System,
                        text: note,
                    });
                }
                self.dequeue_modal();
            }
            Action::ShowElicitationModal(req) => self.enqueue_or_show(Modal::Elicitation {
                request: req,
                answer: String::new(),
            }),
            Action::ElicitationType(c) => {
                if let Some(Modal::Elicitation { answer, .. }) = &mut self.modal {
                    answer.push(c);
                }
            }
            Action::ElicitationBackspace => {
                if let Some(Modal::Elicitation { answer, .. }) = &mut self.modal {
                    answer.pop();
                }
            }
            Action::ResolveElicitationAccept => {
                if let Some(Modal::Elicitation { request, answer }) =
                    self.take_modal_if(|m| matches!(m, Modal::Elicitation { .. }))
                {
                    let content = elicitation_content(&request.requested_schema, &answer);
                    // F9 (Fable-5 adversarial review — LOW security bit):
                    // this used to echo `answer` VERBATIM into the
                    // scrollback transcript — a server asking for a token/
                    // password left it sitting in plaintext, visible on
                    // screen and in anything that later scrolls back
                    // through the transcript. The MCP elicitation schema
                    // has no standardized "this field is a secret" signal
                    // to key an exemption off (see
                    // `PendingElicitation::requested_schema`'s shape), so
                    // the safe default is masking EVERY elicitation
                    // answer's echo, not guessing from the field name —
                    // the actual `content` sent back to the server (right
                    // above) is unaffected, this only changes what the
                    // HUMAN'S OWN screen shows afterward.
                    self.transcript.push(TranscriptEntry {
                        role: Role::System,
                        text: format!("elicitation answered: {}", mask_elicitation_answer(&answer)),
                    });
                    let _ = request.reply_tx.send(ElicitationResponse {
                        action: ElicitationAction::Accept,
                        content: Some(content),
                    });
                }
                self.dequeue_modal();
            }
            Action::ResolveElicitationDecline => {
                if let Some(Modal::Elicitation { request, .. }) =
                    self.take_modal_if(|m| matches!(m, Modal::Elicitation { .. }))
                {
                    self.transcript.push(TranscriptEntry {
                        role: Role::System,
                        text: "elicitation declined".to_string(),
                    });
                    let _ = request.reply_tx.send(ElicitationResponse {
                        action: ElicitationAction::Decline,
                        content: None,
                    });
                }
                self.dequeue_modal();
            }
            Action::ResolveElicitationCancel => {
                if let Some(Modal::Elicitation { request, .. }) =
                    self.take_modal_if(|m| matches!(m, Modal::Elicitation { .. }))
                {
                    let _ = request.reply_tx.send(ElicitationResponse {
                        action: ElicitationAction::Cancel,
                        content: None,
                    });
                }
                self.dequeue_modal();
            }
            Action::ShowOAuthModal(display) => {
                self.enqueue_or_show(Modal::OAuthDeviceCode(display))
            }
            Action::DismissOAuthModal => {
                self.take_modal_if(|m| matches!(m, Modal::OAuthDeviceCode(_)));
                self.dequeue_modal();
            }
            Action::AppendStreamingDelta(delta) => {
                self.streaming
                    .get_or_insert_with(String::new)
                    .push_str(&delta);
            }
            Action::FinalizeStreaming => {
                if let Some(text) = self.streaming.take() {
                    self.transcript.push(TranscriptEntry {
                        role: Role::Assistant,
                        text,
                    });
                }
            }
            Action::PushTranscript(entry) => self.transcript.push(entry),
            Action::SetModelLabel(label) => self.status.model_label = label,
            Action::SetTurnActive(active) => self.status.turn_active = active,
            Action::ArmQuit => {
                self.quit_armed = true;
                self.status.notice = Some("press Ctrl+C again to exit".to_string());
            }
            Action::Quit => self.should_quit = true,
            Action::Noop => {}
        }
    }

    /// Run [`Self::handle_key`], then [`Self::apply`] every resulting
    /// action in order — the render layer's one-call-per-keypress
    /// convenience. Every externally-relevant outcome (a turn to send, an
    /// editor to launch, …) lands in a dedicated `TuiState` field
    /// ([`Self::last_submission`]/[`Self::external_editor_requested`]/
    /// [`Self::should_quit`]) the caller polls afterward — `Action` itself
    /// is intentionally NOT `Clone` (it carries one-shot reply channels),
    /// so this doesn't hand actions back; a caller that needs to react to
    /// the RAW action stream (e.g. a test) calls `handle_key`+`apply`
    /// directly instead, as most of this module's own tests do.
    pub fn on_key(&mut self, key: KeyEvent) {
        for action in self.handle_key(key) {
            self.apply(action);
        }
    }

    /// Take (and clear) the most recent submission, if any — see
    /// [`Self::last_submission`]'s doc comment.
    pub fn take_submission(&mut self) -> Option<String> {
        self.last_submission.take()
    }

    /// F5 (Fable-5 adversarial review): the CLI layer's paired polling
    /// point alongside [`Self::take_submission`] — call both together,
    /// same tick, right after `take_submission` returns `Some`: this
    /// drains (and clears) every image path staged via
    /// [`Action::PasteImage`] for THAT submission, for the caller to
    /// route into the turn's multimodal content (e.g.
    /// `Agent::send_with_images`). Previously `Action::Submit` cleared
    /// `pending_images` eagerly, before the CLI layer could ever read it
    /// — this method is what makes draining it the CLI's job instead, so
    /// a pasted image path actually reaches the model.
    pub fn take_pending_images(&mut self) -> Vec<String> {
        std::mem::take(&mut self.pending_images)
    }

    fn enqueue_or_show(&mut self, modal: Modal) {
        if self.modal.is_none() {
            self.modal = Some(modal);
        } else {
            self.modal_queue.push_back(modal);
        }
    }

    fn dequeue_modal(&mut self) {
        if self.modal.is_none() {
            self.modal = self.modal_queue.pop_front();
        }
    }

    fn take_modal_if(&mut self, pred: impl FnOnce(&Modal) -> bool) -> Option<Modal> {
        if self.modal.as_ref().is_some_and(pred) {
            self.modal.take()
        } else {
            None
        }
    }

    /// D-1 (Fable-5 delta review — MEDIUM, "error-path indefinite hang"):
    /// drop the active modal AND everything still queued behind it,
    /// without sending a reply. Each [`Modal`] variant that carries a
    /// reply channel (`Approval`/`ChildApproval`'s `std::sync::mpsc::Sender`,
    /// `Elicitation`'s `tokio::sync::oneshot::Sender`) has its sender
    /// dropped as part of this — the corresponding blocked caller
    /// (`TuiApprovalHandler::ask`/elicitation) already treats a closed
    /// channel as its documented fail-closed default
    /// (`ApprovalOutcome::Deny` / a declined `ElicitationResponse`; see
    /// `crate::tui::handlers`), so this never silently allows anything.
    /// `OAuthDeviceCode` carries no reply channel — dropping it is a plain
    /// dismissal.
    ///
    /// The CLI's render loop (`run_turn_blocking_with_input`) calls this
    /// when its own terminal I/O has failed while a modal is still
    /// unanswered: nothing is left alive to answer it (crossterm is
    /// broken), and the in-flight turn's worker thread is parked in a
    /// blocking `recv()`/`.await` on that modal's reply channel that
    /// `std::thread::scope` will join before the loop can return ANY
    /// value, including its own I/O error — so leaving the modal pending
    /// would hang the whole session forever instead of surfacing that
    /// error.
    pub fn fail_close_pending_modals(&mut self) {
        self.modal = None;
        self.modal_queue.clear();
    }
}

fn approval_note(tool: &str, subject: Option<&str>, outcome: ApprovalOutcome) -> String {
    let verdict = match outcome {
        ApprovalOutcome::Deny => "denied",
        ApprovalOutcome::Allow => "allowed (once)",
        ApprovalOutcome::AllowForSession => "allowed (for session)",
    };
    match subject {
        Some(s) => format!("approval: {tool} `{s}` — {verdict}"),
        None => format!("approval: {tool} — {verdict}"),
    }
}

/// P5-2: build the `content` an [`ElicitationResponse::Accept`] carries
/// from the modal's free-text `answer` — deliberately basic (not a full
/// JSON-Schema-driven form builder, see the crate doc comment's
/// shippable-vs-staged note): if `schema` names exactly one top-level
/// property, the answer is wrapped under THAT property's name (so a
/// single-field schema round-trips as the field the server actually asked
/// for); otherwise it's wrapped under a generic `"value"` key.
fn elicitation_content(schema: &serde_json::Value, answer: &str) -> serde_json::Value {
    if let Some(props) = schema.get("properties").and_then(|p| p.as_object()) {
        if props.len() == 1 {
            if let Some(name) = props.keys().next() {
                return serde_json::json!({ name: answer });
            }
        }
    }
    serde_json::json!({ "value": answer })
}

/// F9 (Fable-5 adversarial review — LOW security bit): mask an
/// elicitation answer before it's echoed into the (human-visible-only)
/// transcript — see [`TuiState::apply`]'s `ResolveElicitationAccept` arm
/// for why every answer is masked rather than trying to guess which ones
/// are "sensitive" from the field name. A fixed-width placeholder (not
/// one bullet per character) so the mask itself doesn't leak the
/// answer's length; an empty answer gets its own honest placeholder
/// rather than a mask that looks identical to a real one.
fn mask_elicitation_answer(answer: &str) -> &'static str {
    if answer.is_empty() {
        "(empty)"
    } else {
        "••••"
    }
}