agentty 0.15.0

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use crossterm::event::{Event, KeyEvent, KeyEventKind};
use ratatui::Terminal;
use ratatui::backend::Backend;
use tokio::sync::mpsc;
use tracing::debug;

use crate::app::{App, AppRuntimeEvent};
use crate::domain::input::InputCommand;
use crate::presentation::app_mode::AppMode;
use crate::runtime::{EventResult, FRAME_INTERVAL, PresentationState, key_handler, mode};

/// Maximum terminal input events processed in one foreground cycle.
///
/// Additional queued events remain buffered for the next runtime cycle so the
/// render loop can redraw between large paste/key-repeat bursts.
const TERMINAL_EVENT_DRAIN_BUDGET: usize = 64;

/// Reads terminal events from an underlying event backend.
#[cfg_attr(test, mockall::automock)]
pub(crate) trait EventSource: Send + Sync + 'static {
    /// Polls for an available event.
    fn poll(&self, timeout: Duration) -> io::Result<bool>;

    /// Reads the next available event.
    fn read(&self) -> io::Result<Event>;
}

struct CrosstermEventSource;

impl EventSource for CrosstermEventSource {
    fn poll(&self, timeout: Duration) -> io::Result<bool> {
        crossterm::event::poll(timeout)
    }

    fn read(&self) -> io::Result<Event> {
        crossterm::event::read()
    }
}

/// Represents the next runtime wake-up source while awaiting input or redraw.
enum LoopSignal {
    /// One terminal input event from the foreground reader thread.
    Event(Option<io::Result<Event>>),
    /// One foreground-owned app event or session actor command.
    Runtime(AppRuntimeEvent),
    /// One redraw tick with no immediate input payload.
    Tick,
}

/// Converts injected terminal messages into the fallible production event
/// transport used by the runtime loop.
pub(crate) trait TerminalEventMessage {
    fn into_event_result(self) -> io::Result<Event>;
}

impl TerminalEventMessage for Event {
    fn into_event_result(self) -> io::Result<Event> {
        Ok(self)
    }
}

impl TerminalEventMessage for io::Result<Event> {
    fn into_event_result(self) -> io::Result<Event> {
        self
    }
}

/// Returns the terminal-reader failure used when any event sender disappears.
fn terminal_event_channel_closed_error() -> io::Error {
    io::Error::new(
        io::ErrorKind::UnexpectedEof,
        "terminal event reader stopped",
    )
}

/// Spawns the terminal event reader thread with production dependencies.
pub(crate) fn spawn_event_reader(
    event_tx: mpsc::UnboundedSender<io::Result<Event>>,
    shutdown: Arc<AtomicBool>,
) -> std::thread::JoinHandle<()> {
    let event_source: Arc<dyn EventSource> = Arc::new(CrosstermEventSource);

    spawn_event_reader_with_source(event_source, event_tx, shutdown)
}

/// Spawns the terminal event reader with injected dependencies.
fn spawn_event_reader_with_source(
    event_source: Arc<dyn EventSource>,
    event_tx: mpsc::UnboundedSender<io::Result<Event>>,
    shutdown: Arc<AtomicBool>,
) -> std::thread::JoinHandle<()> {
    std::thread::spawn(move || {
        while !shutdown.load(Ordering::Relaxed)
            && forward_next_terminal_event(event_source.as_ref(), &event_tx)
        {}
    })
}

/// Polls for and forwards one terminal event, returning whether reading should
/// continue.
fn forward_next_terminal_event(
    event_source: &dyn EventSource,
    event_tx: &mpsc::UnboundedSender<io::Result<Event>>,
) -> bool {
    let event = match event_source.poll(FRAME_INTERVAL) {
        Ok(true) => event_source.read(),
        Ok(false) => return true,
        Err(error) if error.kind() == io::ErrorKind::Interrupted => return true,
        Err(error) => Err(error),
    };

    match event {
        Ok(event) => event_tx.send(Ok(event)).is_ok(),
        Err(error) if error.kind() == io::ErrorKind::Interrupted => true,
        Err(error) => {
            let _ = event_tx.send(Err(error));

            false
        }
    }
}

/// Waits for the next terminal/app event or tick and dispatches one runtime
/// processing cycle.
pub(crate) async fn process_events<B: Backend, Message: TerminalEventMessage>(
    app: &mut App,
    presentation: Rc<PresentationState>,
    terminal: &mut Terminal<B>,
    event_rx: &mut mpsc::UnboundedReceiver<Message>,
    tick: &mut tokio::time::Interval,
) -> io::Result<EventResult>
where
    B::Error: std::error::Error + Send + Sync + 'static,
{
    process_events_with_handler(app, terminal, event_rx, tick, |app, terminal, event| {
        let presentation = Rc::clone(&presentation);

        Box::pin(process_event(app, presentation, terminal, event))
    })
    .await
}

