nika 0.35.4

Semantic YAML workflow engine for AI tasks - DAG execution, MCP integration, multi-provider LLM support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! Unified status bar widget showing contextual keybindings
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │ [Enter] Send  [Up/Down] History     Claude | 1.2k tokens | MCP: 2 connected │
//! └─────────────────────────────────────────────────────────────────────────────┘
//! ```

use std::borrow::Cow;

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Paragraph, Widget},
};

use unicode_width::UnicodeWidthStr;

use crate::tui::icons::provider as icons_provider;
use crate::tui::keybindings::{format_key, keybindings_for_context, KeyCategory, Keybinding};
use crate::tui::mode::InputMode;
use crate::tui::theme::Theme;
use crate::tui::views::TuiView;

/// Key hint for status bar
///
/// Uses `Cow<'static, str>` to avoid memory leaks - static strings don't allocate,
/// while dynamically generated keys (from keybindings) are owned without Box::leak.
#[derive(Debug, Clone)]
pub struct KeyHint {
    pub key: Cow<'static, str>,
    pub action: Cow<'static, str>,
}

impl KeyHint {
    /// Create a new key hint from static strings (zero allocation)
    pub const fn new(key: &'static str, action: &'static str) -> Self {
        Self {
            key: Cow::Borrowed(key),
            action: Cow::Borrowed(action),
        }
    }

    /// Create a new key hint with an owned key string (for dynamic keys)
    pub fn with_owned_key(key: String, action: &'static str) -> Self {
        Self {
            key: Cow::Owned(key),
            action: Cow::Borrowed(action),
        }
    }
}

/// LLM Provider indicator
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Provider {
    #[default]
    None,
    Claude,
    OpenAI,
    Mistral,
    Native,
    Groq,
    DeepSeek,
    Mock,
}

impl Provider {
    /// Get provider icon (delegates to canonical icons::provider)
    pub fn icon(&self) -> &'static str {
        match self {
            Self::None => "  ",
            Self::Claude => icons_provider::CLAUDE,
            Self::OpenAI => icons_provider::OPENAI,
            Self::Mistral => icons_provider::MISTRAL,
            Self::Native => icons_provider::NATIVE,
            Self::Groq => icons_provider::GROQ,
            Self::DeepSeek => icons_provider::DEEPSEEK,
            Self::Mock => icons_provider::MOCK,
        }
    }

    /// Get provider display name
    pub fn name(&self) -> &'static str {
        match self {
            Self::None => "---",
            Self::Claude => "Claude",
            Self::OpenAI => "OpenAI",
            Self::Mistral => "Mistral",
            Self::Native => "Native",
            Self::Groq => "Groq",
            Self::DeepSeek => "DeepSeek",
            Self::Mock => "Mock",
        }
    }

    /// Detect provider from model name (called once when model changes, not every frame).
    ///
    /// Converts the model name to lowercase once and checks provider patterns.
    pub fn from_model_name(model: &str) -> Self {
        let model_lower = model.to_lowercase();
        if model_lower.contains("claude") {
            Self::Claude
        } else if model_lower.contains("gpt") || model_lower.contains("openai") {
            Self::OpenAI
        } else if model_lower.contains("mistral") || model_lower.contains("mixtral") {
            Self::Mistral
        } else if model_lower.contains("gguf")
            || model_lower.contains("native")
            || model_lower.contains("local")
        {
            Self::Native
        } else if model_lower.contains("groq") {
            Self::Groq
        } else if model_lower.contains("deepseek") {
            Self::DeepSeek
        } else if model_lower.contains("mock") {
            Self::Mock
        } else {
            Self::None
        }
    }
}

/// Workflow execution phase for status feedback
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WorkflowPhase {
    #[default]
    Idle,
    Parsing,
    Validating,
    Executing,
    Completed,
    Failed,
}

