tui-dispatch-debug 0.7.0

Debugging utilities for tui-dispatch
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
//! Action logging with pattern-based filtering and in-memory storage
//!
//! Provides configurable action logging using glob patterns to include/exclude
//! specific actions from logs. Supports both tracing output and in-memory
//! ring buffer storage for display in debug overlays.
//!
//! # Example
//!
//! ```ignore
//! use tui_dispatch_debug::debug::{ActionLoggerConfig, ActionLoggerMiddleware, ActionLogConfig};
//!
//! // Log all actions except Tick and Render (tracing only)
//! let config = ActionLoggerConfig::default();
//! let middleware = ActionLoggerMiddleware::new(config);
//!
//! // Log with in-memory storage for debug overlay display
//! let config = ActionLogConfig::default();
//! let middleware = ActionLoggerMiddleware::with_log(config);
//!
//! // Access the action log
//! if let Some(log) = middleware.log() {
//!     for entry in log.recent(10) {
//!         println!("{}: {}", entry.elapsed, entry.params);
//!     }
//! }
//! ```

use std::collections::VecDeque;
use std::time::Instant;
use tui_dispatch_core::action::ActionParams;
use tui_dispatch_core::store::Middleware;
use tui_dispatch_shared::infer_action_category;

use crate::pattern_utils::split_patterns_csv;

/// Configuration for action logging with include/exclude filtering.
///
/// Patterns support:
/// - `*` matches any sequence of characters
/// - `?` matches any single character
/// - Literal text matches exactly
/// - `cat:<pattern>` / `category:<pattern>` matches inferred action category
/// - `name:<ActionName>` matches exact action name (no wildcards)
///
/// # Examples
///
/// - `Search*` matches SearchAddChar, SearchDeleteChar, etc.
/// - `Did*` matches DidConnect, DidScanKeys, etc.
/// - `*Error*` matches any action containing "Error"
/// - `Tick` matches only Tick
/// - `cat:search` matches `SearchStart`, `SearchSubmit`, etc.
/// - `name:WeatherDidLoad` matches only `WeatherDidLoad`
/// - `WeatherDid*` uses normal glob name matching (without `name:` prefix)
#[derive(Debug, Clone)]
pub struct ActionLoggerConfig {
    /// If non-empty, only log actions matching these patterns
    pub include_patterns: Vec<String>,
    /// Exclude actions matching these patterns (applied after include)
    pub exclude_patterns: Vec<String>,
}

impl Default for ActionLoggerConfig {
    fn default() -> Self {
        Self {
            include_patterns: Vec::new(),
            // By default, exclude noisy high-frequency actions
            exclude_patterns: vec!["Tick".to_string(), "Render".to_string()],
        }
    }
}

impl ActionLoggerConfig {
    /// Create a new config from comma-separated pattern strings
    ///
    /// # Arguments
    /// - `include`: comma-separated glob patterns (or None for all)
    /// - `exclude`: comma-separated glob patterns (or None for default excludes)
    ///
    /// # Example
    /// ```
    /// use tui_dispatch_debug::debug::ActionLoggerConfig;
    ///
    /// let config = ActionLoggerConfig::new(Some("Search*,Connect"), Some("Tick,Render"));
    /// assert!(config.should_log("SearchAddChar"));
    /// assert!(config.should_log("Connect"));
    /// assert!(!config.should_log("Tick"));
    /// ```
    pub fn new(include: Option<&str>, exclude: Option<&str>) -> Self {
        let include_patterns = include.map(split_patterns_csv).unwrap_or_default();

        let exclude_patterns = exclude
            .map(split_patterns_csv)
            .unwrap_or_else(|| vec!["Tick".to_string(), "Render".to_string()]);

        Self {
            include_patterns,
            exclude_patterns,
        }
    }

    /// Create a config with specific pattern vectors
    pub fn with_patterns(include: Vec<String>, exclude: Vec<String>) -> Self {
        Self {
            include_patterns: include,
            exclude_patterns: exclude,
        }
    }

