logana 0.6.0

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
use crate::{
    commands::auto_complete::fuzzy_match,
    config::Keybindings,
    mode::app_mode::{Mode, ModeRenderState, status_entry},
    mode::normal_mode::NormalMode,
    theme::Theme,
    ui::{KeyResult, TabState},
};
use async_trait::async_trait;
use crossterm::event::{KeyCode, KeyModifiers};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use std::collections::HashSet;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorsDialogKind {
    ValueColors,
    LevelColors,
}

/// A single toggleable colour category (leaf node).
#[derive(Debug, Clone)]
pub struct ValueColorEntry {
    /// Internal key (e.g. "http_get", "status_2xx").
    pub key: String,
    /// Human-readable display name.
    pub label: String,
    /// The colour associated with this category.
    pub color: Color,
    /// Whether this category is currently enabled.
    pub enabled: bool,
}

/// A group header that contains child entries.
#[derive(Debug, Clone)]
pub struct ValueColorGroup {
    pub label: String,
    pub children: Vec<ValueColorEntry>,
}

/// Flat row used for rendering and navigation.
#[derive(Debug, Clone)]
pub enum ValueColorRow {
    Group(usize),
    Entry(usize, usize),
}

#[derive(Debug)]
pub struct ValueColorsMode {
    pub groups: Vec<ValueColorGroup>,
    pub search: String,
    /// Index into the *visible* (filtered) row list.
    pub selected: usize,
    /// Snapshot of disabled keys on entry — restored on Esc cancel.
    original_disabled: HashSet<String>,
    pub kind: ColorsDialogKind,
}

impl ValueColorsMode {
    pub fn new(groups: Vec<ValueColorGroup>, original_disabled: HashSet<String>) -> Self {
        ValueColorsMode {
            groups,
            search: String::new(),
            selected: 0,
            original_disabled,
            kind: ColorsDialogKind::ValueColors,
        }
    }

    pub fn new_level_colors(
        groups: Vec<ValueColorGroup>,
        original_disabled: HashSet<String>,
    ) -> Self {
        ValueColorsMode {
            groups,
            search: String::new(),
            selected: 0,
            original_disabled,
            kind: ColorsDialogKind::LevelColors,
        }
    }

    /// Build the flat list of visible rows, applying fuzzy search.
    pub fn visible_rows(&self) -> Vec<ValueColorRow> {
        let mut rows = Vec::new();
        for (gi, group) in self.groups.iter().enumerate() {
            if self.search.is_empty() {
                rows.push(ValueColorRow::Group(gi));
                for (ei, _) in group.children.iter().enumerate() {
                    rows.push(ValueColorRow::Entry(gi, ei));
                }
            } else {
                // Collect children that match the search.
                let matching: Vec<usize> = group
                    .children
                    .iter()
                    .enumerate()
                    .filter(|(_, e)| {
                        let haystack = format!("{} {}", group.label, e.label);
                        fuzzy_match(&self.search, &haystack)
                    })
                    .map(|(i, _)| i)
                    .collect();
                if !matching.is_empty() {
                    rows.push(ValueColorRow::Group(gi));
                    for ei in matching {
                        rows.push(ValueColorRow::Entry(gi, ei));
                    }
                }
            }
        }
        rows
    }

    /// Tri-state: all children enabled → true, none → false, mixed → None.
    pub fn group_enabled(&self, gi: usize) -> Option<bool> {
        let group = &self.groups[gi];
        let all = group.children.iter().all(|e| e.enabled);
        let none = group.children.iter().all(|e| !e.enabled);
        if all {
            Some(true)
        } else if none {
            Some(false)
        } else {
            None
        }
    }

    fn make_result(&self, disabled: HashSet<String>) -> KeyResult {
        match self.kind {
            ColorsDialogKind::ValueColors => KeyResult::ApplyValueColors(disabled),
            ColorsDialogKind::LevelColors => KeyResult::ApplyLevelColors(disabled),
        }
    }