/// Processes one event/tick cycle with an injected event handler so loop exit
/// branches can be tested without a real terminal.
async fn process_events_with_handler<Terminal, Message, EventHandler>(
    app: &mut App,
    terminal: &mut Terminal,
    event_rx: &mut mpsc::UnboundedReceiver<Message>,
    tick: &mut tokio::time::Interval,
    mut handle_event: EventHandler,
) -> io::Result<EventResult>
where
    Message: TerminalEventMessage,
    EventHandler: for<'handler> FnMut(
        &'handler mut App,
        &'handler mut Terminal,
        Option<Event>,
    ) -> Pin<
        Box<dyn Future<Output = io::Result<EventResult>> + 'handler>,
    >,
{
    // Wait for either a terminal event or the next tick (for redraws).
    // This yields to tokio so spawned tasks (agent output, git status) can
    // make progress on this worker thread.
    let signal = tokio::select! {
        event = event_rx.recv() => {
            LoopSignal::Event(event.map(TerminalEventMessage::into_event_result))
        },
        runtime_event = app.next_runtime_event() => LoopSignal::Runtime(runtime_event),
        _ = tick.tick() => LoopSignal::Tick,
    };
    let mut handled_terminal_events = 0;
    let maybe_event = match signal {
        LoopSignal::Runtime(runtime_event) => {
            match runtime_event {
                AppRuntimeEvent::App(event) => {
                    app.apply_app_events(*event).await;
                }
                AppRuntimeEvent::Session(command) => {
                    app.apply_session_runtime_command(command).await;
                }
            }

            None
        }
        LoopSignal::Event(Some(Ok(event))) => {
            handled_terminal_events += 1;

            Some(event)
        }
        LoopSignal::Event(Some(Err(error))) => return Err(error),
        LoopSignal::Event(None) => return Err(terminal_event_channel_closed_error()),
        LoopSignal::Tick => {
            if app.refresh_sessions_if_needed().await {
                app.mark_dirty();
            }

            None
        }
    };

    if matches!(
        handle_event(app, terminal, maybe_event).await?,
        EventResult::Quit
    ) {
        return Ok(EventResult::Quit);
    }

    // Drain a bounded number of remaining queued events before re-rendering so
    // rapid key presses stay responsive without starving the next frame.
    let remaining_terminal_event_budget =
        TERMINAL_EVENT_DRAIN_BUDGET.saturating_sub(handled_terminal_events);
    for _ in 0..remaining_terminal_event_budget {
        let event = match event_rx.try_recv() {
            Ok(message) => message.into_event_result()?,
            Err(mpsc::error::TryRecvError::Empty) => break,
            Err(mpsc::error::TryRecvError::Disconnected) => {
                return Err(terminal_event_channel_closed_error());
            }
        };

        handled_terminal_events += 1;
        if matches!(
            handle_event(app, terminal, Some(event)).await?,
            EventResult::Quit
        ) {
            return Ok(EventResult::Quit);
        }
    }

    let remaining_events = event_rx.len();
    if remaining_events > 0 {
        debug!(
            budget = TERMINAL_EVENT_DRAIN_BUDGET,
            handled_terminal_events,
            remaining_events,
            "terminal event drain budget exhausted with queued events remaining"
        );
    }

    Ok(EventResult::Continue)
}

/// Routes a single terminal event to the active mode handler.
///
/// `Event::Paste` is handled in text-input modes so multiline clipboard
/// content is inserted as text instead of interpreted as navigation keys.
async fn process_event<B: Backend>(
    app: &mut App,
    presentation: Rc<PresentationState>,
    terminal: &mut Terminal<B>,
    event: Option<Event>,
) -> io::Result<EventResult>
where
    B::Error: std::error::Error + Send + Sync + 'static,
{
    process_event_with_key_handler(app, terminal, event, |app, terminal, key| {
        let presentation = Rc::clone(&presentation);

        Box::pin(async move {
            key_handler::handle_key_event(app, presentation.as_ref(), terminal, key).await
        })
    })
    .await
}

/// Routes one terminal event with an injected key handler for deterministic
/// branch tests.
async fn process_event_with_key_handler<Terminal, KeyHandler>(
    app: &mut App,
    terminal: &mut Terminal,
    event: Option<Event>,
    mut handle_key_event: KeyHandler,
) -> io::Result<EventResult>
where
    KeyHandler: for<'handler> FnMut(
        &'handler mut App,
        &'handler mut Terminal,
        KeyEvent,
    ) -> Pin<
        Box<dyn Future<Output = io::Result<EventResult>> + 'handler>,
    >,
{
    if let Some(event) = event {
        match event {
            Event::Key(key) if is_press_key_event(key) => {
                return handle_key_event(app, terminal, key).await;
            }
            Event::Paste(pasted_text) => {
                process_paste_event(app, &pasted_text).await;
                app.mark_dirty();
            }
            _ => {}
        }
    }

    Ok(EventResult::Continue)
}

