opencrabs 0.3.8

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
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
//! Custom provider tests.
//!
//! Tests factory fallback behavior, custom providers with optional API keys,
//! local providers (LM Studio, Ollama), and no-crash guarantees.

use crate::brain::Provider;
use crate::brain::provider::custom_openai_compatible::OpenAIProvider;
use crate::brain::provider::factory::{create_provider, create_provider_by_name};
use crate::config::{Config, ProviderConfig, ProviderConfigs};
use std::collections::BTreeMap;

// ── Custom provider creation ────────────────────────────────────

#[test]
fn custom_provider_without_api_key() {
    // Local providers (LM Studio, Ollama) don't need an API key
    let provider = OpenAIProvider::with_base_url(
        String::new(), // empty key
        "http://localhost:1234/v1/chat/completions".to_string(),
    )
    .with_name("lmstudio");
    assert_eq!(provider.name(), "lmstudio");
}

#[test]
fn custom_provider_with_api_key() {
    let provider = OpenAIProvider::with_base_url(
        "sk-test-key".to_string(),
        "https://api.example.com/v1/chat/completions".to_string(),
    )
    .with_name("my-remote");
    assert_eq!(provider.name(), "my-remote");
}

#[test]
fn custom_provider_default_model() {
    let provider = OpenAIProvider::with_base_url(
        String::new(),
        "http://localhost:1234/v1/chat/completions".to_string(),
    )
    .with_name("ollama")
    .with_default_model("llama3".to_string());
    assert_eq!(provider.default_model(), "llama3");
}

// ── Factory: custom providers from config ───────────────────────

fn config_with_custom(name: &str, api_key: Option<String>, base_url: Option<String>) -> Config {
    let mut custom_map = BTreeMap::new();
    custom_map.insert(
        name.to_string(),
        ProviderConfig {
            enabled: true,
            api_key,
            base_url,
            default_model: Some("test-model".to_string()),
            models: vec![],
            vision_model: None,
            ..Default::default()
        },
    );
    Config {
        providers: ProviderConfigs {
            custom: Some(custom_map),
            ..Default::default()
        },
        ..Default::default()
    }
}

#[tokio::test]
async fn factory_creates_custom_without_api_key() {
    let config = config_with_custom(
        "lmstudio",
        None,
        Some("http://localhost:1234/v1".to_string()),
    );
    let result = create_provider(&config).await;
    assert!(result.is_ok());
    let provider = result.unwrap();
    assert_eq!(provider.name(), "lmstudio");
}

#[tokio::test]
async fn factory_creates_custom_with_api_key() {
    let config = config_with_custom(
        "remote-llm",
        Some("sk-test".to_string()),
        Some("https://api.example.com/v1".to_string()),
    );
    let result = create_provider(&config).await;
    assert!(result.is_ok());
    let provider = result.unwrap();
    assert_eq!(provider.name(), "remote-llm");
}

#[tokio::test]
async fn factory_creates_custom_with_empty_api_key() {
    let config = config_with_custom(
        "ollama",
        Some(String::new()),
        Some("http://localhost:11434/v1".to_string()),
    );
    let result = create_provider(&config).await;
    assert!(result.is_ok());
    let provider = result.unwrap();
    assert_eq!(provider.name(), "ollama");
}

