logana 0.5.1

Turn any log source — files, compressed archives, Docker, or OTel streams — into structured data. Filter by pattern, field, or date range; annotate lines; bookmark findings; and export to Markdown, Jira, or AI assistants via the built-in MCP server.
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
use crate::{
    config::Keybindings,
    mode::app_mode::{Mode, ModeRenderState, status_entry},
    mode::comment_mode::CommentMode,
    mode::normal_mode::NormalMode,
    mode::search_mode::SearchMode,
    theme::Theme,
    ui::{KeyResult, TabState, field_layout::apply_field_layout},
};
use async_trait::async_trait;
use crossterm::event::{KeyCode, KeyModifiers};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};

#[derive(Debug)]
pub struct VisualLineMode {
    /// Index into `visible_indices` that was the cursor when `V` was pressed.
    pub anchor: usize,
    /// Vim-style count prefix for multi-line motions.
    pub count: Option<usize>,
}

#[async_trait]
impl Mode for VisualLineMode {
    async fn handle_key(
        mut self: Box<Self>,
        tab: &mut TabState,
        key: KeyCode,
        modifiers: KeyModifiers,
    ) -> (Box<dyn Mode>, KeyResult) {
        let kb = &tab.interaction.keybindings;

        // ── Digit accumulation for count prefix ─────────────────────────
        if let KeyCode::Char(c @ '1'..='9') = key
            && (modifiers.is_empty() || modifiers == KeyModifiers::SHIFT)
        {
            let digit = (c as u32 - '0' as u32) as usize;
            let n = self
                .count
                .unwrap_or(0)
                .saturating_mul(10)
                .saturating_add(digit);
            self.count = Some(n.min(999_999));
            return (self, KeyResult::Handled);
        }
        if let KeyCode::Char('0') = key
            && self.count.is_some()
            && (modifiers.is_empty() || modifiers == KeyModifiers::SHIFT)
        {
            self.count = Some(self.count.unwrap().saturating_mul(10).min(999_999));
            return (self, KeyResult::Handled);
        }

        if kb.navigation.scroll_down.matches(key, modifiers) {
            let count = self.count.take().unwrap_or(1);
            tab.scroll.scroll_offset = tab.scroll.scroll_offset.saturating_add(count);
            tab.interaction.g_key_pressed = false;
        } else if kb.navigation.scroll_up.matches(key, modifiers) {
            let count = self.count.take().unwrap_or(1);
            tab.scroll.scroll_offset = tab.scroll.scroll_offset.saturating_sub(count);
            tab.interaction.g_key_pressed = false;
        } else if kb.navigation.half_page_down.matches(key, modifiers) {
            let half = (tab.scroll.visible_height / 2).max(1);
            let count = self.count.take().unwrap_or(1);
            tab.scroll.scroll_offset = tab
                .scroll
                .scroll_offset
                .saturating_add(half.saturating_mul(count));
            tab.interaction.g_key_pressed = false;
        } else if kb.navigation.half_page_up.matches(key, modifiers) {
            let half = (tab.scroll.visible_height / 2).max(1);
            let count = self.count.take().unwrap_or(1);
            tab.scroll.scroll_offset = tab
                .scroll
                .scroll_offset
                .saturating_sub(half.saturating_mul(count));
            tab.interaction.g_key_pressed = false;
        } else if kb.navigation.page_down.matches(key, modifiers) {
            let page = tab.scroll.visible_height.max(1);
            let count = self.count.take().unwrap_or(1);
            tab.scroll.scroll_offset = tab
                .scroll
                .scroll_offset
                .saturating_add(page.saturating_mul(count));
            tab.interaction.g_key_pressed = false;
        } else if kb.navigation.page_up.matches(key, modifiers) {
            let page = tab.scroll.visible_height.max(1);
            let count = self.count.take().unwrap_or(1);
            tab.scroll.scroll_offset = tab
                .scroll
                .scroll_offset
                .saturating_sub(page.saturating_mul(count));
            tab.interaction.g_key_pressed = false;
        } else if kb.normal.go_to_bottom.matches(key, modifiers) {
            if let Some(count) = self.count.take() {
                let _ = tab.goto_line(count);
            } else {
                let n = tab.filter.visible_indices.len();
                if n > 0 {
                    tab.scroll.scroll_offset = n - 1;
                }
            }
            tab.interaction.g_key_pressed = false;
        } else if kb.normal.go_to_top_chord.matches(key, modifiers) {
            if tab.interaction.g_key_pressed {
                if let Some(count) = self.count.take() {
                    let _ = tab.goto_line(count);
                } else {
                    tab.scroll.scroll_offset = 0;
                }
                tab.interaction.g_key_pressed = false;
            } else {
                tab.interaction.g_key_pressed = true;
            }
        } else if kb.visual_line.comment.matches(key, modifiers) {
            tab.interaction.g_key_pressed = false;
            // Comment the selected range
            if tab.filter.visible_indices.is_empty() {
                return (Box::new(NormalMode::default()), KeyResult::Handled);
            }
            let max_idx = tab.filter.visible_indices.len() - 1;
            let lo = self.anchor.min(tab.scroll.scroll_offset).min(max_idx);
            let hi = self.anchor.max(tab.scroll.scroll_offset).min(max_idx);
            let line_indices = tab.filter.visible_indices.slice_to_vec(lo, hi);
            if !line_indices.is_empty() {
                return (Box::new(CommentMode::new(line_indices)), KeyResult::Handled);
            }
            return (Box::new(NormalMode::default()), KeyResult::Handled);
        } else if kb.visual_line.mark.matches(key, modifiers) {
            // Mark/unmark all selected lines as a group.
            // If every selected line is already marked → unmark all; otherwise → mark all.
            if !tab.filter.visible_indices.is_empty() {
                let max_idx = tab.filter.visible_indices.len() - 1;
                let lo = self.anchor.min(tab.scroll.scroll_offset).min(max_idx);
                let hi = self.anchor.max(tab.scroll.scroll_offset).min(max_idx);
                let line_indices = tab.filter.visible_indices.slice_to_vec(lo, hi);
                let all_marked = line_indices.iter().all(|&i| tab.log_manager.is_marked(i));
                if all_marked {
                    for idx in &line_indices {
                        tab.log_manager.toggle_mark(*idx);
                    }
                } else {
                    for idx in &line_indices {
                        if !tab.log_manager.is_marked(*idx) {
                            tab.log_manager.toggle_mark(*idx);
                        }
                    }
                }
            }
            return (Box::new(NormalMode::default()), KeyResult::Handled);
        } else if kb.visual_line.yank.matches(key, modifiers) {
            // Yank (copy) selected lines to clipboard
            if tab.filter.visible_indices.is_empty() {
                tab.interaction.command_error = Some("No lines to copy".to_string());
                return (Box::new(NormalMode::default()), KeyResult::Handled);
            }
            let max_idx = tab.filter.visible_indices.len() - 1;
            let lo = self.anchor.min(tab.scroll.scroll_offset).min(max_idx);
            let hi = self.anchor.max(tab.scroll.scroll_offset).min(max_idx);
            let line_indices = tab.filter.visible_indices.slice_to_vec(lo, hi);
            let text: String = line_indices
                .iter()
                .map(|&idx| {
                    let bytes = tab.file_reader.get_line(idx);
                    if tab.display.raw_mode {
                        None
                    } else {
                        tab.display.format.as_ref()
                    }
                    .and_then(|parser| parser.parse_line(bytes))
                    .map(|parts| {
                        apply_field_layout(
                            &parts,
                            &tab.display.field_layout,
                            &tab.display.hidden_fields,
                            tab.display.show_keys,
                            None,
                        )
                        .join(" ")
                    })
                    .unwrap_or_else(|| String::from_utf8_lossy(bytes).into_owned())
                })
                .collect::<Vec<_>>()
                .join("\n");
            return (
                Box::new(NormalMode::default()),
                KeyResult::CopyToClipboard(text),
            );
        } else if kb.visual_line.search.matches(key, modifiers) {
            let text = regex::escape(&lo_line_text(tab, self.anchor, tab.scroll.scroll_offset));
            return (
                Box::new(SearchMode {
                    input: text,
                    forward: true,
                }),
                KeyResult::Handled,
            );
        } else if kb.visual_line.exit.matches(key, modifiers) {
            return (Box::new(NormalMode::default()), KeyResult::Handled);
        }

        (self, KeyResult::Ignored)
    }