    /// Check if an action name should be logged based on include/exclude patterns
    pub fn should_log(&self, action_name: &str) -> bool {
        // If include patterns specified, action must match at least one
        if !self.include_patterns.is_empty() {
            let matches_include = self
                .include_patterns
                .iter()
                .any(|p| filter_match(p, action_name));
            if !matches_include {
                return false;
            }
        }

        // Check exclude patterns
        let matches_exclude = self
            .exclude_patterns
            .iter()
            .any(|p| filter_match(p, action_name));

        !matches_exclude
    }
}

fn filter_match(pattern: &str, action_name: &str) -> bool {
    let pattern = pattern.trim();
    if pattern.is_empty() {
        return false;
    }

    if let Some(category_pattern) =
        strip_filter_prefix(pattern, "cat:").or_else(|| strip_filter_prefix(pattern, "category:"))
    {
        let category_pattern = category_pattern.trim();
        if category_pattern.is_empty() {
            return false;
        }
        return infer_action_category(action_name)
            .as_deref()
            .is_some_and(|category| glob_match(category_pattern, category));
    }

    if let Some(action_name_pattern) = strip_filter_prefix(pattern, "name:") {
        let action_name_pattern = action_name_pattern.trim();
        if action_name_pattern.is_empty() {
            return false;
        }
        // `name:` is intentionally exact-match only; for wildcard name matching,
        // use a plain glob pattern without the prefix.
        return action_name_pattern == action_name;
    }

    glob_match(pattern, action_name)
}

fn strip_filter_prefix<'a>(value: &'a str, prefix: &str) -> Option<&'a str> {
    if value.len() < prefix.len() {
        return None;
    }
    let (head, tail) = value.split_at(prefix.len());
    if head.eq_ignore_ascii_case(prefix) {
        Some(tail)
    } else {
        None
    }
}

// ============================================================================
// In-Memory Action Log
// ============================================================================

/// An entry in the action log
#[derive(Debug, Clone)]
pub struct ActionLogEntry {
    /// Action name (from Action::name())
    pub name: &'static str,
    /// Action parameters (from ActionParams::params())
    pub params: String,
    /// Pretty action parameters (from ActionParams::params_pretty())
    pub params_pretty: String,
    /// Timestamp when the action was logged
    pub timestamp: Instant,
    /// Elapsed time display, frozen at creation time
    pub elapsed: String,
    /// Sequence number for ordering
    pub sequence: u64,
}

impl ActionLogEntry {
    /// Create a new log entry
    pub fn new(name: &'static str, params: String, params_pretty: String, sequence: u64) -> Self {
        Self {
            name,
            params,
            params_pretty,
            timestamp: Instant::now(),
            elapsed: "0ms".to_string(),
            sequence,
        }
    }
}

/// Format elapsed time for display (e.g., "2.3s", "150ms")
fn format_elapsed(elapsed: std::time::Duration) -> String {
    if elapsed.as_secs() >= 1 {
        format!("{:.1}s", elapsed.as_secs_f64())
    } else {
        format!("{}ms", elapsed.as_millis())
    }
}

/// Configuration for the action log ring buffer
#[derive(Debug, Clone)]
pub struct ActionLogConfig {
    /// Maximum number of entries to keep
    pub capacity: usize,
    /// Filter config (reuses existing ActionLoggerConfig)
    pub filter: ActionLoggerConfig,
}

impl Default for ActionLogConfig {
    fn default() -> Self {
        Self {
            capacity: 100,
            filter: ActionLoggerConfig::default(),
        }
    }
}

impl ActionLogConfig {
    /// Create with custom capacity
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            capacity,
            ..Default::default()
        }
    }

    /// Create with custom capacity and filter
    pub fn new(capacity: usize, filter: ActionLoggerConfig) -> Self {
        Self { capacity, filter }
    }
}

/// In-memory ring buffer for storing recent actions
///
/// Stores actions with timestamps and parameters for display in debug overlays.
/// Older entries are automatically discarded when capacity is reached.
#[derive(Debug, Clone)]
pub struct ActionLog {
    entries: VecDeque<ActionLogEntry>,
    config: ActionLogConfig,
    next_sequence: u64,
    /// Time when the log was created (for relative elapsed times)
    start_time: Instant,
}

