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
//! Verification Cache Module
//!
//! TTL-based caching for provider and MCP server verification results.
//! Prevents redundant API calls when opening the provider selector.
//!
//! ## Usage
//!
//! ```rust,ignore
//! use nika::tui::verification::{VerificationCache, VerificationEntry};
//! use std::time::Duration;
//!
//! let mut cache = VerificationCache::new(Duration::from_secs(30));
//!
//! // Check if cached
//! if let Some(entry) = cache.get_provider("claude") {
//!     if cache.is_valid(entry) {
//!         // Use cached result
//!         return;
//!     }
//! }
//!
//! // Store new result
//! cache.set_provider("claude".to_string(), entry);
//! ```

use rustc_hash::FxHashMap;
use std::time::{Duration, Instant};

use super::widgets::VerifyStatus;

/// Cached verification result for a provider or MCP server
#[derive(Debug, Clone)]
pub struct VerificationEntry {
    /// Verification status (Unknown, Verifying, Verified, Failed)
    pub status: VerifyStatus,
    /// Measured latency (if verified)
    pub latency: Option<Duration>,
    /// Number of tools (MCP servers only)
    pub tool_count: Option<usize>,
    /// Model name (providers only)
    pub model: Option<String>,
    /// Error message (if failed)
    pub error: Option<String>,
    /// When this entry was created
    pub verified_at: Instant,
}

impl VerificationEntry {
    /// Create a new verified entry with latency
    pub fn verified(latency: Duration, model: Option<String>) -> Self {
        Self {
            status: VerifyStatus::Verified,
            latency: Some(latency),
            tool_count: None,
            model,
            error: None,
            verified_at: Instant::now(),
        }
    }

    /// Create a new verified MCP entry with latency and tool count
    pub fn verified_mcp(latency: Duration, tool_count: usize) -> Self {
        Self {
            status: VerifyStatus::Verified,
            latency: Some(latency),
            tool_count: Some(tool_count),
            model: None,
            error: None,
            verified_at: Instant::now(),
        }
    }

    /// Create a new failed entry with error message
    pub fn failed(error: String) -> Self {
        Self {
            status: VerifyStatus::Failed,
            latency: None,
            tool_count: None,
            model: None,
            error: Some(error),
            verified_at: Instant::now(),
        }
    }

    /// Create a verifying (in-progress) entry
    pub fn verifying() -> Self {
        Self {
            status: VerifyStatus::Verifying,
            latency: None,
            tool_count: None,
            model: None,
            error: None,
            verified_at: Instant::now(),
        }
    }
}

/// TTL-based verification cache
///
/// Stores verification results for providers and MCP servers with automatic
/// expiration. Default TTL is 30 seconds.
#[derive(Debug)]
pub struct VerificationCache {
    /// Cached provider verification results
    providers: FxHashMap<String, VerificationEntry>,
    /// Cached MCP server verification results
    mcp_servers: FxHashMap<String, VerificationEntry>,
    /// Time-to-live for cache entries
    ttl: Duration,
}

impl Default for VerificationCache {
    fn default() -> Self {
        Self::new(Duration::from_secs(30))
    }
}

impl VerificationCache {
    /// Create a new cache with the specified TTL
    pub fn new(ttl: Duration) -> Self {
        Self {
            providers: FxHashMap::default(),
            mcp_servers: FxHashMap::default(),
            ttl,
        }
    }

    /// Get a cached provider entry
    pub fn get_provider(&self, id: &str) -> Option<&VerificationEntry> {
        self.providers.get(id)
    }

    /// Get a cached MCP server entry
    pub fn get_mcp(&self, name: &str) -> Option<&VerificationEntry> {
        self.mcp_servers.get(name)
    }

    /// Store a provider verification result
    pub fn set_provider(&mut self, id: String, entry: VerificationEntry) {
        self.providers.insert(id, entry);
    }

    /// Store an MCP server verification result
    pub fn set_mcp(&mut self, name: String, entry: VerificationEntry) {
        self.mcp_servers.insert(name, entry);
    }