    fn clamp_selected(&mut self) {
        let count = self.visible_rows().len();
        if count == 0 {
            self.selected = 0;
        } else if self.selected >= count {
            self.selected = count - 1;
        }
    }
}

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

        // Cancel: clear search first, then cancel.
        if kb.value_colors.cancel.matches(key, modifiers) {
            if !self.search.is_empty() {
                self.search.clear();
                self.selected = 0;
                return (self, KeyResult::Handled);
            }
            let result = self.make_result(self.original_disabled.clone());
            return (Box::new(NormalMode::default()), result);
        }

        if kb.value_colors.apply.matches(key, modifiers) {
            let disabled: HashSet<String> = self
                .groups
                .iter()
                .flat_map(|g| g.children.iter())
                .filter(|e| !e.enabled)
                .map(|e| e.key.clone())
                .collect();
            let result = self.make_result(disabled);
            return (Box::new(NormalMode::default()), result);
        }

        if kb.navigation.scroll_down.matches(key, modifiers) {
            let count = self.visible_rows().len();
            if count > 0 {
                self.selected = (self.selected + 1).min(count - 1);
            }
        } else if kb.navigation.scroll_up.matches(key, modifiers) {
            self.selected = self.selected.saturating_sub(1);
        } else if kb.value_colors.toggle.matches(key, modifiers) {
            let rows = self.visible_rows();
            if let Some(row) = rows.get(self.selected) {
                match row {
                    ValueColorRow::Group(gi) => {
                        let gi = *gi;
                        let target = !self.group_enabled(gi).unwrap_or(false);
                        for child in &mut self.groups[gi].children {
                            child.enabled = target;
                        }
                    }
                    ValueColorRow::Entry(gi, ei) => {
                        let (gi, ei) = (*gi, *ei);
                        self.groups[gi].children[ei].enabled =
                            !self.groups[gi].children[ei].enabled;
                    }
                }
            }
        } else if kb.value_colors.all.matches(key, modifiers) && self.search.is_empty() {
            for group in &mut self.groups {
                for child in &mut group.children {
                    child.enabled = true;
                }
            }
        } else if kb.value_colors.none.matches(key, modifiers) && self.search.is_empty() {
            for group in &mut self.groups {
                for child in &mut group.children {
                    child.enabled = false;
                }
            }
        } else {
            match key {
                KeyCode::Char(c) if !modifiers.contains(KeyModifiers::CONTROL) => {
                    self.search.push(c);
                    self.selected = 0;
                    self.clamp_selected();
                }
                KeyCode::Backspace => {
                    self.search.pop();
                    self.selected = 0;
                    self.clamp_selected();
                }
                _ => {}
            }
        }
        (self, KeyResult::Ignored)
    }

    fn mode_bar_content(&self, kb: &Keybindings, theme: &Theme) -> Line<'static> {
        let title = match self.kind {
            ColorsDialogKind::ValueColors => "[VALUE COLORS]  ",
            ColorsDialogKind::LevelColors => "[LEVEL COLORS]  ",
        };
        let mut spans: Vec<Span<'static>> = vec![Span::styled(
            title,
            Style::default()
                .fg(theme.text_highlight_fg)
                .add_modifier(Modifier::BOLD),
        )];
        status_entry(
            &mut spans,
            kb.value_colors.toggle.display(),
            "toggle",
            theme,
        );
        status_entry(&mut spans, kb.value_colors.all.display(), "all", theme);
        status_entry(&mut spans, kb.value_colors.none.display(), "none", theme);
        status_entry(&mut spans, kb.value_colors.apply.display(), "apply", theme);
        status_entry(
            &mut spans,
            kb.value_colors.cancel.display(),
            "cancel",
            theme,
        );
        Line::from(spans)
    }

    fn render_state(&self) -> ModeRenderState {
        match self.kind {
            ColorsDialogKind::ValueColors => ModeRenderState::ValueColors {
                groups: self.groups.clone(),
                search: self.search.clone(),
                selected: self.selected,
            },
            ColorsDialogKind::LevelColors => ModeRenderState::LevelColors {
                groups: self.groups.clone(),
                search: self.search.clone(),
                selected: self.selected,
            },
        }
    }
}

