agentty 0.11.1

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
use std::future::Future;
use std::io;
use std::pin::Pin;
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, AppEvent};
use crate::runtime::{EventResult, FRAME_INTERVAL, key_handler, mode};
use crate::ui::state::app_mode::AppMode;

/// 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 pending app-side event routed through the internal bus.
    AppEvent(Box<Option<AppEvent>>),
    /// One terminal input event from the foreground reader thread.
    Event(Option<Event>),
    /// One redraw tick with no immediate input payload.
    Tick,
}

/// Spawns the terminal event reader thread with production dependencies.
pub(crate) fn spawn_event_reader(
    event_tx: mpsc::UnboundedSender<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<Event>,
    shutdown: Arc<AtomicBool>,
) -> std::thread::JoinHandle<()> {
    std::thread::spawn(move || {
        loop {
            if shutdown.load(Ordering::Relaxed) {
                break;
            }

            match event_source.poll(FRAME_INTERVAL) {
                Ok(true) => {
                    if let Ok(event) = event_source.read()
                        && event_tx.send(event).is_err()
                    {
                        break;
                    }
                }
                Ok(false) => {}
                Err(_) => break,
            }
        }
    })
}

/// Waits for the next terminal/app event or tick and dispatches one runtime
/// processing cycle.
pub(crate) async fn process_events<B: Backend>(
    app: &mut App,
    terminal: &mut Terminal<B>,
    event_rx: &mut mpsc::UnboundedReceiver<Event>,
    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| {
        Box::pin(process_event(app, 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, EventHandler>(
    app: &mut App,
    terminal: &mut Terminal,
    event_rx: &mut mpsc::UnboundedReceiver<Event>,
    tick: &mut tokio::time::Interval,
    mut handle_event: EventHandler,
) -> io::Result<EventResult>
where
    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),
        app_event = app.next_app_event() => LoopSignal::AppEvent(Box::new(app_event)),
        _ = tick.tick() => LoopSignal::Tick,
    };
    let mut handled_terminal_events = 0;
    let maybe_event = match signal {
        LoopSignal::AppEvent(app_event) => {
            if let Some(event) = *app_event {
                app.apply_app_events(event).await;
            }

            None
        }
        LoopSignal::Event(event) => {
            if event.is_some() {
                handled_terminal_events += 1;
            }

            event
        }
        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 Ok(event) = event_rx.try_recv() else {
            break;
        };

        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,
    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| {
        Box::pin(key_handler::handle_key_event(app, terminal, key))
    })
    .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);
                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 prompt or question input.
fn process_paste_event(app: &mut App, pasted_text: &str) {
    if matches!(&app.mode, AppMode::Prompt { .. }) {
        mode::prompt::handle_paste(app, pasted_text);
    }

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

#[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 tempfile::tempdir;

    use super::*;
    use crate::db::Database;
    use crate::domain::agent::AgentKind;
    use crate::domain::input::InputState;
    use crate::domain::question::QuestionItem;
    use crate::domain::session::{Session, SessionSize, SessionStats, Status};
    use crate::ui::state::app_mode::{AppMode, QuestionFocus};
    use crate::ui::state::prompt::{PromptAttachmentState, PromptHistoryState, PromptSlashState};

    /// Builds one client bundle with deterministic agent availability for
    /// test app startup.
    fn test_app_clients() -> crate::app::AppClients {
        crate::app::AppClients::new().with_agent_availability_probe(std::sync::Arc::new(
            crate::infra::agent::StaticAgentAvailabilityProbe {
                available_agent_kinds: AgentKind::ALL.to_vec(),
            },
        ))
    }

    /// Builds one test app rooted at a temporary directory.
    async fn new_test_app() -> App {
        let base_dir = tempdir().expect("failed to create temp dir");
        let base_path = base_dir.path().to_path_buf();
        let database = Database::open_in_memory()
            .await
            .expect("failed to open in-memory db");

        App::new_with_clients(
            base_path.clone(),
            base_path,
            None,
            database,
            test_app_clients(),
        )
        .await
        .expect("failed to build app")
    }

    /// 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::Interrupted, "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");
        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 a false poll result skips reads and leaves the channel empty.
    #[test]
    fn test_spawn_event_reader_with_source_skips_read_when_poll_returns_false() {
        // 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::Interrupted, "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_event = event_rx.try_recv();

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

    /// 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 = new_test_app().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,
            agent: crate::domain::agent::AgentSelection::new(
                crate::domain::agent::AgentKind::Antigravity,
                crate::domain::agent::AgentKind::Antigravity.default_model(),
            ),
            output: String::new(),
            parent_session_id: None,
            project_name: "project".to_string(),
            prompt: String::new(),
            queued_messages: Vec::new(),
            reasoning_level_override: None,
            published_upstream_ref: None,
            published_branch_sync_status: crate::domain::session::PublishedBranchSyncStatus::Idle,
            questions: Vec::new(),
            review_request: None,
            size: SessionSize::Xs,
            stats: SessionStats::default(),
            status: Status::Draft,
            summary: None,
            title: None,
            updated_at: 0,
            workflow_notice: None,
        });
        app.mode = AppMode::Prompt {
            at_mention_state: None,
            attachment_state: PromptAttachmentState::default(),
            history_state: PromptHistoryState::default(),
            input: InputState::default(),
            review_status_message: None,
            review_text: None,
            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\nline 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\nline 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 = new_test_app().await;
        app.mode = AppMode::Question {
            at_mention_state: None,
            current_index: 0,
            focus: QuestionFocus::Answer,
            input: InputState::default(),
            review_status_message: None,
            review_text: None,
            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"
        ));
    }

    /// 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 = new_test_app().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 = new_test_app().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 = new_test_app().await;
        let mut terminal = ();
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        event_tx
            .send(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 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 = new_test_app().await;
        let mut terminal = ();
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        for _ in 0..(TERMINAL_EVENT_DRAIN_BUDGET + 2) {
            event_tx
                .send(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);
    }
}