    /// Check if an entry is still valid (within TTL)
    pub fn is_valid(&self, entry: &VerificationEntry) -> bool {
        entry.verified_at.elapsed() < self.ttl
    }

    /// Check if a provider has a valid cached entry
    pub fn has_valid_provider(&self, id: &str) -> bool {
        self.get_provider(id)
            .map(|e| self.is_valid(e))
            .unwrap_or(false)
    }

    /// Check if an MCP server has a valid cached entry
    pub fn has_valid_mcp(&self, name: &str) -> bool {
        self.get_mcp(name)
            .map(|e| self.is_valid(e))
            .unwrap_or(false)
    }

    /// Invalidate all cached entries
    pub fn invalidate_all(&mut self) {
        self.providers.clear();
        self.mcp_servers.clear();
    }

    /// Invalidate a specific provider
    pub fn invalidate_provider(&mut self, id: &str) {
        self.providers.remove(id);
    }

    /// Invalidate a specific MCP server
    pub fn invalidate_mcp(&mut self, name: &str) {
        self.mcp_servers.remove(name);
    }

    /// Get the number of cached providers
    pub fn provider_count(&self) -> usize {
        self.providers.len()
    }

    /// Get the number of cached MCP servers
    pub fn mcp_count(&self) -> usize {
        self.mcp_servers.len()
    }

    /// Get count of verified providers
    pub fn verified_provider_count(&self) -> usize {
        self.providers
            .values()
            .filter(|e| e.status == VerifyStatus::Verified && self.is_valid(e))
            .count()
    }

    /// Check if ANY provider has been verified
    pub fn has_any_verified_provider(&self) -> bool {
        self.providers
            .values()
            .any(|e| e.status == VerifyStatus::Verified && self.is_valid(e))
    }

    /// Get count of verified MCP servers
    pub fn verified_mcp_count(&self) -> usize {
        self.mcp_servers
            .values()
            .filter(|e| e.status == VerifyStatus::Verified && self.is_valid(e))
            .count()
    }