impl Default for ActionLog {
    fn default() -> Self {
        Self::new(ActionLogConfig::default())
    }
}

impl ActionLog {
    /// Create a new action log with configuration
    pub fn new(config: ActionLogConfig) -> Self {
        Self {
            entries: VecDeque::with_capacity(config.capacity),
            config,
            next_sequence: 0,
            start_time: Instant::now(),
        }
    }

    /// Log an action (if it passes the filter)
    ///
    /// Returns the entry if it was logged, None if filtered out.
    pub fn log<A: ActionParams>(&mut self, action: &A) -> Option<&ActionLogEntry> {
        let name = action.name();

        if !self.config.filter.should_log(name) {
            return None;
        }

        let params = action.params();
        let params_pretty = action.params_pretty();
        let mut entry = ActionLogEntry::new(name, params, params_pretty, self.next_sequence);
        // Freeze the elapsed time at creation
        entry.elapsed = format_elapsed(self.start_time.elapsed());
        self.next_sequence += 1;

        // Maintain capacity
        if self.entries.len() >= self.config.capacity {
            self.entries.pop_front();
        }

        self.entries.push_back(entry);
        self.entries.back()
    }

    /// Get all entries (oldest first)
    pub fn entries(&self) -> impl Iterator<Item = &ActionLogEntry> {
        self.entries.iter()
    }

    /// Get entries in reverse order (newest first)
    pub fn entries_rev(&self) -> impl Iterator<Item = &ActionLogEntry> {
        self.entries.iter().rev()
    }

    /// Get the most recent N entries (newest first)
    pub fn recent(&self, count: usize) -> impl Iterator<Item = &ActionLogEntry> {
        self.entries.iter().rev().take(count)
    }

    /// Number of entries currently stored
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the log is empty
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Clear all entries
    pub fn clear(&mut self) {
        self.entries.clear();
    }

    /// Get configuration
    pub fn config(&self) -> &ActionLogConfig {
        &self.config
    }

    /// Get mutable configuration
    pub fn config_mut(&mut self) -> &mut ActionLogConfig {
        &mut self.config
    }
}

// ============================================================================
// Middleware
// ============================================================================

/// Middleware that logs actions with configurable pattern filtering.
///
/// Supports two modes:
/// - **Tracing only** (default): logs via `tracing::debug!()`
/// - **With storage**: also stores in ActionLog ring buffer for overlay display
///
/// # Example
///
/// ```ignore
/// use tui_dispatch_debug::debug::{ActionLoggerConfig, ActionLoggerMiddleware, ActionLogConfig};
/// use tui_dispatch_core::{Store, StoreWithMiddleware};
///
/// // Tracing only
/// let middleware = ActionLoggerMiddleware::new(ActionLoggerConfig::default());
///
/// // With in-memory storage
/// let middleware = ActionLoggerMiddleware::with_log(ActionLogConfig::default());
///
/// // Access the log for display
/// if let Some(log) = middleware.log() {
///     for entry in log.recent(10) {
///         println!("{}", entry.params);
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct ActionLoggerMiddleware {
    config: ActionLoggerConfig,
    log: Option<ActionLog>,
    /// Whether the middleware is active (processes actions)
    /// When false, all methods become no-ops for zero overhead.
    active: bool,
}

impl ActionLoggerMiddleware {
    /// Create a new action logger middleware with tracing only (no in-memory storage)
    pub fn new(config: ActionLoggerConfig) -> Self {
        Self {
            config,
            log: None,
            active: true,
        }
    }

    /// Create middleware with in-memory storage
    pub fn with_log(config: ActionLogConfig) -> Self {
        Self {
            config: config.filter.clone(),
            log: Some(ActionLog::new(config)),
            active: true,
        }
    }

    /// Create with default config and in-memory storage
    pub fn with_default_log() -> Self {
        Self::with_log(ActionLogConfig::default())
    }