impl WorkflowPhase {
    /// Get phase icon
    pub fn icon(&self) -> &'static str {
        match self {
            Self::Idle => "",
            Self::Parsing => "",
            Self::Validating => "",
            Self::Executing => "",
            Self::Completed => "",
            Self::Failed => "",
        }
    }

    /// Get animated icon for active phases
    pub fn animated_icon(&self, frame: u8) -> &'static str {
        match self {
            Self::Parsing | Self::Validating | Self::Executing => {
                // Spinning animation: ◐ ◓ ◑ ◒
                const SPIN: [&str; 4] = ["", "", "", ""];
                SPIN[(frame / 8) as usize % 4]
            }
            _ => self.icon(),
        }
    }

    /// Get phase display name
    pub fn name(&self) -> &'static str {
        match self {
            Self::Idle => "Idle",
            Self::Parsing => "Parsing",
            Self::Validating => "Validating",
            Self::Executing => "Executing",
            Self::Completed => "Completed",
            Self::Failed => "Failed",
        }
    }

    /// Check if phase is active (showing animation)
    pub fn is_active(&self) -> bool {
        matches!(self, Self::Parsing | Self::Validating | Self::Executing)
    }
}

/// MCP Connection status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConnectionStatus {
    #[default]
    Disconnected,
    Connecting,
    Connected,
    Error,
}

impl ConnectionStatus {
    /// Get status icon
    pub fn icon(&self) -> &'static str {
        match self {
            Self::Disconnected => "",
            Self::Connecting => "",
            Self::Connected => "",
            Self::Error => "",
        }
    }

    /// Get animated icon (for connecting status)
    pub fn animated_icon(&self, frame: u8) -> &'static str {
        match self {
            Self::Connecting => {
                // Spinning animation: ◐ ◓ ◑ ◒
                const SPIN: [&str; 4] = ["", "", "", ""];
                SPIN[(frame / 8) as usize % 4]
            }
            _ => self.icon(),
        }
    }
}

/// Metrics to display on the right side of status bar
#[derive(Debug, Clone, Default)]
pub struct StatusMetrics {
    /// Current LLM provider
    pub provider: Provider,
    /// Total tokens used in session
    pub tokens: Option<u64>,
    /// Number of connected MCP servers
    pub mcp_connected: usize,
    /// Total MCP servers configured
    pub mcp_total: usize,
    /// Connection status
    pub connection: ConnectionStatus,
    /// Current workflow phase
    pub phase: WorkflowPhase,
    /// Progress percentage (0-100) for long-running tasks
    pub progress: Option<u8>,
    /// Error code (NIKA-XXX) for failed state
    pub error_code: Option<String>,
}

impl StatusMetrics {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn provider(mut self, provider: Provider) -> Self {
        self.provider = provider;
        self
    }

    pub fn tokens(mut self, tokens: u64) -> Self {
        self.tokens = Some(tokens);
        self
    }

    pub fn mcp(mut self, connected: usize, total: usize) -> Self {
        self.mcp_connected = connected;
        self.mcp_total = total;
        self
    }

    pub fn connection(mut self, status: ConnectionStatus) -> Self {
        self.connection = status;
        self
    }

    pub fn phase(mut self, phase: WorkflowPhase) -> Self {
        self.phase = phase;
        self
    }

    pub fn progress(mut self, progress: u8) -> Self {
        self.progress = Some(progress.min(100));
        self
    }

    pub fn error_code(mut self, code: impl Into<String>) -> Self {
        self.error_code = Some(code.into());
        self
    }

    /// Format progress as a mini bar
    fn format_progress(&self) -> Option<String> {
        self.progress.map(|p| {
            // Mini progress bar: [████░░░░░░] 45%
            let filled = (p as usize * 8) / 100;
            let empty = 8 - filled;
            format!("[{}{}] {}%", "".repeat(filled), "".repeat(empty), p)
        })
    }