    /// Get the TTL duration
    pub fn ttl(&self) -> Duration {
        self.ttl
    }
}

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

    #[test]
    fn test_cache_new_empty() {
        let cache = VerificationCache::new(Duration::from_secs(30));
        assert_eq!(cache.provider_count(), 0);
        assert_eq!(cache.mcp_count(), 0);
        assert_eq!(cache.ttl(), Duration::from_secs(30));
    }

    #[test]
    fn test_cache_default_ttl() {
        let cache = VerificationCache::default();
        assert_eq!(cache.ttl(), Duration::from_secs(30));
    }

    #[test]
    fn test_cache_set_get_provider() {
        let mut cache = VerificationCache::new(Duration::from_secs(30));

        let entry = VerificationEntry::verified(
            Duration::from_millis(450),
            Some("claude-sonnet-4".to_string()),
        );

        cache.set_provider("claude".to_string(), entry);

        assert_eq!(cache.provider_count(), 1);

        let retrieved = cache.get_provider("claude").unwrap();
        assert_eq!(retrieved.status, VerifyStatus::Verified);
        assert_eq!(retrieved.latency, Some(Duration::from_millis(450)));
        assert_eq!(retrieved.model, Some("claude-sonnet-4".to_string()));
    }

    #[test]
    fn test_cache_set_get_mcp() {
        let mut cache = VerificationCache::new(Duration::from_secs(30));

        let entry = VerificationEntry::verified_mcp(Duration::from_millis(45), 12);

        cache.set_mcp("novanet".to_string(), entry);

        assert_eq!(cache.mcp_count(), 1);

        let retrieved = cache.get_mcp("novanet").unwrap();
        assert_eq!(retrieved.status, VerifyStatus::Verified);
        assert_eq!(retrieved.latency, Some(Duration::from_millis(45)));
        assert_eq!(retrieved.tool_count, Some(12));
    }

    #[test]
    fn test_cache_ttl_valid() {
        let cache = VerificationCache::new(Duration::from_secs(30));
        let entry = VerificationEntry::verified(Duration::from_millis(100), None);

        // Fresh entry should be valid
        assert!(cache.is_valid(&entry));
    }

    #[test]
    fn test_cache_ttl_expired() {
        // Very short TTL for testing
        let cache = VerificationCache::new(Duration::from_millis(10));
        let entry = VerificationEntry::verified(Duration::from_millis(100), None);

        // Wait for expiry
        sleep(Duration::from_millis(15));

        // Entry should now be invalid
        assert!(!cache.is_valid(&entry));
    }

    #[test]
    fn test_cache_has_valid_provider() {
        let mut cache = VerificationCache::new(Duration::from_secs(30));

        // No entry yet
        assert!(!cache.has_valid_provider("claude"));

        // Add entry
        cache.set_provider(
            "claude".to_string(),
            VerificationEntry::verified(Duration::from_millis(100), None),
        );

        // Should be valid now
        assert!(cache.has_valid_provider("claude"));
    }

    #[test]
    fn test_cache_invalidate_all() {
        let mut cache = VerificationCache::new(Duration::from_secs(30));

        cache.set_provider(
            "claude".to_string(),
            VerificationEntry::verified(Duration::from_millis(100), None),
        );
        cache.set_provider(
            "openai".to_string(),
            VerificationEntry::verified(Duration::from_millis(200), None),
        );
        cache.set_mcp(
            "novanet".to_string(),
            VerificationEntry::verified_mcp(Duration::from_millis(50), 10),
        );

        assert_eq!(cache.provider_count(), 2);
        assert_eq!(cache.mcp_count(), 1);

        cache.invalidate_all();

        assert_eq!(cache.provider_count(), 0);
        assert_eq!(cache.mcp_count(), 0);
    }

    #[test]
    fn test_cache_invalidate_specific() {
        let mut cache = VerificationCache::new(Duration::from_secs(30));

        cache.set_provider(
            "claude".to_string(),
            VerificationEntry::verified(Duration::from_millis(100), None),
        );
        cache.set_provider(
            "openai".to_string(),
            VerificationEntry::verified(Duration::from_millis(200), None),
        );

        cache.invalidate_provider("claude");

        assert_eq!(cache.provider_count(), 1);
        assert!(cache.get_provider("claude").is_none());
        assert!(cache.get_provider("openai").is_some());
    }

    #[test]
    fn test_cache_failed_entry() {
        let mut cache = VerificationCache::new(Duration::from_secs(30));

        let entry = VerificationEntry::failed("Connection refused".to_string());
        cache.set_provider("native".to_string(), entry);

        let retrieved = cache.get_provider("native").unwrap();
        assert_eq!(retrieved.status, VerifyStatus::Failed);
        assert_eq!(retrieved.error, Some("Connection refused".to_string()));
        assert!(retrieved.latency.is_none());
    }

    #[test]
    fn test_cache_verifying_entry() {
        let entry = VerificationEntry::verifying();
        assert_eq!(entry.status, VerifyStatus::Verifying);
        assert!(entry.latency.is_none());
        assert!(entry.error.is_none());
    }

    #[test]
    fn test_verified_provider_count() {
        let mut cache = VerificationCache::new(Duration::from_secs(30));

        cache.set_provider(
            "claude".to_string(),
            VerificationEntry::verified(Duration::from_millis(100), None),
        );
        cache.set_provider(
            "openai".to_string(),
            VerificationEntry::verified(Duration::from_millis(200), None),
        );
        cache.set_provider(
            "native".to_string(),
            VerificationEntry::failed("Offline".to_string()),
        );

        assert_eq!(cache.verified_provider_count(), 2);
    }

    #[test]
    fn test_verified_mcp_count() {
        let mut cache = VerificationCache::new(Duration::from_secs(30));

        cache.set_mcp(
            "novanet".to_string(),
            VerificationEntry::verified_mcp(Duration::from_millis(50), 12),
        );
        cache.set_mcp(
            "firecrawl".to_string(),
            VerificationEntry::failed("Timeout".to_string()),
        );

        assert_eq!(cache.verified_mcp_count(), 1);
    }
}