    /// Create with default config (excludes Tick and Render), tracing only
    pub fn default_filtering() -> Self {
        Self::new(ActionLoggerConfig::default())
    }

    /// Create with no filtering (logs all actions), tracing only
    pub fn log_all() -> Self {
        Self::new(ActionLoggerConfig::with_patterns(vec![], vec![]))
    }

    /// Set whether the middleware is active.
    ///
    /// When inactive (`false`), all methods become no-ops with zero overhead.
    /// This is useful for conditional logging based on CLI flags.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let middleware = ActionLoggerMiddleware::default_filtering()
    ///     .active(args.debug);  // Only log if --debug flag passed
    /// ```
    pub fn active(mut self, active: bool) -> Self {
        self.active = active;
        self
    }

    /// Check if the middleware is active.
    pub fn is_active(&self) -> bool {
        self.active
    }

    /// Get the action log (if storage is enabled)
    pub fn log(&self) -> Option<&ActionLog> {
        self.log.as_ref()
    }

    /// Get mutable action log
    pub fn log_mut(&mut self) -> Option<&mut ActionLog> {
        self.log.as_mut()
    }

    /// Get a reference to the config
    pub fn config(&self) -> &ActionLoggerConfig {
        &self.config
    }

    /// Get a mutable reference to the config
    pub fn config_mut(&mut self) -> &mut ActionLoggerConfig {
        &mut self.config
    }
}

impl<S, A: ActionParams> Middleware<S, A> for ActionLoggerMiddleware {
    fn before(&mut self, action: &A, _state: &S) -> bool {
        // Inactive: no-op
        if !self.active {
            return true;
        }

        let name = action.name();

        // Always log to tracing if filter passes
        if self.config.should_log(name) {
            tracing::debug!(action = %name, "action");
        }

        // Log to in-memory buffer if enabled
        if let Some(ref mut log) = self.log {
            log.log(action);
        }

        true
    }

    fn after(&mut self, _action: &A, _state_changed: bool, _state: &S) -> Vec<A> {
        vec![]
    }
}

/// Simple glob pattern matching supporting `*` and `?`.
///
/// - `*` matches zero or more characters
/// - `?` matches exactly one character
pub fn glob_match(pattern: &str, text: &str) -> bool {
    let pattern: Vec<char> = pattern.chars().collect();
    let text: Vec<char> = text.chars().collect();
    glob_match_impl(&pattern, &text)
}