    fn mode_bar_content(&self, kb: &Keybindings, theme: &Theme) -> Line<'static> {
        let label = match self.count {
            Some(n) => format!("[VISUAL] {}  ", n),
            None => "[VISUAL]  ".to_string(),
        };
        let mut spans: Vec<Span<'static>> = vec![Span::styled(
            label,
            Style::default()
                .fg(theme.text_highlight_fg)
                .add_modifier(Modifier::BOLD),
        )];
        // Extend up/down
        spans.push(Span::styled("<", Style::default().fg(theme.text)));
        spans.push(Span::styled(
            kb.navigation.scroll_up.display(),
            Style::default()
                .fg(theme.text_highlight_fg)
                .add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::styled("/", Style::default().fg(theme.text)));
        spans.push(Span::styled(
            kb.navigation.scroll_down.display(),
            Style::default()
                .fg(theme.text_highlight_fg)
                .add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::styled("> extend  ", Style::default().fg(theme.text)));
        status_entry(
            &mut spans,
            kb.visual_line.comment.display(),
            "comment",
            theme,
        );
        status_entry(&mut spans, kb.visual_line.yank.display(), "yank", theme);
        status_entry(&mut spans, kb.visual_line.mark.display(), "mark", theme);
        status_entry(&mut spans, kb.visual_line.search.display(), "search", theme);
        status_entry(&mut spans, kb.visual_line.exit.display(), "cancel", theme);
        Line::from(spans)
    }

    fn render_state(&self) -> ModeRenderState {
        ModeRenderState::VisualLine {
            anchor: self.anchor,
        }
    }
}