#[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() -> TabState {
        let file_reader = FileReader::from_bytes(b"test line\n".to_vec());
        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())
    }

    fn sample_groups() -> Vec<ValueColorGroup> {
        vec![
            ValueColorGroup {
                label: "HTTP methods".to_string(),
                children: vec![
                    ValueColorEntry {
                        key: "http_get".to_string(),
                        label: "GET".to_string(),
                        color: Color::Green,
                        enabled: true,
                    },
                    ValueColorEntry {
                        key: "http_post".to_string(),
                        label: "POST".to_string(),
                        color: Color::Cyan,
                        enabled: true,
                    },
                ],
            },
            ValueColorGroup {
                label: "Status codes".to_string(),
                children: vec![
                    ValueColorEntry {
                        key: "status_2xx".to_string(),
                        label: "2xx".to_string(),
                        color: Color::Green,
                        enabled: true,
                    },
                    ValueColorEntry {
                        key: "status_4xx".to_string(),
                        label: "4xx".to_string(),
                        color: Color::Yellow,
                        enabled: false,
                    },
                ],
            },
            ValueColorGroup {
                label: "Identifiers".to_string(),
                children: vec![ValueColorEntry {
                    key: "uuid".to_string(),
                    label: "UUIDs".to_string(),
                    color: Color::Magenta,
                    enabled: true,
                }],
            },
        ]
    }

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

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

    #[tokio::test]
    async fn test_visible_rows_no_search() {
        let mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        let rows = mode.visible_rows();
        // 3 groups + 2 + 2 + 1 entries = 8 rows
        assert_eq!(rows.len(), 8);
        assert!(matches!(rows[0], ValueColorRow::Group(0)));
        assert!(matches!(rows[1], ValueColorRow::Entry(0, 0)));
        assert!(matches!(rows[3], ValueColorRow::Group(1)));
    }

    #[tokio::test]
    async fn test_visible_rows_with_search() {
        let mut mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        mode.search = "get".to_string();
        let rows = mode.visible_rows();
        // Only "HTTP methods" group with "GET" entry
        assert_eq!(rows.len(), 2);
        assert!(matches!(rows[0], ValueColorRow::Group(0)));
        assert!(matches!(rows[1], ValueColorRow::Entry(0, 0)));
    }

    #[tokio::test]
    async fn test_navigate_down() {
        let mut tab = make_tab().await;
        let mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        let (mode, _) = press(mode, &mut tab, KeyCode::Char('j')).await;
        match mode.render_state() {
            ModeRenderState::ValueColors { selected, .. } => assert_eq!(selected, 1),
            other => panic!("expected ValueColors, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_navigate_up_at_top() {
        let mut tab = make_tab().await;
        let mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        let (mode, _) = press(mode, &mut tab, KeyCode::Char('k')).await;
        match mode.render_state() {
            ModeRenderState::ValueColors { selected, .. } => assert_eq!(selected, 0),
            other => panic!("expected ValueColors, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_toggle_group_disables_all_children() {
        let mut tab = make_tab().await;
        let mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        // selected=0 is "HTTP methods" group, both children enabled → toggle disables
        let (mode, _) = press(mode, &mut tab, KeyCode::Char(' ')).await;
        match mode.render_state() {
            ModeRenderState::ValueColors { groups, .. } => {
                assert!(groups[0].children.iter().all(|c| !c.enabled));
            }
            other => panic!("expected ValueColors, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_toggle_group_enables_when_mixed() {
        let mut tab = make_tab().await;
        let groups = sample_groups(); // Status codes group has mixed (2xx=on, 4xx=off)
        let mode = ValueColorsMode::new(groups, HashSet::new());
        // Navigate to "Status codes" group (row index 3)
        let (mode, _) = press(mode, &mut tab, KeyCode::Char('j')).await;
        let (mode, _) = press_dyn(mode, &mut tab, KeyCode::Char('j')).await;
        let (mode, _) = press_dyn(mode, &mut tab, KeyCode::Char('j')).await;
        // Now at row 3 = Group(1) = Status codes
        let (mode, _) = press_dyn(mode, &mut tab, KeyCode::Char(' ')).await;
        match mode.render_state() {
            ModeRenderState::ValueColors { groups, .. } => {
                // Mixed → should enable all
                assert!(groups[1].children.iter().all(|c| c.enabled));
            }
            other => panic!("expected ValueColors, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_toggle_entry() {
        let mut tab = make_tab().await;
        let mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        // Navigate to row 1 = Entry(0, 0) = GET
        let (mode, _) = press(mode, &mut tab, KeyCode::Char('j')).await;
        let (mode, _) = press_dyn(mode, &mut tab, KeyCode::Char(' ')).await;
        match mode.render_state() {
            ModeRenderState::ValueColors { groups, .. } => {
                assert!(!groups[0].children[0].enabled);
            }
            other => panic!("expected ValueColors, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_enable_all() {
        let mut tab = make_tab().await;
        let mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        let (mode, _) = press(mode, &mut tab, KeyCode::Char('a')).await;
        match mode.render_state() {
            ModeRenderState::ValueColors { groups, .. } => {
                assert!(groups.iter().all(|g| g.children.iter().all(|c| c.enabled)));
            }
            other => panic!("expected ValueColors, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_disable_all() {
        let mut tab = make_tab().await;
        let mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        let (mode, _) = press(mode, &mut tab, KeyCode::Char('n')).await;
        match mode.render_state() {
            ModeRenderState::ValueColors { groups, .. } => {
                assert!(groups.iter().all(|g| g.children.iter().all(|c| !c.enabled)));
            }
            other => panic!("expected ValueColors, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_enter_collects_disabled() {
        let mut tab = make_tab().await;
        let mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        let (_, result) = press(mode, &mut tab, KeyCode::Enter).await;
        match result {
            KeyResult::ApplyValueColors(disabled) => {
                // Only status_4xx was disabled in sample_groups
                assert!(disabled.contains("status_4xx"));
                assert!(!disabled.contains("http_get"));
                assert!(!disabled.contains("uuid"));
            }
            _ => panic!("expected ApplyValueColors"),
        }
    }

    #[tokio::test]
    async fn test_esc_with_search_clears_search() {
        let mut tab = make_tab().await;
        let mut mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        mode.search = "http".to_string();
        let (mode, result) = press(mode, &mut tab, KeyCode::Esc).await;
        assert!(matches!(result, KeyResult::Handled));
        match mode.render_state() {
            ModeRenderState::ValueColors { search, .. } => assert!(search.is_empty()),
            other => panic!("expected ValueColors, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_esc_without_search_restores_original() {
        let mut tab = make_tab().await;
        let mut original = HashSet::new();
        original.insert("status_5xx".to_string());
        let mode = ValueColorsMode::new(sample_groups(), original.clone());
        let (_, result) = press(mode, &mut tab, KeyCode::Esc).await;
        match result {
            KeyResult::ApplyValueColors(disabled) => {
                assert_eq!(disabled, original);
            }
            _ => panic!("expected ApplyValueColors"),
        }
    }

    #[tokio::test]
    async fn test_typing_activates_search() {
        let mut tab = make_tab().await;
        let mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        // Type 'g' — should go into search
        let (mode, _) = press(mode, &mut tab, KeyCode::Char('g')).await;
        match mode.render_state() {
            ModeRenderState::ValueColors { search, .. } => assert_eq!(search, "g"),
            other => panic!("expected ValueColors, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_backspace_removes_search_char() {
        let mut tab = make_tab().await;
        let mut mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        mode.search = "ge".to_string();
        let (mode, _) = press(mode, &mut tab, KeyCode::Backspace).await;
        match mode.render_state() {
            ModeRenderState::ValueColors { search, .. } => assert_eq!(search, "g"),
            other => panic!("expected ValueColors, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_group_enabled_all() {
        let mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        assert_eq!(mode.group_enabled(0), Some(true)); // HTTP: all enabled
    }

    #[tokio::test]
    async fn test_group_enabled_mixed() {
        let mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        assert_eq!(mode.group_enabled(1), None); // Status: mixed
    }

    #[tokio::test]
    async fn test_group_enabled_none() {
        let mut groups = sample_groups();
        for child in &mut groups[0].children {
            child.enabled = false;
        }
        let mode = ValueColorsMode::new(groups, HashSet::new());
        assert_eq!(mode.group_enabled(0), Some(false));
    }

    #[tokio::test]
    async fn test_mode_bar_content() {
        let mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        assert!(matches!(
            mode.render_state(),
            ModeRenderState::ValueColors { .. }
        ));
    }

    #[tokio::test]
    async fn test_search_filters_to_matching_groups() {
        let mut mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        mode.search = "uuid".to_string();
        let rows = mode.visible_rows();
        // Only "Identifiers" group + "UUIDs" entry
        assert_eq!(rows.len(), 2);
        assert!(matches!(rows[0], ValueColorRow::Group(2)));
        assert!(matches!(rows[1], ValueColorRow::Entry(2, 0)));
    }

    #[tokio::test]
    async fn test_unrecognized_key_returns_ignored() {
        let mut tab = make_tab().await;
        let mode = ValueColorsMode::new(sample_groups(), HashSet::new());
        let (_, result) = press(mode, &mut tab, KeyCode::F(2)).await;
        assert!(matches!(result, KeyResult::Ignored));
    }
}