fn glob_match_impl(pattern: &[char], text: &[char]) -> bool {
    let mut pi = 0;
    let mut ti = 0;
    let mut star_pi = None;
    let mut star_ti = 0;

    while ti < text.len() {
        if pi < pattern.len() && (pattern[pi] == '?' || pattern[pi] == text[ti]) {
            pi += 1;
            ti += 1;
        } else if pi < pattern.len() && pattern[pi] == '*' {
            star_pi = Some(pi);
            star_ti = ti;
            pi += 1;
        } else if let Some(spi) = star_pi {
            pi = spi + 1;
            star_ti += 1;
            ti = star_ti;
        } else {
            return false;
        }
    }

    while pi < pattern.len() && pattern[pi] == '*' {
        pi += 1;
    }

    pi == pattern.len()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_glob_match_exact() {
        assert!(glob_match("Tick", "Tick"));
        assert!(!glob_match("Tick", "Tock"));
        assert!(!glob_match("Tick", "TickTock"));
    }

    #[test]
    fn test_glob_match_star() {
        assert!(glob_match("Search*", "SearchAddChar"));
        assert!(glob_match("Search*", "SearchDeleteChar"));
        assert!(glob_match("Search*", "Search"));
        assert!(!glob_match("Search*", "StartSearch"));

        assert!(glob_match("*Search", "StartSearch"));
        assert!(glob_match("*Search*", "StartSearchNow"));

        assert!(glob_match("Did*", "DidConnect"));
        assert!(glob_match("Did*", "DidScanKeys"));
    }

    #[test]
    fn test_glob_match_question() {
        assert!(glob_match("Tick?", "Ticks"));
        assert!(!glob_match("Tick?", "Tick"));
        assert!(!glob_match("Tick?", "Tickss"));
    }

    #[test]
    fn test_glob_match_combined() {
        assert!(glob_match("*Add*", "SearchAddChar"));
        assert!(glob_match("Connection*Add*", "ConnectionFormAddChar"));
    }

    #[test]
    fn test_action_logger_config_include() {
        let config = ActionLoggerConfig::new(Some("Search*,Connect"), None);
        assert!(config.should_log("SearchAddChar"));
        assert!(config.should_log("Connect"));
        assert!(!config.should_log("Tick"));
        assert!(!config.should_log("LoadKeys"));
    }

    #[test]
    fn test_action_logger_config_exclude() {
        let config = ActionLoggerConfig::new(None, Some("Tick,Render,LoadValue*"));
        assert!(!config.should_log("Tick"));
        assert!(!config.should_log("Render"));
        assert!(!config.should_log("LoadValueDebounced"));
        assert!(config.should_log("SearchAddChar"));
        assert!(config.should_log("Connect"));
    }

    #[test]
    fn test_action_logger_config_include_and_exclude() {
        // Include Did* but exclude DidFail*
        let config = ActionLoggerConfig::new(Some("Did*"), Some("DidFail*"));
        assert!(config.should_log("DidConnect"));
        assert!(config.should_log("DidScanKeys"));
        assert!(!config.should_log("DidFailConnect"));
        assert!(!config.should_log("DidFailScanKeys"));
        assert!(!config.should_log("SearchAddChar")); // Not in include
    }

    #[test]
    fn test_action_logger_config_default() {
        let config = ActionLoggerConfig::default();
        assert!(!config.should_log("Tick"));
        assert!(!config.should_log("Render"));
        assert!(config.should_log("Connect"));
        assert!(config.should_log("SearchAddChar"));
    }

    #[test]
    fn test_action_logger_config_category_filters() {
        let config = ActionLoggerConfig::new(
            Some("cat:search,category:weather"),
            Some("cat:search_query"),
        );

        assert!(config.should_log("SearchStart"));
        assert!(config.should_log("WeatherDidLoad"));
        assert!(!config.should_log("SearchQuerySubmit"));
        assert!(!config.should_log("Connect"));
    }

    #[test]
    fn test_action_logger_config_action_name_filters() {
        let config = ActionLoggerConfig::new(
            Some("name:Connect,name:SearchStart"),
            Some("name:SearchStart"),
        );

        assert!(config.should_log("Connect"));
        assert!(!config.should_log("SearchStart"));
        assert!(!config.should_log("SearchAddChar"));
    }

    #[test]
    fn test_action_logger_name_filter_is_case_sensitive() {
        let lowercase = ActionLoggerConfig::new(Some("name:searchstart"), None);
        let exact = ActionLoggerConfig::new(Some("name:SearchStart"), None);

        assert!(!lowercase.should_log("SearchStart"));
        assert!(exact.should_log("SearchStart"));
    }

    #[test]
    fn test_action_logger_name_filter_no_action_alias() {
        let config = ActionLoggerConfig::new(Some("action:SearchStart"), None);
        assert!(!config.should_log("SearchStart"));
    }

    #[test]
    fn test_action_logger_category_inference_edges() {
        let async_result = ActionLoggerConfig::new(Some("cat:async_result"), None);
        assert!(async_result.should_log("DidLoad"));
        assert!(!async_result.should_log("Tick"));

        let acronym = ActionLoggerConfig::new(Some("cat:api"), None);
        assert!(acronym.should_log("APIFetchStart"));
        assert!(!acronym.should_log("OpenConnectionForm"));
    }

    #[test]
    fn test_action_logger_config_category_glob_and_case_insensitive_prefix() {
        let config = ActionLoggerConfig::new(Some("CAT:search*"), None);
        assert!(config.should_log("SearchStart"));
        assert!(config.should_log("SearchQuerySubmit"));
        assert!(!config.should_log("WeatherDidLoad"));
    }

    // Test action for ActionLog tests
    #[derive(Clone, Debug)]
    enum TestAction {
        Tick,
        Connect,
        SearchStart,
    }

    impl tui_dispatch_core::Action for TestAction {
        fn name(&self) -> &'static str {
            match self {
                TestAction::Tick => "Tick",
                TestAction::Connect => "Connect",
                TestAction::SearchStart => "SearchStart",
            }
        }
    }

    impl tui_dispatch_core::ActionParams for TestAction {
        fn params(&self) -> String {
            String::new()
        }
    }

    #[test]
    fn test_action_log_basic() {
        let mut log = ActionLog::default();
        assert!(log.is_empty());

        log.log(&TestAction::Connect);
        assert_eq!(log.len(), 1);

        let entry = log.entries().next().unwrap();
        assert_eq!(entry.name, "Connect");
        assert_eq!(entry.sequence, 0);
    }

    #[test]
    fn test_action_log_filtering() {
        let mut log = ActionLog::default(); // Default excludes Tick

        log.log(&TestAction::Tick);
        assert!(log.is_empty()); // Tick should be filtered

        log.log(&TestAction::Connect);
        assert_eq!(log.len(), 1);
    }

    #[test]
    fn test_action_log_capacity() {
        let config = ActionLogConfig::new(
            3,
            ActionLoggerConfig::with_patterns(vec![], vec![]), // No filtering
        );
        let mut log = ActionLog::new(config);

        log.log(&TestAction::Connect);
        log.log(&TestAction::Connect);
        log.log(&TestAction::Connect);
        assert_eq!(log.len(), 3);

        log.log(&TestAction::Connect);
        assert_eq!(log.len(), 3); // Still 3, oldest was removed

        // First entry should now be sequence 1 (sequence 0 was removed)
        assert_eq!(log.entries().next().unwrap().sequence, 1);
    }

    #[test]
    fn test_action_log_recent() {
        let config = ActionLogConfig::new(10, ActionLoggerConfig::with_patterns(vec![], vec![]));
        let mut log = ActionLog::new(config);

        for _ in 0..5 {
            log.log(&TestAction::Connect);
        }

        // Recent should return newest first
        let recent: Vec<_> = log.recent(3).collect();
        assert_eq!(recent.len(), 3);
        assert_eq!(recent[0].sequence, 4); // Newest
        assert_eq!(recent[1].sequence, 3);
        assert_eq!(recent[2].sequence, 2);
    }

    #[test]
    fn test_action_log_entry_elapsed() {
        let entry = ActionLogEntry::new(
            "Test",
            "test_params".to_string(),
            "test_params".to_string(),
            0,
        );
        // Should have "0ms" as default elapsed
        assert_eq!(entry.elapsed, "0ms");
    }

    #[test]
    fn test_middleware_filtering() {
        use tui_dispatch_core::store::Middleware;

        // Default config filters out "Tick"
        let mut middleware = ActionLoggerMiddleware::with_default_log();

        // Log a Connect action
        middleware.before(&TestAction::Connect, &());
        middleware.after(&TestAction::Connect, true, &());

        // Verify Connect was logged
        let log = middleware.log().unwrap();
        assert_eq!(log.len(), 1);

        // Now dispatch a Tick (filtered out by default)
        middleware.before(&TestAction::Tick, &());
        middleware.after(&TestAction::Tick, false, &());

        // Log should still have only 1 entry (Tick was filtered)
        let log = middleware.log().unwrap();
        assert_eq!(log.len(), 1);
    }

    #[test]
    fn test_action_log_include_category_with_exclude_name_can_filter_all() {
        let config = ActionLogConfig::new(
            10,
            ActionLoggerConfig::new(Some("cat:search"), Some("name:SearchStart")),
        );
        let mut log = ActionLog::new(config);

        log.log(&TestAction::SearchStart);
        log.log(&TestAction::Connect);

        // SearchStart is included by category but excluded by exact name.
        // Connect doesn't match include category, so nothing is logged.
        assert!(log.is_empty());
    }
}