/// Returns the displayed text of the lo line of the visual selection.
fn lo_line_text(tab: &TabState, anchor: usize, scroll_offset: usize) -> String {
    if tab.filter.visible_indices.is_empty() {
        return String::new();
    }
    let max_idx = tab.filter.visible_indices.len() - 1;
    let lo = anchor.min(scroll_offset).min(max_idx);
    let idx = tab.filter.visible_indices.get(lo);
    let bytes = tab.file_reader.get_line(idx);
    if !tab.display.raw_mode
        && let Some(parser) = tab.display.format.as_ref()
        && let Some(parts) = parser.parse_line(bytes)
    {
        return apply_field_layout(
            &parts,
            &tab.display.field_layout,
            &tab.display.hidden_fields,
            tab.display.show_keys,
            None,
        )
        .join(" ");
    }
    String::from_utf8_lossy(bytes).into_owned()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::Database;
    use crate::db::LogManager;
    use crate::ingestion::FileReader;
    use crate::mode::app_mode::ModeRenderState;
    use crate::ui::TabState;
    use std::sync::Arc;

    async fn make_tab(lines: &[&str]) -> TabState {
        let data = lines.join("\n").into_bytes();
        let file_reader = FileReader::from_bytes(data);
        let db = Arc::new(Database::in_memory().await.unwrap());
        let log_manager = LogManager::new(db, None).await;
        TabState::new(file_reader, log_manager, "test".to_string())
    }

    async fn press(
        mode: VisualLineMode,
        tab: &mut TabState,
        key: KeyCode,
    ) -> (Box<dyn Mode>, KeyResult) {
        Box::new(mode)
            .handle_key(tab, key, KeyModifiers::NONE)
            .await
    }

    #[tokio::test]
    async fn test_j_moves_cursor_down() {
        let mut tab = make_tab(&["a", "b", "c"]).await;
        tab.scroll.scroll_offset = 0;
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        let (mode2, _) = press(mode, &mut tab, KeyCode::Char('j')).await;
        assert_eq!(tab.scroll.scroll_offset, 1);
        assert!(matches!(
            mode2.render_state(),
            ModeRenderState::VisualLine { .. }
        ));
    }

    #[tokio::test]
    async fn test_k_moves_cursor_up() {
        let mut tab = make_tab(&["a", "b", "c"]).await;
        tab.scroll.scroll_offset = 2;
        let mode = VisualLineMode {
            anchor: 2,
            count: None,
        };
        let (_, _) = press(mode, &mut tab, KeyCode::Char('k')).await;
        assert_eq!(tab.scroll.scroll_offset, 1);
    }

    #[tokio::test]
    async fn test_k_saturates_at_zero() {
        let mut tab = make_tab(&["a"]).await;
        tab.scroll.scroll_offset = 0;
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        let _ = press(mode, &mut tab, KeyCode::Char('k')).await;
        assert_eq!(tab.scroll.scroll_offset, 0);
    }

    #[tokio::test]
    async fn test_esc_returns_normal_mode() {
        let mut tab = make_tab(&["a"]).await;
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        let (mode2, result) = press(mode, &mut tab, KeyCode::Esc).await;
        assert!(matches!(result, KeyResult::Handled));
        assert!(!matches!(
            mode2.render_state(),
            ModeRenderState::VisualLine { .. }
        ));
        assert!(matches!(mode2.render_state(), ModeRenderState::Normal));
    }

    #[tokio::test]
    async fn test_c_opens_comment_mode_with_selected_lines() {
        let mut tab = make_tab(&["a", "b", "c", "d"]).await;
        tab.scroll.scroll_offset = 3; // cursor at line index 3
        let mode = VisualLineMode {
            anchor: 1,
            count: None,
        }; // anchor at visible index 1
        let (mode2, result) = press(mode, &mut tab, KeyCode::Char('c')).await;
        assert!(matches!(result, KeyResult::Handled));
        // Should be in comment mode
        match mode2.render_state() {
            ModeRenderState::Comment { line_count, .. } => {
                assert_eq!(line_count, 3); // visible indices 1,2,3 → 3 lines
            }
            other => panic!("expected Comment, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_c_with_anchor_above_cursor() {
        let mut tab = make_tab(&["a", "b", "c"]).await;
        tab.scroll.scroll_offset = 0;
        let mode = VisualLineMode {
            anchor: 2,
            count: None,
        }; // anchor below cursor
        let (mode2, _) = press(mode, &mut tab, KeyCode::Char('c')).await;
        match mode2.render_state() {
            ModeRenderState::Comment { line_count, .. } => {
                assert_eq!(line_count, 3); // lines 0,1,2
            }
            other => panic!("expected Comment, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_visual_selection_anchor_returns_anchor() {
        let mode = VisualLineMode {
            anchor: 5,
            count: None,
        };
        match mode.render_state() {
            ModeRenderState::VisualLine { anchor } => assert_eq!(anchor, 5),
            other => panic!("expected VisualLine, got {:?}", other),
        }
    }

    #[test]
    fn test_mode_bar_content_contains_visual() {
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        assert!(matches!(
            mode.render_state(),
            ModeRenderState::VisualLine { .. }
        ));
    }

    #[test]
    fn test_mode_bar_content_contains_yank() {
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        let content = mode.mode_bar_content(&Keybindings::default(), &Theme::default());
        let text: String = content.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("yank"));
    }

    #[tokio::test]
    async fn test_y_yanks_and_returns_normal() {
        let mut tab = make_tab(&["line one", "line two", "line three"]).await;
        tab.scroll.scroll_offset = 0;
        let mode = VisualLineMode {
            anchor: 2,
            count: None,
        };
        let (mode2, result) = press(mode, &mut tab, KeyCode::Char('y')).await;
        // Should return to normal mode
        assert!(matches!(mode2.render_state(), ModeRenderState::Normal));
        // Should return the selected text for clipboard via App
        match result {
            KeyResult::CopyToClipboard(text) => {
                assert_eq!(text, "line one\nline two\nline three");
            }
            other => panic!("expected CopyToClipboard, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_y_yanks_structured_lines_as_displayed() {
        // JSON log lines — the parser should detect them and format columns.
        let mut tab = make_tab(&[
            r#"{"timestamp":"2024-01-01T00:00:00Z","level":"INFO","message":"hello"}"#,
            r#"{"timestamp":"2024-01-01T00:00:01Z","level":"WARN","message":"world"}"#,
        ])
        .await;
        // Ensure the parser was detected.
        assert!(
            tab.display.format.is_some(),
            "expected a format parser to be detected"
        );
        tab.scroll.scroll_offset = 0;
        let mode = VisualLineMode {
            anchor: 1,
            count: None,
        };
        let (_, result) = press(mode, &mut tab, KeyCode::Char('y')).await;
        match result {
            KeyResult::CopyToClipboard(text) => {
                // Should contain the formatted columns, not raw JSON.
                assert!(!text.contains('{'), "expected formatted text, got raw JSON");
                assert!(text.contains("hello"));
                assert!(text.contains("world"));
            }
            other => panic!("expected CopyToClipboard, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_m_marks_all_selected_lines() {
        let mut tab = make_tab(&["a", "b", "c", "d"]).await;
        tab.scroll.scroll_offset = 3;
        let mode = VisualLineMode {
            anchor: 1,
            count: None,
        };
        let (mode2, result) = press(mode, &mut tab, KeyCode::Char('m')).await;
        assert!(matches!(result, KeyResult::Handled));
        assert!(matches!(mode2.render_state(), ModeRenderState::Normal));
        // Lines at visible indices 1, 2, 3 should be marked.
        assert!(tab.log_manager.is_marked(1));
        assert!(tab.log_manager.is_marked(2));
        assert!(tab.log_manager.is_marked(3));
        assert!(!tab.log_manager.is_marked(0));
    }

    #[tokio::test]
    async fn test_m_unmarks_when_all_already_marked() {
        let mut tab = make_tab(&["a", "b", "c"]).await;
        tab.log_manager.toggle_mark(0);
        tab.log_manager.toggle_mark(1);
        tab.log_manager.toggle_mark(2);
        tab.scroll.scroll_offset = 2;
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        let (_, _) = press(mode, &mut tab, KeyCode::Char('m')).await;
        // All were marked → all should now be unmarked.
        assert!(!tab.log_manager.is_marked(0));
        assert!(!tab.log_manager.is_marked(1));
        assert!(!tab.log_manager.is_marked(2));
    }

    #[tokio::test]
    async fn test_m_marks_all_when_partially_marked() {
        let mut tab = make_tab(&["a", "b", "c"]).await;
        tab.log_manager.toggle_mark(0); // only first is marked
        tab.scroll.scroll_offset = 2;
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        let (_, _) = press(mode, &mut tab, KeyCode::Char('m')).await;
        // Partial marks → mark all.
        assert!(tab.log_manager.is_marked(0));
        assert!(tab.log_manager.is_marked(1));
        assert!(tab.log_manager.is_marked(2));
    }

    #[tokio::test]
    async fn test_y_raw_mode_yanks_raw_bytes() {
        let mut tab =
            make_tab(&[r#"{"timestamp":"2024-01-01T00:00:00Z","level":"INFO","message":"hello"}"#])
                .await;
        assert!(tab.display.format.is_some());
        tab.display.raw_mode = true;
        tab.scroll.scroll_offset = 0;
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        let (_, result) = press(mode, &mut tab, KeyCode::Char('y')).await;
        match result {
            KeyResult::CopyToClipboard(text) => {
                // Raw mode: should preserve the original JSON, not format columns.
                assert!(text.contains('{'), "expected raw JSON, got formatted text");
                assert!(text.contains("hello"));
            }
            other => panic!("expected CopyToClipboard, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_y_empty_visible_indices_returns_normal() {
        let mut tab = make_tab(&[]).await;
        tab.scroll.scroll_offset = 0;
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        let (mode2, _) = press(mode, &mut tab, KeyCode::Char('y')).await;
        assert!(matches!(mode2.render_state(), ModeRenderState::Normal));
        assert_eq!(
            tab.interaction.command_error.as_deref(),
            Some("No lines to copy")
        );
    }

    // ── Count prefix tests ───────────────────────────────────────────────

    #[tokio::test]
    async fn test_visual_count_5j_moves_down_5() {
        let lines: Vec<&str> = (0..20).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        tab.scroll.scroll_offset = 0;
        let mode = VisualLineMode {
            anchor: 0,
            count: Some(5),
        };
        let (_, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('j'), KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 5);
    }

    #[tokio::test]
    async fn test_visual_count_3k_moves_up_3() {
        let lines: Vec<&str> = (0..20).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        tab.scroll.scroll_offset = 10;
        let mode = VisualLineMode {
            anchor: 10,
            count: Some(3),
        };
        let (_, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('k'), KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 7);
    }

    #[tokio::test]
    async fn test_visual_digit_accumulation() {
        let lines: Vec<&str> = (0..200).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        tab.scroll.scroll_offset = 0;
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        // Type "15j"
        let (mode, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('1'), KeyModifiers::NONE)
            .await;
        let (mode, _) = mode
            .handle_key(&mut tab, KeyCode::Char('5'), KeyModifiers::NONE)
            .await;
        let _ = mode
            .handle_key(&mut tab, KeyCode::Char('j'), KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 15);
    }

    #[tokio::test]
    async fn test_slash_enters_search_with_lo_line_text() {
        let mut tab = make_tab(&["foo", "bar"]).await;
        tab.scroll.scroll_offset = 1;
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        let (mode2, _) = press(mode, &mut tab, KeyCode::Char('/')).await;
        match mode2.render_state() {
            ModeRenderState::Search { query, forward } => {
                assert!(query.contains("foo"), "expected lo-line text, got: {query}");
                assert!(forward);
            }
            other => panic!("expected Search, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_slash_escapes_regex_metacharacters_in_search() {
        let mut tab = make_tab(&["GET /api/v2?limit=10"]).await;
        tab.scroll.scroll_offset = 0;
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        let (mode2, _) = press(mode, &mut tab, KeyCode::Char('/')).await;
        match mode2.render_state() {
            ModeRenderState::Search { query, forward } => {
                assert!(
                    query.contains(r"GET /api/v2\?limit=10"),
                    "? must be escaped, got: {query}"
                );
                assert!(forward);
            }
            other => panic!("expected Search, got {:?}", other),
        }
    }

    // ── New motion tests ─────────────────────────────────────────────────

    async fn press_ctrl(
        mode: VisualLineMode,
        tab: &mut TabState,
        c: char,
    ) -> (Box<dyn Mode>, KeyResult) {
        Box::new(mode)
            .handle_key(tab, KeyCode::Char(c), KeyModifiers::CONTROL)
            .await
    }

    #[tokio::test]
    async fn test_ctrl_d_moves_half_page_down() {
        let lines: Vec<&str> = (0..40).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        tab.scroll.scroll_offset = 0;
        tab.scroll.visible_height = 20;
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        let _ = press_ctrl(mode, &mut tab, 'd').await;
        assert_eq!(tab.scroll.scroll_offset, 10); // half of 20
    }

    #[tokio::test]
    async fn test_ctrl_u_moves_half_page_up() {
        let lines: Vec<&str> = (0..40).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        tab.scroll.scroll_offset = 20;
        tab.scroll.visible_height = 20;
        let mode = VisualLineMode {
            anchor: 20,
            count: None,
        };
        let _ = press_ctrl(mode, &mut tab, 'u').await;
        assert_eq!(tab.scroll.scroll_offset, 10);
    }

    #[tokio::test]
    async fn test_page_down_moves_full_page() {
        let lines: Vec<&str> = (0..60).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        tab.scroll.scroll_offset = 0;
        tab.scroll.visible_height = 20;
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        let _ = Box::new(mode)
            .handle_key(&mut tab, KeyCode::PageDown, KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 20);
    }

    #[tokio::test]
    async fn test_page_up_moves_full_page() {
        let lines: Vec<&str> = (0..60).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        tab.scroll.scroll_offset = 20;
        tab.scroll.visible_height = 20;
        let mode = VisualLineMode {
            anchor: 20,
            count: None,
        };
        let _ = Box::new(mode)
            .handle_key(&mut tab, KeyCode::PageUp, KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 0);
    }

    #[tokio::test]
    async fn test_g_goes_to_last_line() {
        let lines: Vec<&str> = (0..10).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        tab.scroll.scroll_offset = 0;
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        let _ = press(mode, &mut tab, KeyCode::Char('G')).await;
        assert_eq!(tab.scroll.scroll_offset, 9);
    }

    #[tokio::test]
    async fn test_gg_goes_to_first_line() {
        let lines: Vec<&str> = (0..10).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        tab.scroll.scroll_offset = 9;
        let mode = VisualLineMode {
            anchor: 9,
            count: None,
        };
        // First 'g' sets the flag
        let (mode2, _) = press(mode, &mut tab, KeyCode::Char('g')).await;
        assert!(tab.interaction.g_key_pressed);
        assert_eq!(tab.scroll.scroll_offset, 9); // not moved yet
        // Second 'g' jumps to top
        let _ = mode2
            .handle_key(&mut tab, KeyCode::Char('g'), KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 0);
        assert!(!tab.interaction.g_key_pressed);
    }

    #[tokio::test]
    async fn test_j_resets_g_key_pressed() {
        let lines: Vec<&str> = (0..10).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        tab.interaction.g_key_pressed = true;
        tab.scroll.scroll_offset = 0;
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        let _ = press(mode, &mut tab, KeyCode::Char('j')).await;
        assert!(!tab.interaction.g_key_pressed);
    }

    #[tokio::test]
    async fn test_unrecognized_key_returns_ignored() {
        let mut tab = make_tab(&["a"]).await;
        let mode = VisualLineMode {
            anchor: 0,
            count: None,
        };
        let (_, result) = press(mode, &mut tab, KeyCode::F(2)).await;
        assert!(matches!(result, KeyResult::Ignored));
    }
}