#[tokio::test]
async fn factory_custom_auto_appends_chat_completions() {
    // base_url without /chat/completions should get it appended
    let config = config_with_custom(
        "test-local",
        None,
        Some("http://localhost:1234/v1".to_string()),
    );
    let result = create_provider(&config).await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn factory_custom_preserves_chat_completions_suffix() {
    // base_url already has /chat/completions — should not double-append
    let config = config_with_custom(
        "test-local",
        None,
        Some("http://localhost:1234/v1/chat/completions".to_string()),
    );
    let result = create_provider(&config).await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn factory_custom_default_base_url() {
    // No base_url → defaults to localhost:1234
    let config = config_with_custom("local", None, None);
    let result = create_provider(&config).await;
    assert!(result.is_ok());
}

// ── Factory: create_provider_by_name ────────────────────────────

#[tokio::test]
async fn create_by_name_custom_prefix() {
    let config = config_with_custom(
        "mylocal",
        None,
        Some("http://localhost:1234/v1".to_string()),
    );
    let result = create_provider_by_name(&config, "custom:mylocal").await;
    assert!(result.is_ok());
    assert_eq!(result.unwrap().name(), "mylocal");
}

#[tokio::test]
async fn create_by_name_unknown_custom() {
    let config = Config::default();
    let result = create_provider_by_name(&config, "custom:nonexistent").await;
    assert!(result.is_err());
}

#[tokio::test]
async fn create_by_name_legacy_custom() {
    // Legacy sessions store just the custom name without "custom:" prefix
    let config = config_with_custom(
        "lmstudio",
        None,
        Some("http://localhost:1234/v1".to_string()),
    );
    let result = create_provider_by_name(&config, "lmstudio").await;
    assert!(result.is_ok());
    assert_eq!(result.unwrap().name(), "lmstudio");
}

// ── Factory: no-crash guarantees ────────────────────────────────

#[tokio::test]
async fn factory_never_crashes_empty_config() {
    let config = Config::default();
    let result = create_provider(&config).await;
    // Must succeed — returns PlaceholderProvider
    assert!(result.is_ok());
}

#[tokio::test]
async fn factory_never_crashes_all_missing_keys() {
    // All providers enabled but none have API keys
    let config = Config {
        providers: ProviderConfigs {
            anthropic: Some(ProviderConfig {
                enabled: true,
                api_key: None,
                ..Default::default()
            }),
            openai: Some(ProviderConfig {
                enabled: true,
                api_key: None,
                base_url: None,
                ..Default::default()
            }),
            github: Some(ProviderConfig {
                enabled: true,
                api_key: None,
                ..Default::default()
            }),
            gemini: Some(ProviderConfig {
                enabled: true,
                api_key: None,
                ..Default::default()
            }),
            openrouter: Some(ProviderConfig {
                enabled: true,
                api_key: None,
                ..Default::default()
            }),
            minimax: Some(ProviderConfig {
                enabled: true,
                api_key: None,
                ..Default::default()
            }),
            ..Default::default()
        },
        ..Default::default()
    };
    let result = create_provider(&config).await;
    // Must succeed — falls back to PlaceholderProvider
    assert!(result.is_ok());
}

#[tokio::test]
async fn factory_falls_back_when_primary_fails() {
    // Anthropic enabled but no key, OpenAI has key → should fall back to OpenAI
    let config = Config {
        providers: ProviderConfigs {
            anthropic: Some(ProviderConfig {
                enabled: true,
                api_key: None,
                ..Default::default()
            }),
            openai: Some(ProviderConfig {
                enabled: true,
                api_key: Some("test-key".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        },
        ..Default::default()
    };
    let result = create_provider(&config).await;
    assert!(result.is_ok());
    assert_eq!(result.unwrap().name(), "openai");
}

#[tokio::test]
async fn factory_priority_order_anthropic_first() {
    // Both Anthropic and OpenAI have keys — Anthropic should win
    let config = Config {
        providers: ProviderConfigs {
            anthropic: Some(ProviderConfig {
                enabled: true,
                api_key: Some("anthropic-key".to_string()),
                ..Default::default()
            }),
            openai: Some(ProviderConfig {
                enabled: true,
                api_key: Some("openai-key".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        },
        ..Default::default()
    };
    let result = create_provider(&config).await;
    assert!(result.is_ok());
    assert_eq!(result.unwrap().name(), "anthropic");
}

#[tokio::test]
async fn factory_custom_before_placeholder() {
    // Only custom provider configured — should use it, not placeholder
    let config = config_with_custom(
        "ollama",
        None,
        Some("http://localhost:11434/v1".to_string()),
    );
    let result = create_provider(&config).await;
    assert!(result.is_ok());
    assert_ne!(result.unwrap().name(), "placeholder");
}

// ── Multiple custom providers ───────────────────────────────────

#[test]
fn active_custom_picks_first_enabled() {
    let mut custom_map = BTreeMap::new();
    custom_map.insert(
        "disabled-one".to_string(),
        ProviderConfig {
            enabled: false,
            base_url: Some("http://localhost:1111/v1".to_string()),
            ..Default::default()
        },
    );
    custom_map.insert(
        "enabled-one".to_string(),
        ProviderConfig {
            enabled: true,
            base_url: Some("http://localhost:2222/v1".to_string()),
            default_model: Some("model-a".to_string()),
            ..Default::default()
        },
    );
    let configs = ProviderConfigs {
        custom: Some(custom_map),
        ..Default::default()
    };
    let active = configs.active_custom();
    assert!(active.is_some());
    let (name, cfg) = active.unwrap();
    assert_eq!(name, "enabled-one");
    assert!(cfg.enabled);
}

#[test]
fn no_active_custom_when_all_disabled() {
    let mut custom_map = BTreeMap::new();
    custom_map.insert(
        "off".to_string(),
        ProviderConfig {
            enabled: false,
            ..Default::default()
        },
    );
    let configs = ProviderConfigs {
        custom: Some(custom_map),
        ..Default::default()
    };
    assert!(configs.active_custom().is_none());
}

#[test]
fn no_active_custom_when_none() {
    let configs = ProviderConfigs::default();
    assert!(configs.active_custom().is_none());
}

// ── Custom provider list (model selector / onboarding) ──────────

#[test]
fn wizard_is_custom_for_new_and_existing() {
    use crate::tui::onboarding::OnboardingWizard;
    use crate::tui::provider_selector::{CUSTOM_INSTANCES_START, CUSTOM_PROVIDER_IDX};
    let mut wizard = OnboardingWizard::new();
    // CUSTOM_PROVIDER_IDX = "+ New Custom Provider"
    wizard.ps.selected_provider = CUSTOM_PROVIDER_IDX;
    assert!(wizard.ps.is_custom());
    // CUSTOM_INSTANCES_START+ = existing custom providers
    wizard.ps.selected_provider = CUSTOM_INSTANCES_START;
    assert!(wizard.ps.is_custom());
    wizard.ps.selected_provider = CUSTOM_INSTANCES_START + 1;
    assert!(wizard.ps.is_custom());
    // Index < CUSTOM_PROVIDER_IDX = not custom
    wizard.ps.selected_provider = 0;
    assert!(!wizard.ps.is_custom());
    wizard.ps.selected_provider = CUSTOM_PROVIDER_IDX - 1;
    assert!(!wizard.ps.is_custom());
}

#[test]
fn wizard_current_provider_clamps_for_existing_custom() {
    use crate::tui::onboarding::{OnboardingWizard, PROVIDERS};
    use crate::tui::provider_selector::{CUSTOM_INSTANCES_START, CUSTOM_PROVIDER_IDX};
    let mut wizard = OnboardingWizard::new();
    // CUSTOM_INSTANCES_START+ should map to the Custom entry in PROVIDERS
    wizard.ps.selected_provider = CUSTOM_INSTANCES_START;
    assert_eq!(
        wizard.ps.current_provider().name,
        PROVIDERS[CUSTOM_PROVIDER_IDX].name
    );
    wizard.ps.selected_provider = 99;
    assert_eq!(
        wizard.ps.current_provider().name,
        PROVIDERS[CUSTOM_PROVIDER_IDX].name
    );
}

#[test]
fn wizard_load_custom_fields_clears_for_new() {
    use crate::tui::onboarding::OnboardingWizard;
    use crate::tui::provider_selector::CUSTOM_PROVIDER_IDX;
    let mut wizard = OnboardingWizard::new();
    wizard.ps.custom_name = "leftover".to_string();
    wizard.ps.base_url = "http://old-url".to_string();
    wizard.ps.custom_model = "old-model".to_string();
    wizard.ps.selected_provider = CUSTOM_PROVIDER_IDX;
    wizard.ps.load_custom_fields();
    assert!(wizard.ps.custom_name.is_empty());
    assert!(wizard.ps.base_url.is_empty());
    assert!(wizard.ps.custom_model.is_empty());
}

#[test]
fn wizard_existing_custom_names_populated_from_config() {
    use crate::tui::onboarding::OnboardingWizard;
    // The wizard loads existing_custom_names from config in new()
    // This test just verifies the field exists and is a Vec
    let wizard = OnboardingWizard::new();
    let _: &Vec<String> = &wizard.ps.custom_names;
}

#[test]
fn multiple_custom_providers_in_config() {
    // Verify BTreeMap preserves insertion order (alphabetical for BTreeMap)
    let mut custom_map = BTreeMap::new();
    custom_map.insert(
        "nvidia".to_string(),
        ProviderConfig {
            enabled: false,
            base_url: Some("https://integrate.api.nvidia.com/v1".to_string()),
            default_model: Some("llama-3.3-70b".to_string()),
            ..Default::default()
        },
    );
    custom_map.insert(
        "ollama".to_string(),
        ProviderConfig {
            enabled: true,
            base_url: Some("http://localhost:11434/v1".to_string()),
            default_model: Some("llama3".to_string()),
            ..Default::default()
        },
    );
    custom_map.insert(
        "lmstudio".to_string(),
        ProviderConfig {
            enabled: false,
            base_url: Some("http://localhost:1234/v1".to_string()),
            default_model: Some("qwen".to_string()),
            ..Default::default()
        },
    );
    let configs = ProviderConfigs {
        custom: Some(custom_map),
        ..Default::default()
    };

    // active_custom should return the enabled one
    let (name, _) = configs.active_custom().unwrap();
    assert_eq!(name, "ollama");

    // All names should be available as keys
    let names: Vec<String> = configs.custom.as_ref().unwrap().keys().cloned().collect();
    assert_eq!(names.len(), 3);
    assert!(names.contains(&"nvidia".to_string()));
    assert!(names.contains(&"ollama".to_string()));
    assert!(names.contains(&"lmstudio".to_string()));
}

#[tokio::test]
async fn factory_switches_between_custom_providers() {
    // Two custom providers, only one enabled — factory picks the enabled one
    let mut custom_map = BTreeMap::new();
    custom_map.insert(
        "nvidia".to_string(),
        ProviderConfig {
            enabled: false,
            base_url: Some("https://integrate.api.nvidia.com/v1".to_string()),
            default_model: Some("llama-3.3-70b".to_string()),
            ..Default::default()
        },
    );
    custom_map.insert(
        "local".to_string(),
        ProviderConfig {
            enabled: true,
            base_url: Some("http://localhost:1234/v1".to_string()),
            default_model: Some("qwen".to_string()),
            ..Default::default()
        },
    );
    let config = Config {
        providers: ProviderConfigs {
            custom: Some(custom_map),
            ..Default::default()
        },
        ..Default::default()
    };
    let result = create_provider(&config).await;
    assert!(result.is_ok());
    assert_eq!(result.unwrap().name(), "local");
}

#[tokio::test]
async fn create_by_name_picks_specific_custom() {
    // Even when "local" is enabled, create_by_name("custom:nvidia") picks nvidia
    let mut custom_map = BTreeMap::new();
    custom_map.insert(
        "nvidia".to_string(),
        ProviderConfig {
            enabled: false,
            base_url: Some("https://integrate.api.nvidia.com/v1".to_string()),
            default_model: Some("llama-3.3-70b".to_string()),
            ..Default::default()
        },
    );
    custom_map.insert(
        "local".to_string(),
        ProviderConfig {
            enabled: true,
            base_url: Some("http://localhost:1234/v1".to_string()),
            default_model: Some("qwen".to_string()),
            ..Default::default()
        },
    );
    let config = Config {
        providers: ProviderConfigs {
            custom: Some(custom_map),
            ..Default::default()
        },
        ..Default::default()
    };
    let result = create_provider_by_name(&config, "custom:nvidia").await;
    assert!(result.is_ok());
    assert_eq!(result.unwrap().name(), "nvidia");
}