    /// Format token count for display
    fn format_tokens(&self) -> Option<String> {
        self.tokens.map(|t| {
            if t >= 1_000_000 {
                format!("{:.1}M", t as f64 / 1_000_000.0)
            } else if t >= 1_000 {
                format!("{:.1}k", t as f64 / 1_000.0)
            } else {
                format!("{}", t)
            }
        })
    }
}

/// Status bar configuration
pub struct StatusBar<'a> {
    /// Current view (determines which hints to show)
    pub view: TuiView,
    /// Optional custom hints (overrides defaults)
    pub hints: Option<Vec<KeyHint>>,
    /// Theme for colors
    pub theme: &'a Theme,
    /// Metrics to display on the right
    pub metrics: Option<StatusMetrics>,
    /// Current input mode (Normal, Insert, Command, Search)
    pub input_mode: Option<InputMode>,
    /// Custom status text from the view's status_line() method
    pub custom_text: Option<String>,
    /// Animation frame counter (0-255) for live indicators
    pub frame: u8,
}

impl<'a> StatusBar<'a> {
    pub fn new(view: TuiView, theme: &'a Theme) -> Self {
        Self {
            view,
            hints: None,
            theme,
            metrics: None,
            input_mode: None,
            custom_text: None,
            frame: 0,
        }
    }

    /// Set animation frame for live indicators
    pub fn frame(mut self, frame: u8) -> Self {
        self.frame = frame;
        self
    }

    pub fn hints(mut self, hints: Vec<KeyHint>) -> Self {
        self.hints = Some(hints);
        self
    }

    pub fn metrics(mut self, metrics: StatusMetrics) -> Self {
        self.metrics = Some(metrics);
        self
    }

    pub fn mode(mut self, mode: InputMode) -> Self {
        self.input_mode = Some(mode);
        self
    }

    /// Set custom status text from the view's status_line() method
    pub fn custom_text(mut self, text: String) -> Self {
        if !text.is_empty() {
            self.custom_text = Some(text);
        }
        self
    }

    fn default_hints(&self) -> Vec<KeyHint> {
        // If input_mode is set, use keybindings_for_context for dynamic hints
        if let Some(mode) = self.input_mode {
            return self.hints_from_keybindings(keybindings_for_context(self.view, mode));
        }

        // Fallback to static hints
        match self.view {
            TuiView::Command => vec![
                KeyHint::new("Enter", "Send"),
                KeyHint::new("Up/Down", "History"),
                KeyHint::new("Tab", "Views"),
                KeyHint::new("Ctrl+L", "Clear"),
                KeyHint::new("q", "Quit"),
            ],
            TuiView::Studio => vec![
                KeyHint::new("i", "Insert"),
                KeyHint::new("Esc", "Normal"),
                KeyHint::new("F5", "Run"),
                KeyHint::new("Ctrl+S", "Save"),
                KeyHint::new("c", "Command"),
                KeyHint::new("q", "Back"),
            ],
            // Control is auxiliary view
            TuiView::Control => vec![
                KeyHint::new("Tab", "Next"),
                KeyHint::new("Enter", "Select"),
                KeyHint::new("Esc", "Back"),
                KeyHint::new("q", "Close"),
            ],
        }
    }

    /// Convert keybindings to key hints for display
    ///
    /// Selects the most relevant keybindings based on priority:
    /// - View-specific actions first
    /// - Mode switching actions
    /// - Global actions (quit, help)
    fn hints_from_keybindings(&self, keybindings: Vec<Keybinding>) -> Vec<KeyHint> {
        // Prioritize categories: view-specific > mode > scroll > global
        let priority = |kb: &Keybinding| -> u8 {
            match kb.category {
                KeyCategory::Chat | KeyCategory::Monitor => 0,
                KeyCategory::Action => 1,
                KeyCategory::Mode => 2,
                KeyCategory::Scroll => 3,
                KeyCategory::PanelNav => 4,
                KeyCategory::ViewNav => 5,
                KeyCategory::Global => 6,
            }
        };

        // Sort by priority and take top 6 hints (to fit status bar)
        let mut sorted: Vec<_> = keybindings.iter().collect();
        sorted.sort_by_key(|kb| priority(kb));

        sorted
            .into_iter()
            .take(6)
            .map(|kb| {
                // Convert Keybinding to KeyHint using format_key
                let key_str = format_key(kb.code, kb.modifiers);
                // Use with_owned_key to avoid Box::leak memory leak
                KeyHint::with_owned_key(key_str, kb.description)
            })
            .collect()
    }
}