/// Returns whether the runtime should treat the key event as actionable input.
///
/// Keyboard enhancement protocols can emit release and repeat events. The TUI
/// only reacts to the initial press so higher-level mode handlers retain their
/// existing semantics.
fn is_press_key_event(key: KeyEvent) -> bool {
    key.kind == KeyEventKind::Press
}

/// Applies one pasted-text event to the active editable input.
async fn process_paste_event(app: &mut App, pasted_text: &str) {
    if matches!(&app.mode, AppMode::Prompt { .. }) {
        mode::prompt::handle_paste(app, pasted_text).await;
    }

    if matches!(&app.mode, AppMode::Question { .. }) {
        mode::question::handle_paste(app, pasted_text);
    }

    if matches!(&app.mode, AppMode::Diff { .. }) {
        mode::diff::handle_paste(app, pasted_text);
    }

    if let AppMode::PublishBranchInput {
        input,
        locked_upstream_ref: None,
        ..
    } = &mut app.mode
    {
        let text = mode::input_key::normalize_single_line_pasted_text(pasted_text);
        input.apply(InputCommand::InsertText(text));
    }

    if matches!(&app.mode, AppMode::List)
        && let Some(action) = app.settings_presentation.action_for_paste(pasted_text)
    {
        let view = app.settings.view();
        let _ = app.settings_presentation.apply(&view, action);
    }
}

#[cfg(test)]
mod tests {
    use std::io::ErrorKind;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
    use mockall::Sequence;
    use mockall::predicate::eq;

    use super::*;
    use crate::app::AppEvent;
    use crate::domain::input::InputState;
    use crate::domain::question::QuestionItem;
    use crate::domain::session::{Session, SessionRole, SessionSize, SessionStats, Status};
    use crate::domain::transient_message::TransientMessageStore;
    use crate::presentation::app_mode::{
        AppMode, ChatFocus, DiffFocus, DiffLineCommentAnchor, DiffLineComments, DiffLineSide,
        DiffPreview,
    };
    use crate::presentation::prompt::{
        PromptAttachmentState, PromptHistoryState, PromptSlashState,
    };
    use crate::presentation::settings::SettingsAction;

