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
//! Chat Node Box Widget
//!
//! Renders individual nodes in the Chat DAG visualization.
//! Supports User, Assistant, ToolCall, System, and Error node types.
//!
//! Chat-as-DAG architecture

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
    widgets::{Block, Borders, Widget},
};

use crate::tui::tokens::compat;

// ═══════════════════════════════════════════════════════════════════════════
// CHAT NODE KIND
// ═══════════════════════════════════════════════════════════════════════════

/// Kind of node in the Chat DAG
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChatNodeKind {
    /// User message
    User,
    /// Assistant response
    Assistant,
    /// Tool call (MCP invoke)
    ToolCall,
    /// System message
    System,
    /// Error state
    Error,
}

impl ChatNodeKind {
    /// Get icon for this node kind
    pub fn icon(&self) -> &'static str {
        match self {
            ChatNodeKind::User => "👤",
            ChatNodeKind::Assistant => "🤖",
            ChatNodeKind::ToolCall => "🔌",
            ChatNodeKind::System => "⚙️",
            ChatNodeKind::Error => "",
        }
    }

    /// All node kinds
    pub fn all() -> &'static [ChatNodeKind] {
        &[
            ChatNodeKind::User,
            ChatNodeKind::Assistant,
            ChatNodeKind::ToolCall,
            ChatNodeKind::System,
            ChatNodeKind::Error,
        ]
    }

    /// Default color for this node kind
    pub fn color(&self) -> Color {
        match self {
            ChatNodeKind::User => compat::CYAN_500,
            ChatNodeKind::Assistant => compat::GREEN_500,
            ChatNodeKind::ToolCall => compat::PINK_500,
            ChatNodeKind::System => compat::AMBER_500,
            ChatNodeKind::Error => compat::RED_500,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// CHAT NODE STATE
// ═══════════════════════════════════════════════════════════════════════════

/// State of a node in execution
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ChatNodeState {
    /// Idle - not yet started
    #[default]
    Idle,
    /// Running - currently executing
    Running,
    /// Complete - finished successfully
    Complete,
    /// Failed - execution failed
    Failed,
}

impl ChatNodeState {
    /// Check if node is currently running
    pub fn is_running(&self) -> bool {
        matches!(self, ChatNodeState::Running)
    }

    /// Get border color for this state
    pub fn border_color(&self) -> Color {
        match self {
            ChatNodeState::Idle => compat::SLATE_500,
            ChatNodeState::Running => compat::AMBER_500,
            ChatNodeState::Complete => compat::GREEN_500,
            ChatNodeState::Failed => compat::RED_500,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// CHAT NODE BOX
// ═══════════════════════════════════════════════════════════════════════════

/// A box widget representing a node in the Chat DAG
#[derive(Debug, Clone)]
pub struct ChatNodeBox {
    /// Unique identifier
    id: String,
    /// Node kind (User, Assistant, etc.)
    kind: ChatNodeKind,
    /// Display label (truncated message preview)
    label: String,
    /// Stable node index for @N reference
    index: u32,
    /// Current execution state
    state: ChatNodeState,
    /// Whether this node is selected/focused
    selected: bool,
    /// Animation tick for pulse effect
    animation_tick: u8,
}

impl ChatNodeBox {
    /// Create a new chat node box
    pub fn new(id: &str, kind: ChatNodeKind) -> Self {
        Self {
            id: id.to_string(),
            kind,
            label: String::new(),
            index: 0,
            state: ChatNodeState::default(),
            selected: false,
            animation_tick: 0,
        }
    }

    /// Set the display label
    pub fn with_label(mut self, label: &str) -> Self {
        self.label = label.to_string();
        self
    }

    /// Set the stable node index (@N reference)
    pub fn with_index(mut self, index: u32) -> Self {
        self.index = index;
        self
    }

    /// Set the execution state
    pub fn with_state(mut self, state: ChatNodeState) -> Self {
        self.state = state;
        self
    }

    /// Set whether this node is selected
    pub fn with_selected(mut self, selected: bool) -> Self {
        self.selected = selected;
        self
    }

    // Getters
    /// Get the node ID
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Get the node kind
    pub fn kind(&self) -> ChatNodeKind {
        self.kind
    }

    /// Get the display label
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Get the stable node index
    pub fn index(&self) -> u32 {
        self.index
    }

    /// Get the current state
    pub fn state(&self) -> ChatNodeState {
        self.state
    }

    /// Check if selected
    pub fn selected(&self) -> bool {
        self.selected
    }

    /// Advance animation state
    pub fn tick(&mut self) {
        if self.state.is_running() {
            self.animation_tick = self.animation_tick.wrapping_add(1);
        }
    }

    /// Get pulse intensity (0.0 - 1.0) for running animation
    pub fn pulse_intensity(&self) -> f32 {
        if !self.state.is_running() {
            return 0.0;
        }
        // Sine wave pulse
        let t = self.animation_tick as f32 / 30.0;
        (t.sin() + 1.0) / 2.0
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// WIDGET IMPLEMENTATION
// ═══════════════════════════════════════════════════════════════════════════

impl Widget for ChatNodeBox {
    fn render(self, area: Rect, buf: &mut Buffer) {
        // Skip if area too small
        if area.height < 3 || area.width < 10 {
            return;
        }

        // Calculate dimensions
        let width = area.width.min(30);
        let _height = 3.min(area.height);

        // Border style based on state
        let border_color = if self.selected {
            self.kind.color()
        } else {
            self.state.border_color()
        };

        let border_style = Style::default().fg(border_color);
        let border_style = if self.selected || self.state.is_running() {
            border_style.add_modifier(Modifier::BOLD)
        } else {
            border_style
        };

        // Draw border
        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(border_style);

        let inner = block.inner(area);
        block.render(area, buf);

        // Draw content: "@N 🔌 Label"
        let content = format!(
            "@{} {} {}",
            self.index,
            self.kind.icon(),
            truncate_label(&self.label, (width.saturating_sub(8)) as usize)
        );

        let content_style = Style::default().fg(self.kind.color());
        buf.set_string(inner.x, inner.y, &content, content_style);
    }
}

/// Truncate label to fit within max length, adding ellipsis
fn truncate_label(label: &str, max_len: usize) -> String {
    if label.chars().count() <= max_len {
        label.to_string()
    } else if max_len <= 1 {
        "".to_string()
    } else {
        let truncated: String = label.chars().take(max_len.saturating_sub(1)).collect();
        format!("{}", truncated)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════

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

    // --- ChatNodeKind tests ---

    #[test]
    fn test_chat_node_kind_icons() {
        assert_eq!(ChatNodeKind::User.icon(), "👤");
        assert_eq!(ChatNodeKind::Assistant.icon(), "🤖");
        assert_eq!(ChatNodeKind::ToolCall.icon(), "🔌");
        assert_eq!(ChatNodeKind::System.icon(), "⚙️");
        assert_eq!(ChatNodeKind::Error.icon(), "");
    }

    #[test]
    fn test_chat_node_kind_all_variants() {
        let kinds = ChatNodeKind::all();
        assert_eq!(kinds.len(), 5);
    }

    #[test]
    fn test_chat_node_kind_colors() {
        assert_eq!(ChatNodeKind::User.color(), compat::CYAN_500);
        assert_eq!(ChatNodeKind::Assistant.color(), compat::GREEN_500);
        assert_eq!(ChatNodeKind::ToolCall.color(), compat::PINK_500);
        assert_eq!(ChatNodeKind::System.color(), compat::AMBER_500);
        assert_eq!(ChatNodeKind::Error.color(), compat::RED_500);
    }

    // --- ChatNodeState tests ---

    #[test]
    fn test_chat_node_state_is_running() {
        assert!(!ChatNodeState::Idle.is_running());
        assert!(ChatNodeState::Running.is_running());
        assert!(!ChatNodeState::Complete.is_running());
        assert!(!ChatNodeState::Failed.is_running());
    }

    #[test]
    fn test_chat_node_state_border_color() {
        assert_eq!(ChatNodeState::Idle.border_color(), compat::SLATE_500);
        assert_eq!(ChatNodeState::Running.border_color(), compat::AMBER_500);
        assert_eq!(ChatNodeState::Complete.border_color(), compat::GREEN_500);
        assert_eq!(ChatNodeState::Failed.border_color(), compat::RED_500);
    }

    #[test]
    fn test_chat_node_state_default() {
        let state = ChatNodeState::default();
        assert_eq!(state, ChatNodeState::Idle);
    }

    // --- ChatNodeBox creation tests ---

    #[test]
    fn test_chat_node_box_creation() {
        let node = ChatNodeBox::new("msg-001", ChatNodeKind::User)
            .with_label("Hello world")
            .with_index(1);

        assert_eq!(node.id(), "msg-001");
        assert_eq!(node.kind(), ChatNodeKind::User);
        assert_eq!(node.label(), "Hello world");
        assert_eq!(node.index(), 1);
    }

    #[test]
    fn test_chat_node_box_default_state() {
        let node = ChatNodeBox::new("msg-001", ChatNodeKind::User);
        assert_eq!(node.state(), ChatNodeState::Idle);
        assert!(!node.selected());
    }

    #[test]
    fn test_chat_node_box_builder_pattern() {
        let node = ChatNodeBox::new("msg-002", ChatNodeKind::Assistant)
            .with_label("I'll help you...")
            .with_index(2)
            .with_state(ChatNodeState::Running)
            .with_selected(true);

        assert_eq!(node.id(), "msg-002");
        assert_eq!(node.kind(), ChatNodeKind::Assistant);
        assert_eq!(node.label(), "I'll help you...");
        assert_eq!(node.index(), 2);
        assert_eq!(node.state(), ChatNodeState::Running);
        assert!(node.selected());
    }

    // --- Animation tests ---

    #[test]
    fn test_chat_node_box_tick() {
        let mut node =
            ChatNodeBox::new("msg-001", ChatNodeKind::User).with_state(ChatNodeState::Running);

        let initial = node.animation_tick;
        node.tick();
        assert_eq!(node.animation_tick, initial.wrapping_add(1));
    }

    #[test]
    fn test_chat_node_box_tick_only_when_running() {
        let mut node =
            ChatNodeBox::new("msg-001", ChatNodeKind::User).with_state(ChatNodeState::Idle);

        let initial = node.animation_tick;
        node.tick();
        // Should not change when not running
        assert_eq!(node.animation_tick, initial);
    }

    #[test]
    fn test_chat_node_box_pulse_intensity() {
        let node =
            ChatNodeBox::new("msg-001", ChatNodeKind::User).with_state(ChatNodeState::Running);

        let intensity = node.pulse_intensity();
        assert!((0.0..=1.0).contains(&intensity));
    }

    #[test]
    fn test_no_pulse_when_idle() {
        let node = ChatNodeBox::new("msg-001", ChatNodeKind::User).with_state(ChatNodeState::Idle);

        assert_eq!(node.pulse_intensity(), 0.0);
    }

    // --- Truncation tests ---

    #[test]
    fn test_truncate_label_short() {
        let result = truncate_label("Hello", 10);
        assert_eq!(result, "Hello");
    }

    #[test]
    fn test_truncate_label_long() {
        let result = truncate_label("Hello, World!", 8);
        assert_eq!(result, "Hello, …");
    }

    #[test]
    fn test_truncate_label_empty() {
        let result = truncate_label("", 10);
        assert_eq!(result, "");
    }

    #[test]
    fn test_truncate_label_exact_fit() {
        let result = truncate_label("Hello", 5);
        assert_eq!(result, "Hello");
    }

    #[test]
    fn test_truncate_label_unicode() {
        // Unicode characters should be handled correctly
        let result = truncate_label("你好世界", 3);
        assert_eq!(result, "你好…");
    }

    // --- Render tests ---

    #[test]
    fn test_chat_node_box_render_basic() {
        let node = ChatNodeBox::new("msg-001", ChatNodeKind::User)
            .with_label("Hello")
            .with_index(1);

        let mut buf = Buffer::empty(Rect::new(0, 0, 20, 3));
        node.render(buf.area, &mut buf);

        // Should contain icon and index
        let content = buffer_to_string(&buf);
        assert!(content.contains("@1"));
    }

    #[test]
    fn test_chat_node_box_render_selected() {
        let node = ChatNodeBox::new("msg-001", ChatNodeKind::User)
            .with_label("Hello")
            .with_index(1)
            .with_selected(true);

        let mut buf = Buffer::empty(Rect::new(0, 0, 20, 3));
        node.render(buf.area, &mut buf);

        // Should render without panic
        let content = buffer_to_string(&buf);
        assert!(!content.is_empty());
    }

    #[test]
    fn test_chat_node_box_render_running() {
        let node = ChatNodeBox::new("msg-001", ChatNodeKind::ToolCall)
            .with_label("search...")
            .with_index(3)
            .with_state(ChatNodeState::Running);

        let mut buf = Buffer::empty(Rect::new(0, 0, 25, 3));
        node.render(buf.area, &mut buf);

        // Should render without panic
        let content = buffer_to_string(&buf);
        assert!(content.contains("@3"));
    }

    #[test]
    fn test_chat_node_box_render_too_small() {
        let node = ChatNodeBox::new("msg-001", ChatNodeKind::User)
            .with_label("Hello")
            .with_index(1);

        // Area too small - should skip rendering
        let mut buf = Buffer::empty(Rect::new(0, 0, 5, 2));
        node.render(Rect::new(0, 0, 5, 2), &mut buf);

        // Buffer should remain empty (default cells)
        let cell = buf.cell((0, 0)).unwrap();
        assert_eq!(cell.symbol(), " ");
    }

    // --- Integration test ---

    #[test]
    fn test_chat_node_box_exported() {
        // This test verifies the type is accessible
        let _ = ChatNodeBox::new("test", ChatNodeKind::User);
    }

    /// Helper to convert buffer to string for assertions
    fn buffer_to_string(buf: &Buffer) -> String {
        buf.content.iter().map(|c| c.symbol()).collect()
    }
}