/// Status bar background — matches header for visual consistency
const STATUS_BAR_BG: Color = Color::Rgb(20, 24, 41);

impl Widget for StatusBar<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        // Fill the entire row with the status bar background first
        let bg_style = Style::default().bg(STATUS_BAR_BG);
        for x in area.x..area.x + area.width {
            buf[(x, area.y)].set_style(bg_style);
        }

        // Get default hints before potentially moving self.hints
        let default = self.default_hints();
        let hints = self.hints.unwrap_or(default);

        // Build left side (input mode indicator + key hints)
        let mut left_spans = vec![Span::raw(" ")];

        // Add input mode indicator if set
        if let Some(mode) = self.input_mode {
            let (mode_char, mode_color) = match mode {
                InputMode::Normal => ('N', self.theme.status_success), // Green for Normal
                InputMode::Insert => ('I', self.theme.status_running), // Amber for Insert
                InputMode::Search => ('/', self.theme.highlight),      // Cyan for Search
            };
            left_spans.push(Span::styled(
                format!("[{}]", mode_char),
                Style::default().fg(mode_color).add_modifier(Modifier::BOLD),
            ));
            left_spans.push(Span::raw(" "));
        }

        // Add custom status text from view (if present)
        if let Some(ref text) = self.custom_text {
            left_spans.push(Span::styled(
                text.clone(),
                Style::default().fg(self.theme.text_primary),
            ));
            left_spans.push(Span::styled(
                "",
                Style::default().fg(self.theme.text_muted),
            ));
        }

        for (i, hint) in hints.iter().enumerate() {
            if i > 0 || self.input_mode.is_some() || self.custom_text.is_some() {
                left_spans.push(Span::raw("  "));
            }
            left_spans.push(Span::styled(
                format!("[{}]", &*hint.key),
                Style::default()
                    .fg(self.theme.highlight)
                    .add_modifier(Modifier::BOLD),
            ));
            left_spans.push(Span::raw(" "));
            left_spans.push(Span::styled(
                hint.action.to_string(),
                Style::default().fg(self.theme.text_secondary),
            ));
        }

        // Build right side (metrics) if available
        let mut right_spans: Vec<Span> = Vec::new();

        if let Some(ref metrics) = self.metrics {
            // Workflow phase indicator (only show if not Idle)
            if metrics.phase != WorkflowPhase::Idle {
                // Phase color based on state
                let phase_color = match metrics.phase {
                    WorkflowPhase::Idle => self.theme.text_muted,
                    WorkflowPhase::Parsing | WorkflowPhase::Validating => {
                        // Animated pulse between cyan and blue
                        use crate::tui::theme::solarized;
                        if (self.frame / 8) % 2 == 0 {
                            solarized::CYAN
                        } else {
                            solarized::BLUE
                        }
                    }
                    WorkflowPhase::Executing => {
                        // Animated pulse between yellow and orange
                        use crate::tui::theme::solarized;
                        if (self.frame / 8) % 2 == 0 {
                            solarized::YELLOW
                        } else {
                            solarized::ORANGE
                        }
                    }
                    WorkflowPhase::Completed => self.theme.status_success,
                    WorkflowPhase::Failed => self.theme.status_failed,
                };

                right_spans.push(Span::styled(
                    metrics.phase.animated_icon(self.frame),
                    Style::default().fg(phase_color),
                ));
                right_spans.push(Span::raw(" "));
                right_spans.push(Span::styled(
                    metrics.phase.name(),
                    Style::default().fg(phase_color),
                ));

                // Show progress bar if present
                if let Some(progress_str) = metrics.format_progress() {
                    right_spans.push(Span::raw(" "));
                    right_spans.push(Span::styled(
                        progress_str,
                        Style::default().fg(self.theme.highlight),
                    ));
                }

                // Show error code if failed
                if metrics.phase == WorkflowPhase::Failed {
                    if let Some(ref code) = metrics.error_code {
                        right_spans.push(Span::raw(" "));
                        right_spans.push(Span::styled(
                            format!("[{}]", code),
                            Style::default()
                                .fg(self.theme.status_failed)
                                .add_modifier(Modifier::BOLD),
                        ));
                    }
                }
            }

            // Provider indicator
            if metrics.provider != Provider::None {
                if !right_spans.is_empty() {
                    right_spans.push(Span::styled(
                        "",
                        Style::default().fg(self.theme.text_muted),
                    ));
                }
                right_spans.push(Span::raw(metrics.provider.icon()));
                right_spans.push(Span::raw(" "));
                right_spans.push(Span::styled(
                    metrics.provider.name(),
                    Style::default()
                        .fg(self.theme.text_primary)
                        .add_modifier(Modifier::BOLD),
                ));
            }

            // Token counter
            if let Some(token_str) = metrics.format_tokens() {
                if !right_spans.is_empty() {
                    right_spans.push(Span::styled(
                        "",
                        Style::default().fg(self.theme.text_muted),
                    ));
                }
                right_spans.push(Span::styled(
                    token_str,
                    Style::default().fg(self.theme.status_running), // Amber for attention
                ));
                right_spans.push(Span::styled(
                    " tokens",
                    Style::default().fg(self.theme.text_secondary),
                ));
            }

            // MCP connection status
            if metrics.mcp_total > 0 {
                if !right_spans.is_empty() {
                    right_spans.push(Span::styled(
                        "",
                        Style::default().fg(self.theme.text_muted),
                    ));
                }

                // Connection status icon with color (animated for Connecting)
                let conn_color = match metrics.connection {
                    ConnectionStatus::Connected => self.theme.status_success,
                    ConnectionStatus::Connecting => {
                        // Animated pulse between yellow and orange
                        use crate::tui::theme::solarized;
                        if (self.frame / 8) % 2 == 0 {
                            solarized::YELLOW
                        } else {
                            solarized::ORANGE
                        }
                    }
                    ConnectionStatus::Disconnected => self.theme.text_muted,
                    ConnectionStatus::Error => self.theme.status_failed,
                };

                right_spans.push(Span::styled(
                    metrics.connection.animated_icon(self.frame),
                    Style::default().fg(conn_color),
                ));
                right_spans.push(Span::raw(" "));
                right_spans.push(Span::styled(
                    "MCP:",
                    Style::default().fg(self.theme.text_secondary),
                ));
                right_spans.push(Span::styled(
                    format!(" {}/{}", metrics.mcp_connected, metrics.mcp_total),
                    Style::default().fg(if metrics.mcp_connected == metrics.mcp_total {
                        self.theme.status_success
                    } else {
                        self.theme.text_primary
                    }),
                ));
            }

            right_spans.push(Span::raw(" "));
        }

        // Calculate widths for layout (use display width, not byte length)
        let left_width: usize = left_spans
            .iter()
            .map(|s| UnicodeWidthStr::width(s.content.as_ref()))
            .sum();
        let right_width: usize = right_spans
            .iter()
            .map(|s| UnicodeWidthStr::width(s.content.as_ref()))
            .sum();

        // Render left side
        let left_line = Line::from(left_spans);
        let left_paragraph = Paragraph::new(left_line).style(Style::default().bg(STATUS_BAR_BG));
        left_paragraph.render(area, buf);

        // Render right side (right-aligned)
        if !right_spans.is_empty() && area.width as usize > left_width + right_width {
            let right_x = area.x + area.width - right_width as u16;
            let right_line = Line::from(right_spans);

            for (i, span) in right_line.spans.iter().enumerate() {
                let x_offset: usize = right_line.spans[..i]
                    .iter()
                    .map(|s| UnicodeWidthStr::width(s.content.as_ref()))
                    .sum();
                buf.set_string(
                    right_x + x_offset as u16,
                    area.y,
                    span.content.as_ref(),
                    span.style,
                );
            }
        }
    }
}

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

    #[test]
    fn test_status_bar_default_hints_studio() {
        let theme = Theme::dark();
        let bar = StatusBar::new(TuiView::Studio, &theme);
        let hints = bar.default_hints();
        // Studio view hints include editor-style shortcuts
        assert!(hints
            .iter()
            .any(|h| h.key.as_ref() == "F5" && h.action.as_ref() == "Run"));
        assert!(hints
            .iter()
            .any(|h| h.key.as_ref() == "Ctrl+S" && h.action.as_ref() == "Save"));
    }

    #[test]
    fn test_status_bar_custom_hints() {
        let theme = Theme::dark();
        let custom = vec![KeyHint::new("x", "Custom")];
        let bar = StatusBar::new(TuiView::Command, &theme).hints(custom);
        assert!(bar.hints.is_some());
        assert_eq!(bar.hints.unwrap().len(), 1);
    }

    #[test]
    fn test_provider_icons_match_canonical() {
        use crate::tui::icons::provider as p;
        assert_eq!(Provider::Claude.icon(), p::CLAUDE);
        assert_eq!(Provider::OpenAI.icon(), p::OPENAI);
        assert_eq!(Provider::Mistral.icon(), p::MISTRAL);
        assert_eq!(Provider::Native.icon(), p::NATIVE);
        assert_eq!(Provider::Groq.icon(), p::GROQ);
        assert_eq!(Provider::DeepSeek.icon(), p::DEEPSEEK);
        assert_eq!(Provider::Mock.icon(), p::MOCK);
        assert_eq!(Provider::None.icon(), "  ");
    }

    #[test]
    fn test_provider_names() {
        assert_eq!(Provider::Claude.name(), "Claude");
        assert_eq!(Provider::OpenAI.name(), "OpenAI");
        assert_eq!(Provider::Mistral.name(), "Mistral");
        assert_eq!(Provider::Native.name(), "Native");
        assert_eq!(Provider::Groq.name(), "Groq");
        assert_eq!(Provider::DeepSeek.name(), "DeepSeek");
        assert_eq!(Provider::Mock.name(), "Mock");
        assert_eq!(Provider::None.name(), "---");
    }

    #[test]
    fn test_connection_status_icons() {
        assert_eq!(ConnectionStatus::Connected.icon(), "");
        assert_eq!(ConnectionStatus::Connecting.icon(), "");
        assert_eq!(ConnectionStatus::Disconnected.icon(), "");
        assert_eq!(ConnectionStatus::Error.icon(), "");
    }

    #[test]
    fn test_status_metrics_token_formatting() {
        let m1 = StatusMetrics::new().tokens(500);
        assert_eq!(m1.format_tokens(), Some("500".to_string()));

        let m2 = StatusMetrics::new().tokens(1500);
        assert_eq!(m2.format_tokens(), Some("1.5k".to_string()));

        let m3 = StatusMetrics::new().tokens(1_500_000);
        assert_eq!(m3.format_tokens(), Some("1.5M".to_string()));

        let m4 = StatusMetrics::new();
        assert_eq!(m4.format_tokens(), None);
    }

    #[test]
    fn test_status_metrics_builder() {
        let metrics = StatusMetrics::new()
            .provider(Provider::Claude)
            .tokens(1234)
            .mcp(2, 3)
            .connection(ConnectionStatus::Connected);

        assert_eq!(metrics.provider, Provider::Claude);
        assert_eq!(metrics.tokens, Some(1234));
        assert_eq!(metrics.mcp_connected, 2);
        assert_eq!(metrics.mcp_total, 3);
        assert_eq!(metrics.connection, ConnectionStatus::Connected);
    }

    #[test]
    fn test_status_bar_with_metrics() {
        let theme = Theme::dark();
        let metrics = StatusMetrics::new().provider(Provider::Claude).tokens(5000);
        let bar = StatusBar::new(TuiView::Command, &theme).metrics(metrics);
        assert!(bar.metrics.is_some());
    }

    #[test]
    fn test_workflow_phase_icons() {
        assert_eq!(WorkflowPhase::Idle.icon(), "");
        assert_eq!(WorkflowPhase::Parsing.icon(), "");
        assert_eq!(WorkflowPhase::Validating.icon(), "");
        assert_eq!(WorkflowPhase::Executing.icon(), "");
        assert_eq!(WorkflowPhase::Completed.icon(), "");
        assert_eq!(WorkflowPhase::Failed.icon(), "");
    }

    #[test]
    fn test_workflow_phase_names() {
        assert_eq!(WorkflowPhase::Idle.name(), "Idle");
        assert_eq!(WorkflowPhase::Parsing.name(), "Parsing");
        assert_eq!(WorkflowPhase::Validating.name(), "Validating");
        assert_eq!(WorkflowPhase::Executing.name(), "Executing");
        assert_eq!(WorkflowPhase::Completed.name(), "Completed");
        assert_eq!(WorkflowPhase::Failed.name(), "Failed");
    }

    #[test]
    fn test_workflow_phase_is_active() {
        assert!(!WorkflowPhase::Idle.is_active());
        assert!(WorkflowPhase::Parsing.is_active());
        assert!(WorkflowPhase::Validating.is_active());
        assert!(WorkflowPhase::Executing.is_active());
        assert!(!WorkflowPhase::Completed.is_active());
        assert!(!WorkflowPhase::Failed.is_active());
    }

    #[test]
    fn test_workflow_phase_animated_icons() {
        // Active phases should return spinning animation
        let parsing_icon = WorkflowPhase::Parsing.animated_icon(0);
        assert!(["", "", "", ""].contains(&parsing_icon));

        // Non-active phases return static icon
        assert_eq!(WorkflowPhase::Idle.animated_icon(0), "");
        assert_eq!(WorkflowPhase::Completed.animated_icon(0), "");
        assert_eq!(WorkflowPhase::Failed.animated_icon(0), "");
    }

    #[test]
    fn test_status_metrics_progress_formatting() {
        let m1 = StatusMetrics::new().progress(0);
        assert_eq!(m1.format_progress(), Some("[░░░░░░░░] 0%".to_string()));

        let m2 = StatusMetrics::new().progress(50);
        assert_eq!(m2.format_progress(), Some("[████░░░░] 50%".to_string()));

        let m3 = StatusMetrics::new().progress(100);
        assert_eq!(m3.format_progress(), Some("[████████] 100%".to_string()));

        let m4 = StatusMetrics::new(); // No progress set
        assert_eq!(m4.format_progress(), None);
    }

    #[test]
    fn test_status_metrics_progress_clamping() {
        // Progress should be clamped to 100
        let m = StatusMetrics::new().progress(150);
        assert_eq!(m.progress, Some(100));
    }

    #[test]
    fn test_status_metrics_phase_builder() {
        let metrics = StatusMetrics::new()
            .phase(WorkflowPhase::Executing)
            .progress(75)
            .error_code("NIKA-042");

        assert_eq!(metrics.phase, WorkflowPhase::Executing);
        assert_eq!(metrics.progress, Some(75));
        assert_eq!(metrics.error_code, Some("NIKA-042".to_string()));
    }

    #[test]
    fn test_status_metrics_default_phase() {
        let metrics = StatusMetrics::new();
        assert_eq!(metrics.phase, WorkflowPhase::Idle);
        assert_eq!(metrics.progress, None);
        assert_eq!(metrics.error_code, None);
    }
}