    /// Continues a test cycle while asserting no terminal event was produced.
    fn continue_without_terminal_event<'handler>(
        _app: &'handler mut App,
        _terminal: &'handler mut (),
        event: Option<Event>,
    ) -> Pin<Box<dyn Future<Output = io::Result<EventResult>> + 'handler>> {
        assert_eq!(
            event.into_iter().count(),
            0,
            "reader failures must not become events"
        );

        Box::pin(std::future::ready(Ok(EventResult::Continue)))
    }

    /// Continues after a key event without applying mode behavior.
    fn continue_for_key_event<'handler>(
        _app: &'handler mut App,
        _terminal: &'handler mut (),
        _key: KeyEvent,
    ) -> Pin<Box<dyn Future<Output = io::Result<EventResult>> + 'handler>> {
        Box::pin(std::future::ready(Ok(EventResult::Continue)))
    }

    /// Verifies the production reader wiring honors a pre-requested shutdown
    /// without polling the concrete terminal source.
    #[test]
    fn test_spawn_event_reader_exits_when_shutdown_is_already_requested() {
        // Arrange
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        let shutdown = Arc::new(AtomicBool::new(true));

        // Act
        let join_result = spawn_event_reader(event_tx, shutdown).join();

        // Assert
        assert!(join_result.is_ok());
        assert!(event_rx.try_recv().is_err());
    }

    /// Verifies the event reader forwards one queued event before stopping on
    /// a poll error.
    #[tokio::test]
    async fn test_spawn_event_reader_with_source_forwards_event_to_channel() {
        // Arrange
        let mut mock_source = MockEventSource::new();
        let mut sequence = Sequence::new();
        mock_source
            .expect_poll()
            .with(eq(FRAME_INTERVAL))
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Ok(true));
        mock_source
            .expect_read()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|| {
                Ok(Event::Key(KeyEvent::new(
                    KeyCode::Char('x'),
                    KeyModifiers::NONE,
                )))
            });
        mock_source
            .expect_poll()
            .with(eq(FRAME_INTERVAL))
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Err(io::Error::new(ErrorKind::BrokenPipe, "stop")));
        let event_source: Arc<dyn EventSource> = Arc::new(mock_source);
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        let shutdown = Arc::new(AtomicBool::new(false));

        // Act
        let join_handle = spawn_event_reader_with_source(event_source, event_tx, shutdown);
        let received_event = tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
            .await
            .expect("timed out waiting for event")
            .expect("failed to receive event")
            .expect("event reader returned an error");
        join_handle
            .join()
            .expect("failed to join event reader thread");

        // Assert
        assert!(matches!(received_event, Event::Key(_)));
    }

    /// Verifies the reader exits cleanly when the event receiver is already
    /// gone.
    #[test]
    fn test_spawn_event_reader_with_source_stops_when_receiver_is_dropped() {
        // Arrange
        let mut mock_source = MockEventSource::new();
        mock_source
            .expect_poll()
            .with(eq(FRAME_INTERVAL))
            .times(1)
            .returning(|_| Ok(true));
        mock_source.expect_read().times(1).returning(|| {
            Ok(Event::Key(KeyEvent::new(
                KeyCode::Char('x'),
                KeyModifiers::NONE,
            )))
        });
        let event_source: Arc<dyn EventSource> = Arc::new(mock_source);
        let (event_tx, event_rx) = mpsc::unbounded_channel();
        drop(event_rx);
        let shutdown = Arc::new(AtomicBool::new(false));

        // Act
        let join_handle = spawn_event_reader_with_source(event_source, event_tx, shutdown);
        let join_result = join_handle.join();

        // Assert
        assert!(join_result.is_ok());
    }

    /// Verifies an interrupted poll is retried before a later fatal failure is
    /// forwarded.
    #[test]
    fn test_spawn_event_reader_with_source_retries_interrupted_poll() {
        // Arrange
        let mut mock_source = MockEventSource::new();
        let mut sequence = Sequence::new();
        mock_source
            .expect_poll()
            .with(eq(FRAME_INTERVAL))
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Err(io::Error::new(ErrorKind::Interrupted, "retry")));
        mock_source
            .expect_poll()
            .with(eq(FRAME_INTERVAL))
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Err(io::Error::new(ErrorKind::BrokenPipe, "stop")));
        mock_source.expect_read().times(0);
        let event_source: Arc<dyn EventSource> = Arc::new(mock_source);
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        let shutdown = Arc::new(AtomicBool::new(false));

        // Act
        let join_handle = spawn_event_reader_with_source(event_source, event_tx, shutdown);
        let join_result = join_handle.join();
        let queued_error = event_rx
            .try_recv()
            .expect("fatal poll failure should be forwarded after retry")
            .expect_err("reader should forward the fatal poll error");

        // Assert
        assert!(join_result.is_ok());
        assert_eq!(queued_error.kind(), ErrorKind::BrokenPipe);
        assert_eq!(queued_error.to_string(), "stop");
        assert!(event_rx.try_recv().is_err());
    }

    /// Verifies a false poll result skips reads before forwarding the next
    /// fatal poll failure.
    #[test]
    fn test_spawn_event_reader_with_source_forwards_poll_error_after_empty_poll() {
        // Arrange
        let mut mock_source = MockEventSource::new();
        let mut sequence = Sequence::new();
        mock_source
            .expect_poll()
            .with(eq(FRAME_INTERVAL))
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Ok(false));
        mock_source
            .expect_poll()
            .with(eq(FRAME_INTERVAL))
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Err(io::Error::new(ErrorKind::BrokenPipe, "stop")));
        mock_source.expect_read().times(0);
        let event_source: Arc<dyn EventSource> = Arc::new(mock_source);
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        let shutdown = Arc::new(AtomicBool::new(false));

        // Act
        let join_handle = spawn_event_reader_with_source(event_source, event_tx, shutdown);
        let join_result = join_handle.join();
        let queued_error = event_rx
            .try_recv()
            .expect("poll failure should be forwarded")
            .expect_err("reader should forward the poll error");

        // Assert
        assert!(join_result.is_ok());
        assert_eq!(queued_error.kind(), ErrorKind::BrokenPipe);
        assert_eq!(queued_error.to_string(), "stop");
    }

    /// Verifies an interrupted read is retried from polling instead of being
    /// forwarded to the runtime.
    #[test]
    fn test_spawn_event_reader_with_source_retries_interrupted_read() {
        // Arrange
        let mut mock_source = MockEventSource::new();
        let mut sequence = Sequence::new();
        mock_source
            .expect_poll()
            .with(eq(FRAME_INTERVAL))
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Ok(true));
        mock_source
            .expect_read()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|| Err(io::Error::new(ErrorKind::Interrupted, "retry")));
        mock_source
            .expect_poll()
            .with(eq(FRAME_INTERVAL))
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Err(io::Error::new(ErrorKind::BrokenPipe, "stop")));
        let event_source: Arc<dyn EventSource> = Arc::new(mock_source);
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        let shutdown = Arc::new(AtomicBool::new(false));

        // Act
        let join_handle = spawn_event_reader_with_source(event_source, event_tx, shutdown);
        let join_result = join_handle.join();
        let queued_error = event_rx
            .try_recv()
            .expect("fatal poll failure should be forwarded after read retry")
            .expect_err("reader should forward the fatal poll error");

        // Assert
        assert!(join_result.is_ok());
        assert_eq!(queued_error.kind(), ErrorKind::BrokenPipe);
        assert_eq!(queued_error.to_string(), "stop");
        assert!(event_rx.try_recv().is_err());
    }

    /// Verifies terminal read failures are forwarded before the reader exits.
    #[test]
    fn test_spawn_event_reader_with_source_forwards_read_error() {
        // Arrange
        let mut mock_source = MockEventSource::new();
        mock_source
            .expect_poll()
            .with(eq(FRAME_INTERVAL))
            .once()
            .returning(|_| Ok(true));
        mock_source
            .expect_read()
            .once()
            .returning(|| Err(io::Error::new(ErrorKind::BrokenPipe, "read failed")));
        let event_source: Arc<dyn EventSource> = Arc::new(mock_source);
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        let shutdown = Arc::new(AtomicBool::new(false));

        // Act
        let join_handle = spawn_event_reader_with_source(event_source, event_tx, shutdown);
        let join_result = join_handle.join();
        let queued_error = event_rx
            .try_recv()
            .expect("read failure should be forwarded")
            .expect_err("reader should forward the read error");

        // Assert
        assert!(join_result.is_ok());
        assert_eq!(queued_error.kind(), ErrorKind::BrokenPipe);
        assert_eq!(queued_error.to_string(), "read failed");
    }

    /// Verifies a pre-set shutdown flag exits the reader without touching the
    /// event source.
    #[test]
    fn test_spawn_event_reader_with_source_exits_when_shutdown_is_already_requested() {
        // Arrange
        let mut mock_source = MockEventSource::new();
        mock_source.expect_poll().times(0);
        mock_source.expect_read().times(0);
        let event_source: Arc<dyn EventSource> = Arc::new(mock_source);
        let (event_tx, _event_rx) = mpsc::unbounded_channel();
        let shutdown = Arc::new(AtomicBool::new(true));

        // Act
        let join_handle = spawn_event_reader_with_source(event_source, event_tx, shutdown);
        let join_result = join_handle.join();

        // Assert
        assert!(join_result.is_ok());
    }

    /// Verifies pasted text is routed into prompt input without invoking the
    /// key handler.
    #[tokio::test]
    async fn test_process_event_with_key_handler_pastes_into_prompt_mode() {
        // Arrange
        let mut app = crate::test_support::new_test_app_without_retained_base_dir().await;
        let session_id = "session-1".to_string();
        app.sessions.push_session(Session {
            base_branch: "main".to_string(),
            created_at: 0,
            draft_attachments: Vec::new(),
            folder: std::env::temp_dir(),
            follow_up_tasks: Vec::new(),
            id: session_id.clone().into(),
            in_progress_started_at: None,
            in_progress_total_seconds: 0,
            is_draft: false,
            controller_session_id: None,
            orchestration_progress: None,
            role: SessionRole::default(),
            agent: crate::domain::agent::AgentSelection::new(
                crate::domain::agent::AgentKind::Antigravity,
                crate::domain::agent::AgentKind::Antigravity.default_model(),
            ),
            parent_session_id: None,
            personality_id: None,
            project_name: "project".to_string(),
            prompt: String::new(),
            queued_messages: Vec::new(),
            reasoning_level_override: None,
            published_upstream_ref: None,
            questions: Vec::new(),
            review_request: None,
            size: SessionSize::Xs,
            speed_mode: crate::domain::agent::SpeedMode::default(),
            stats: SessionStats::default(),
            status: Status::Draft,
            summary: None,
            title: None,
            transcript: None,
            updated_at: 0,
            transient_messages: TransientMessageStore::default(),
        });
        app.mode = AppMode::Prompt {
            at_mention_state: None,
            attachment_state: PromptAttachmentState::default(),
            focus: ChatFocus::Input,
            history_state: PromptHistoryState::default(),
            input: InputState::default(),
            scroll_offset: None,
            session_id: session_id.into(),
            slash_state: PromptSlashState::default(),
        };
        let mut terminal = ();

        // Act
        let result = process_event_with_key_handler(
            &mut app,
            &mut terminal,
            Some(Event::Paste("    line 1\r\n        line 2".to_string())),
            |_, (), _| Box::pin(async { Err(io::Error::other("unexpected key-handler call")) }),
        )
        .await;

        // Assert
        assert!(matches!(result, Ok(EventResult::Continue)));
        assert!(
            matches!(&app.mode, AppMode::Prompt { input, .. } if input.text() == "    line 1\n        line 2")
        );
    }

    /// Verifies pasted text updates question input in free-text mode.
    #[tokio::test]
    async fn test_process_event_with_key_handler_pastes_into_question_free_text_mode() {
        // Arrange — paste only works in free-text mode (`selected_option_index`
        // is `None`).
        let mut app = crate::test_support::new_test_app_without_retained_base_dir().await;
        app.mode = AppMode::Question {
            at_mention_state: None,
            current_index: 0,
            focus: ChatFocus::Input,
            input: InputState::default(),
            scroll_offset: None,
            questions: vec![QuestionItem {
                options: vec!["yes".to_string()],
                text: "Is this enough?".to_string(),
            }],
            responses: Vec::new(),
            selected_option_index: None,
            session_id: "session-1".into(),
        };
        let mut terminal = ();

        // Act
        let result = process_event_with_key_handler(
            &mut app,
            &mut terminal,
            Some(Event::Paste("custom\ranswer".to_string())),
            |_, (), _| Box::pin(async { Err(io::Error::other("unexpected key-handler call")) }),
        )
        .await;

        // Assert
        assert!(matches!(result, Ok(EventResult::Continue)));
        assert!(matches!(
            &app.mode,
            AppMode::Question {
                input,
                selected_option_index: None,
                ..
            } if input.text() == "custom\nanswer"
        ));
    }

    #[tokio::test]
    async fn test_process_event_with_key_handler_pastes_into_inline_diff_comment() {
        // Arrange
        let mut app = crate::test_support::new_test_app_without_retained_base_dir().await;
        let mut line_comments = DiffLineComments::default();
        line_comments.start_editing(DiffLineCommentAnchor {
            content: "review();".to_string(),
            line: 1,
            path: "src/main.rs".to_string(),
            side: DiffLineSide::New,
        });
        app.mode = AppMode::Diff {
            diff: "diff --git a/src/main.rs b/src/main.rs\n+review();\n".to_string(),
            file_explorer_selected_index: 1,
            focus: DiffFocus::Content,
            line_comments,
            preview: DiffPreview::default(),
            review_comments: None,
            restore: None,
            scroll_cache: None,
            scroll_offset: 0,
            selected_diff_line_index: 0,
            session_id: "session-1".into(),
        };
        let mut terminal = ();

        // Act
        let result = process_event_with_key_handler(
            &mut app,
            &mut terminal,
            Some(Event::Paste("first line\r\nsecond line".to_string())),
            continue_for_key_event,
        )
        .await;
        let key_result = process_event_with_key_handler(
            &mut app,
            &mut terminal,
            Some(Event::Key(KeyEvent::new(
                KeyCode::Char('x'),
                KeyModifiers::NONE,
            ))),
            continue_for_key_event,
        )
        .await;

        // Assert
        assert!(matches!(result, Ok(EventResult::Continue)));
        assert!(matches!(key_result, Ok(EventResult::Continue)));
        assert!(matches!(
            &app.mode,
            AppMode::Diff { line_comments, .. }
                if line_comments.comments[0].input.text() == "first line"
        ));
    }

    #[tokio::test]
    async fn test_process_paste_event_updates_publish_branch_input() {
        // Arrange
        let mut app = crate::test_support::new_test_app_without_retained_base_dir().await;
        app.mode = AppMode::PublishBranchInput {
            default_branch_name: "wt/session".to_string(),
            input: InputState::default(),
            locked_upstream_ref: None,
            publish_branch_action: crate::domain::session::PublishBranchAction::Push,
            restore_view: crate::presentation::app_mode::ConfirmationViewMode {
                scroll_offset: None,
                session_id: "session-1".into(),
            },
        };

        // Act
        process_paste_event(&mut app, "review/shared-input\r\nignored").await;

        // Assert
        assert!(matches!(
            &app.mode,
            AppMode::PublishBranchInput { input, .. }
                if input.text() == "review/shared-input"
        ));
    }

    #[tokio::test]
    async fn test_process_paste_event_updates_launch_configuration_input() {
        // Arrange
        let mut app = crate::test_support::new_test_app_without_retained_base_dir().await;
        app.tabs.set(crate::app::Tab::Settings);
        for _ in 0..7 {
            let view = app.settings.view();
            let _ = app.settings_presentation.apply(&view, SettingsAction::Next);
        }
        let view = app.settings.view();
        let _ = app
            .settings_presentation
            .apply(&view, SettingsAction::Activate);
        let view = app.settings.view();
        let _ = app
            .settings_presentation
            .apply(&view, SettingsAction::StartAddingLaunchConfiguration);

        // Act
        process_paste_event(&mut app, "cargo nextest run\r\nignored").await;

        // Assert
        let editor = app
            .settings_presentation
            .snapshot(&app.settings.view())
            .launch_configuration_list_editor
            .expect("launch-configuration editor should be open");
        assert!(matches!(
            editor.input,
            Some(ref input) if input.text() == "cargo nextest run"
        ));
    }

    /// Verifies non-key terminal events are ignored by the runtime handler.
    #[tokio::test]
    async fn test_process_event_with_key_handler_ignores_resize_events() {
        // Arrange
        let mut app = crate::test_support::new_test_app_without_retained_base_dir().await;
        let original_mode = AppMode::List;
        app.mode = original_mode;
        let mut terminal = ();

        // Act
        let result = process_event_with_key_handler(
            &mut app,
            &mut terminal,
            Some(Event::Resize(120, 40)),
            |_, (), _| Box::pin(async { Err(io::Error::other("unexpected key-handler call")) }),
        )
        .await;

        // Assert
        assert!(matches!(result, Ok(EventResult::Continue)));
        assert!(matches!(&app.mode, AppMode::List));
    }

    /// Verifies key release events are ignored even when keyboard enhancement
    /// flags make them visible to the runtime.
    #[tokio::test]
    async fn test_process_event_with_key_handler_ignores_key_release_events() {
        // Arrange
        let mut app = crate::test_support::new_test_app_without_retained_base_dir().await;
        let mut terminal = ();

        // Act
        let result = process_event_with_key_handler(
            &mut app,
            &mut terminal,
            Some(Event::Key(KeyEvent::new_with_kind(
                KeyCode::Enter,
                KeyModifiers::ALT,
                KeyEventKind::Release,
            ))),
            |_, (), _| Box::pin(async { Err(io::Error::other("unexpected key-handler call")) }),
        )
        .await;

        // Assert
        assert!(matches!(result, Ok(EventResult::Continue)));
    }

    /// Verifies handler errors terminate the outer event-processing cycle.
    #[tokio::test]
    async fn test_process_events_with_handler_returns_handler_error() {
        // Arrange
        let mut app = crate::test_support::new_test_app_without_retained_base_dir().await;
        let mut terminal = ();
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        event_tx
            .send(Ok(Event::Key(KeyEvent::new(
                KeyCode::Char('x'),
                KeyModifiers::NONE,
            ))))
            .expect("failed to queue event");
        let mut tick = tokio::time::interval(Duration::from_mins(1));

        // Act
        let result = process_events_with_handler(
            &mut app,
            &mut terminal,
            &mut event_rx,
            &mut tick,
            |_, (), _| Box::pin(async { Err(io::Error::other("handler failed")) }),
        )
        .await;

        // Assert
        assert!(result.is_err());
        let error = result
            .err()
            .expect("handler error should exit the event loop");
        assert_eq!(error.to_string(), "handler failed");
    }

    /// Verifies a terminal reader failure exits the event cycle without being
    /// converted into a terminal event.
    #[tokio::test]
    async fn test_process_events_with_handler_returns_reader_error() {
        // Arrange
        let mut app = crate::test_support::new_test_app_without_retained_base_dir().await;
        let mut terminal = ();
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        let mut tick = tokio::time::interval(Duration::from_mins(1));
        let initial_result = process_events_with_handler(
            &mut app,
            &mut terminal,
            &mut event_rx,
            &mut tick,
            continue_without_terminal_event,
        )
        .await;
        event_tx
            .send(Err(io::Error::new(ErrorKind::BrokenPipe, "reader failed")))
            .expect("failed to queue reader error");

        // Act
        let result = process_events_with_handler(
            &mut app,
            &mut terminal,
            &mut event_rx,
            &mut tick,
            continue_without_terminal_event,
        )
        .await;

        // Assert
        assert!(matches!(initial_result, Ok(EventResult::Continue)));
        let error = result
            .err()
            .expect("reader failure should exit the event cycle");
        assert_eq!(error.kind(), ErrorKind::BrokenPipe);
        assert_eq!(error.to_string(), "reader failed");
    }

    /// Verifies a closed terminal channel exits instead of spinning through
    /// no-input cycles.
    #[tokio::test]
    async fn test_process_events_with_handler_returns_error_when_reader_channel_closes() {
        // Arrange
        let mut app = crate::test_support::new_test_app_without_retained_base_dir().await;
        let mut terminal = ();
        let (event_tx, mut event_rx) = mpsc::unbounded_channel::<io::Result<Event>>();
        let mut tick = tokio::time::interval(Duration::from_mins(1));
        let initial_result = process_events_with_handler(
            &mut app,
            &mut terminal,
            &mut event_rx,
            &mut tick,
            continue_without_terminal_event,
        )
        .await;
        drop(event_tx);

        // Act
        let result = process_events_with_handler(
            &mut app,
            &mut terminal,
            &mut event_rx,
            &mut tick,
            continue_without_terminal_event,
        )
        .await;

        // Assert
        assert!(matches!(initial_result, Ok(EventResult::Continue)));
        let error = result
            .err()
            .expect("closed reader channel should exit the event cycle");
        assert_eq!(error.kind(), ErrorKind::UnexpectedEof);
        assert_eq!(error.to_string(), "terminal event reader stopped");
    }

    #[tokio::test]
    async fn test_process_events_with_handler_drives_session_runtime_commands() {
        // Arrange
        let mut app = crate::test_support::new_test_app_without_retained_base_dir().await;
        let mut terminal = ();
        let (_event_tx, mut event_rx) = mpsc::unbounded_channel::<Event>();
        let mut tick = tokio::time::interval(Duration::from_mins(1));
        tick.tick().await;
        let _session_runtime_consumer = app.sessions.foreground_consumer();
        let service = app.session_service();
        let lookup = tokio::spawn(async move {
            service
                .get_session(&ag_session::SessionId::from("missing"))
                .await
        });

        // Act
        let result = tokio::time::timeout(Duration::from_secs(1), async {
            loop {
                let result = process_events_with_handler(
                    &mut app,
                    &mut terminal,
                    &mut event_rx,
                    &mut tick,
                    |_, (), event| {
                        assert!(event.is_none());

                        Box::pin(async { Ok(EventResult::Continue) })
                    },
                )
                .await;
                assert!(matches!(&result, Ok(EventResult::Continue)));

                tokio::task::yield_now().await;
                if lookup.is_finished() {
                    break result;
                }
            }
        })
        .await
        .expect("runtime should process the session command");
        let session = lookup
            .await
            .expect("lookup task should finish")
            .expect("lookup should succeed");

        // Assert
        assert!(matches!(result, Ok(EventResult::Continue)));
        assert_eq!(session, None);
    }

    #[tokio::test]
    async fn test_process_events_with_handler_drives_app_runtime_events() {
        // Arrange
        let mut app = crate::test_support::new_test_app_without_retained_base_dir().await;
        app.services.emit_app_event(AppEvent::RefreshSessions);
        let mut terminal = ();
        let (_event_tx, mut event_rx) = mpsc::unbounded_channel::<Event>();
        let mut tick = tokio::time::interval(Duration::from_mins(1));
        tick.tick().await;

        // Act
        let result = process_events_with_handler(
            &mut app,
            &mut terminal,
            &mut event_rx,
            &mut tick,
            |_, (), event| {
                assert!(event.is_none());

                Box::pin(async { Ok(EventResult::Continue) })
            },
        )
        .await;

        // Assert
        assert!(matches!(result, Ok(EventResult::Continue)));
    }

    /// Verifies queued terminal events beyond the foreground budget stay in
    /// the channel for the next render cycle.
    #[tokio::test]
    async fn test_process_events_with_handler_keeps_events_over_budget_queued() {
        // Arrange
        let mut app = crate::test_support::new_test_app_without_retained_base_dir().await;
        let mut terminal = ();
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        for _ in 0..(TERMINAL_EVENT_DRAIN_BUDGET + 2) {
            event_tx
                .send(Ok(Event::Key(KeyEvent::new(
                    KeyCode::Char('x'),
                    KeyModifiers::NONE,
                ))))
                .expect("failed to queue event");
        }
        let handled_events = Arc::new(AtomicUsize::new(0));
        let mut tick = tokio::time::interval(Duration::from_mins(1));

        // Act
        let result =
            process_events_with_handler(&mut app, &mut terminal, &mut event_rx, &mut tick, {
                let handled_events = Arc::clone(&handled_events);

                move |_, (), event| {
                    if event.is_some() {
                        handled_events.fetch_add(1, Ordering::Relaxed);
                    }

                    Box::pin(async { Ok(EventResult::Continue) })
                }
            })
            .await;

        // Assert
        assert!(matches!(result, Ok(EventResult::Continue)));
        assert_eq!(
            handled_events.load(Ordering::Relaxed),
            TERMINAL_EVENT_DRAIN_BUDGET
        );
        assert_eq!(event_rx.len(), 2);
    }

    /// Verifies channel closure noticed while draining queued input exits the
    /// event cycle after handling the final event.
    #[tokio::test]
    async fn test_process_events_with_handler_returns_error_when_channel_closes_during_drain() {
        // Arrange
        let mut app = crate::test_support::new_test_app_without_retained_base_dir().await;
        let mut terminal = ();
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        event_tx
            .send(Ok(Event::Key(KeyEvent::new(
                KeyCode::Char('x'),
                KeyModifiers::NONE,
            ))))
            .expect("failed to queue event");
        drop(event_tx);
        let handled_events = Arc::new(AtomicUsize::new(0));
        let mut tick = tokio::time::interval(Duration::from_mins(1));
        tick.tick().await;

        // Act
        let result =
            process_events_with_handler(&mut app, &mut terminal, &mut event_rx, &mut tick, {
                let handled_events = Arc::clone(&handled_events);

                move |_, (), event| {
                    if event.is_some() {
                        handled_events.fetch_add(1, Ordering::Relaxed);
                    }

                    Box::pin(async { Ok(EventResult::Continue) })
                }
            })
            .await;

        // Assert
        let error = result
            .err()
            .expect("closed reader channel should exit during drain");
        assert_eq!(error.kind(), ErrorKind::UnexpectedEof);
        assert_eq!(handled_events.load(Ordering::Relaxed), 1);
    }
}