chabeau 0.7.1

A full-screen terminal chat interface that connects to various AI APIs for real-time conversations
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
// Integration tests for persona workflows
// These tests verify end-to-end functionality across multiple modules

#[cfg(test)]
mod integration_tests {
    use crate::commands::{process_input, CommandResult};
    use crate::core::app::conversation::ConversationController;
    use crate::core::config::data::{Config, Persona};
    use crate::core::persona::PersonaManager;
    use crate::utils::test_utils::create_test_app;
    use std::fs;
    use tempfile::TempDir;

    /// Helper to create test personas for integration tests
    fn create_test_personas() -> Vec<Persona> {
        vec![
            Persona {
                id: "alice-dev".to_string(),
                display_name: "Alice".to_string(),
                bio: Some("You are talking to Alice, a senior software developer with 10 years of experience in {{char}} development.".to_string()),
            },
            Persona {
                id: "bob-student".to_string(),
                display_name: "Bob".to_string(),
                bio: Some("You are talking to {{user}}, a computer science student learning about AI.".to_string()),
            },
            Persona {
                id: "charlie-no-bio".to_string(),
                display_name: "Charlie".to_string(),
                bio: None,
            },
        ]
    }

    /// Helper to create a test config with personas
    fn create_test_config_with_personas() -> Config {
        Config {
            personas: create_test_personas(),
            ..Default::default()
        }
    }

    #[test]
    fn test_cli_persona_command_updates_ui_and_status() {
        // Test that the persona command wiring updates UI state and status messages

        let mut app = create_test_app();

        // Add test personas to the app's persona manager
        let config = create_test_config_with_personas();
        app.persona_manager =
            PersonaManager::load_personas(&config).expect("Failed to load personas");

        // Initial UI state should reflect no active persona
        assert_eq!(app.ui.user_display_name, "You");
        assert!(app.ui.status.is_none());

        // Activate persona via CLI-style command
        let result = process_input(&mut app, "/persona alice-dev");
        assert!(matches!(result, CommandResult::Continue));

        // Verify UI and persona manager are updated together
        assert_eq!(app.ui.user_display_name, "Alice");
        assert_eq!(app.ui.status.as_deref(), Some("Persona activated: Alice"));
        assert_eq!(
            app.persona_manager
                .get_active_persona()
                .expect("Persona should be active")
                .id,
            "alice-dev"
        );

        // Invalid persona should keep existing state but surface an error status
        let result = process_input(&mut app, "/persona nonexistent-persona");
        assert!(matches!(result, CommandResult::Continue));

        assert_eq!(app.ui.user_display_name, "Alice");
        assert_eq!(
            app.persona_manager
                .get_active_persona()
                .expect("Persona should remain active")
                .id,
            "alice-dev"
        );
        assert!(app
            .ui
            .status
            .as_deref()
            .unwrap_or_default()
            .starts_with("Persona error: Persona 'nonexistent-persona' not found"));
    }

    #[test]
    fn test_interactive_persona_command_workflow() {
        // Test interactive command execution and picker workflow
        // This simulates: /persona command → picker opens → selection made

        let mut app = create_test_app();

        // Add test personas to the app's persona manager
        let config = create_test_config_with_personas();
        app.persona_manager =
            PersonaManager::load_personas(&config).expect("Failed to load personas");

        // Execute /persona command
        let result = process_input(&mut app, "/persona");
        assert!(
            matches!(result, CommandResult::OpenPersonaPicker),
            "Persona command should open picker"
        );

        // Test direct persona activation via command
        let result = process_input(&mut app, "/persona alice-dev");
        assert!(
            matches!(result, CommandResult::Continue),
            "Direct persona activation should continue"
        );

        // Verify persona is activated
        let active_persona = app.persona_manager.get_active_persona();
        assert!(
            active_persona.is_some(),
            "Persona should be active after direct command"
        );
        assert_eq!(active_persona.unwrap().id, "alice-dev");

        // Test invalid persona ID
        let result = process_input(&mut app, "/persona nonexistent");
        assert!(
            matches!(result, CommandResult::Continue),
            "Invalid persona should continue with error"
        );

        // Verify original persona is still active
        let active_persona = app.persona_manager.get_active_persona();
        assert!(active_persona.is_some());
        assert_eq!(active_persona.unwrap().id, "alice-dev");
    }

    #[test]
    fn test_persona_picker_with_active_persona() {
        // Test picker behavior when a persona is already active

        let mut app = create_test_app();

        // Set up personas and activate one
        let config = create_test_config_with_personas();
        app.persona_manager =
            PersonaManager::load_personas(&config).expect("Failed to load personas");
        app.persona_manager
            .set_active_persona("alice-dev")
            .expect("Failed to activate persona");

        // Execute /persona command
        let result = process_input(&mut app, "/persona");
        assert!(matches!(result, CommandResult::OpenPersonaPicker));

        // Test switching to another persona
        let result = process_input(&mut app, "/persona bob-student");
        assert!(matches!(result, CommandResult::Continue));

        // Verify persona switched
        let active_persona = app.persona_manager.get_active_persona();
        assert!(active_persona.is_some());
        assert_eq!(active_persona.unwrap().id, "bob-student");
        assert_eq!(active_persona.unwrap().display_name, "Bob");
    }

    #[test]
    fn test_persona_picker_turn_off_updates_ui_state() {
        // Test persona deactivation through the picker flow and ensure UI is updated

        let mut app = create_test_app();

        // Set up personas and activate one so the "turn off" option is present
        let config = create_test_config_with_personas();
        app.persona_manager =
            PersonaManager::load_personas(&config).expect("Failed to load personas");
        app.persona_manager
            .set_active_persona("alice-dev")
            .expect("Failed to activate persona");

        // Mirror the active persona in the UI like the command handler does
        let active_display_name = app.persona_manager.get_display_name();
        app.ui.update_user_display_name(active_display_name.clone());
        assert_eq!(app.ui.user_display_name, "Alice");

        // Opening the picker should include the "turn off persona" entry
        app.open_persona_picker();

        {
            let picker_state = app.picker_state().expect("Persona picker should be opened");
            assert!(
                picker_state
                    .items
                    .iter()
                    .any(|item| item.id == "[turn_off_persona]"),
                "Turn off persona entry should be present in picker"
            );
        }

        {
            let picker_state = app
                .picker_state_mut()
                .expect("Persona picker state should be mutable");
            let turn_off_index = picker_state
                .items
                .iter()
                .position(|item| item.id == "[turn_off_persona]")
                .expect("Turn off persona entry missing");
            picker_state.selected = turn_off_index;
        }

        // Apply the currently selected option to deactivate the persona
        app.apply_selected_persona(false);

        assert!(app.persona_manager.get_active_persona().is_none());
        assert_eq!(app.ui.user_display_name, "You");
        assert_eq!(app.ui.status.as_deref(), Some("Persona deactivated"));
        assert!(app.picker_state().is_none());
    }

    #[test]
    fn test_system_prompt_modification_with_active_persona() {
        // Test system prompt modification with active personas

        let config = create_test_config_with_personas();
        let mut persona_manager =
            PersonaManager::load_personas(&config).expect("Failed to load personas");

        let base_prompt = "You are a helpful assistant.";

        // Test without persona
        let prompt_no_persona = persona_manager.get_modified_system_prompt(base_prompt, None);
        assert_eq!(
            prompt_no_persona, base_prompt,
            "Prompt should be unchanged without persona"
        );

        // Test with persona that has bio
        persona_manager
            .set_active_persona("alice-dev")
            .expect("Failed to activate persona");
        let prompt_with_persona = persona_manager.get_modified_system_prompt(base_prompt, None);

        assert!(prompt_with_persona.contains("Alice, a senior software developer"));
        assert!(prompt_with_persona.contains(base_prompt));
        assert!(
            prompt_with_persona.len() > base_prompt.len(),
            "Modified prompt should be longer"
        );

        // Test with persona without bio
        persona_manager
            .set_active_persona("charlie-no-bio")
            .expect("Failed to activate persona");
        let prompt_no_bio = persona_manager.get_modified_system_prompt(base_prompt, None);
        assert_eq!(
            prompt_no_bio, base_prompt,
            "Prompt should be unchanged for persona without bio"
        );
    }

    #[test]
    fn test_persona_substitution_in_conversation() {
        // Test character and user substitution with personas

        let config = create_test_config_with_personas();
        let mut persona_manager =
            PersonaManager::load_personas(&config).expect("Failed to load personas");

        // Test substitution without persona
        let text_with_placeholders = "Hello {{user}}, I am {{char}}!";
        let result_no_persona =
            persona_manager.apply_substitutions(text_with_placeholders, Some("TestBot"));
        assert_eq!(result_no_persona, "Hello Anon, I am TestBot!");

        // Test substitution with persona
        persona_manager
            .set_active_persona("alice-dev")
            .expect("Failed to activate persona");
        let result_with_persona =
            persona_manager.apply_substitutions(text_with_placeholders, Some("TestBot"));
        assert_eq!(result_with_persona, "Hello Alice, I am TestBot!");

        // Test substitution in persona bio
        let active_persona = persona_manager.get_active_persona().unwrap();
        let bio_with_substitution = active_persona.bio.as_ref().unwrap();
        let substituted_bio =
            persona_manager.apply_substitutions(bio_with_substitution, Some("TestBot"));
        assert!(substituted_bio.contains("Alice, a senior software developer"));
        assert!(substituted_bio.contains("TestBot development"));
    }

    #[test]
    fn test_default_persona_loading_from_config() {
        // Test automatic default persona loading based on provider/model

        let mut config = create_test_config_with_personas();

        // Set default persona in config
        config.set_default_persona(
            "openai".to_string(),
            "gpt-4".to_string(),
            "alice-dev".to_string(),
        );

        let persona_manager =
            PersonaManager::load_personas(&config).expect("Failed to load personas");

        // Verify default is loaded
        let default = persona_manager.get_default_for_provider_model("openai", "gpt-4");
        assert!(default.is_some());
        assert_eq!(default.unwrap(), "alice-dev");
    }

    #[test]
    fn test_cli_persona_overrides_default() {
        // Test that CLI persona selection overrides default persona

        let mut config = create_test_config_with_personas();
        config.set_default_persona(
            "openai".to_string(),
            "gpt-4".to_string(),
            "bob-student".to_string(),
        );

        let mut persona_manager =
            PersonaManager::load_personas(&config).expect("Failed to load personas");

        // Verify default is set
        assert_eq!(
            persona_manager
                .get_default_for_provider_model("openai", "gpt-4")
                .unwrap(),
            "bob-student"
        );

        // Simulate CLI override
        persona_manager
            .set_active_persona("alice-dev")
            .expect("Failed to set CLI persona");

        // Verify CLI persona is active (not default)
        let active = persona_manager.get_active_persona().unwrap();
        assert_eq!(active.id, "alice-dev");
        assert_ne!(active.id, "bob-student");
    }

    #[test]
    fn test_persona_display_name_in_conversation() {
        // Test persona display name integration with conversation UI

        let mut app = create_test_app();

        // Set up personas
        let config = create_test_config_with_personas();
        app.persona_manager =
            PersonaManager::load_personas(&config).expect("Failed to load personas");

        // Test without persona - should use "You"
        assert_eq!(app.persona_manager.get_display_name(), "You");

        // Activate persona
        app.persona_manager
            .set_active_persona("alice-dev")
            .expect("Failed to activate persona");

        // Test with persona - should use persona display name
        assert_eq!(app.persona_manager.get_display_name(), "Alice");

        // Add a user message and verify display name is used
        {
            let mut conversation = ConversationController::new(
                &mut app.session,
                &mut app.ui,
                &app.persona_manager,
                &app.preset_manager,
            );
            conversation.add_user_message("Hello!".to_string());
        }

        // Verify message was added (we can't easily test the exact display without UI rendering)
        assert!(!app.ui.messages.is_empty());
    }

    #[test]
    fn test_persona_config_persistence() {
        // Test persona configuration persistence across save/load

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("test_personas.toml");

        // Create config with personas and defaults
        let mut config = create_test_config_with_personas();
        config.set_default_persona(
            "openai".to_string(),
            "gpt-4".to_string(),
            "alice-dev".to_string(),
        );
        config.set_default_persona(
            "anthropic".to_string(),
            "claude-3-opus".to_string(),
            "bob-student".to_string(),
        );

        // Save config
        let toml_str = toml::to_string(&config).unwrap();
        fs::write(&config_path, toml_str).unwrap();

        // Load config
        let loaded_toml = fs::read_to_string(&config_path).unwrap();
        let loaded_config: Config = toml::from_str(&loaded_toml).unwrap();

        // Verify personas are preserved
        assert_eq!(loaded_config.personas.len(), 3);
        assert!(loaded_config.personas.iter().any(|p| p.id == "alice-dev"));
        assert!(loaded_config.personas.iter().any(|p| p.id == "bob-student"));
        assert!(loaded_config
            .personas
            .iter()
            .any(|p| p.id == "charlie-no-bio"));

        // Verify defaults are preserved
        let persona_manager =
            PersonaManager::load_personas(&loaded_config).expect("Failed to load personas");
        assert_eq!(
            persona_manager
                .get_default_for_provider_model("openai", "gpt-4")
                .unwrap(),
            "alice-dev"
        );
        assert_eq!(
            persona_manager
                .get_default_for_provider_model("anthropic", "claude-3-opus")
                .unwrap(),
            "bob-student"
        );
    }

    #[test]
    fn test_end_to_end_persona_workflow() {
        // Test complete end-to-end persona workflow
        // This simulates: config load → CLI selection → conversation → picker change → conversation

        let mut app = create_test_app();

        // Step 1: Load personas from config
        let config = create_test_config_with_personas();
        app.persona_manager =
            PersonaManager::load_personas(&config).expect("Failed to load personas");

        // Step 2: Simulate CLI persona selection
        app.persona_manager
            .set_active_persona("alice-dev")
            .expect("Failed to set CLI persona");

        // Verify initial state
        assert_eq!(app.persona_manager.get_display_name(), "Alice");
        let initial_prompt = app
            .persona_manager
            .get_modified_system_prompt("You are helpful.", None);
        assert!(initial_prompt.contains("Alice, a senior software developer"));

        // Step 3: Add user message with persona active
        {
            let mut conversation = ConversationController::new(
                &mut app.session,
                &mut app.ui,
                &app.persona_manager,
                &app.preset_manager,
            );
            conversation.add_user_message("What's your experience?".to_string());
        }

        // Step 4: Switch persona via picker simulation
        app.persona_manager
            .set_active_persona("bob-student")
            .expect("Failed to switch persona");

        // Verify persona switch
        assert_eq!(app.persona_manager.get_display_name(), "Bob");
        let switched_prompt = app
            .persona_manager
            .get_modified_system_prompt("You are helpful.", None);
        assert!(switched_prompt.contains("Bob, a computer science student"));
        assert!(!switched_prompt.contains("Alice"));

        // Step 5: Add another message with new persona
        {
            let mut conversation = ConversationController::new(
                &mut app.session,
                &mut app.ui,
                &app.persona_manager,
                &app.preset_manager,
            );
            conversation.add_user_message("I'm learning AI.".to_string());
        }

        // Step 6: Deactivate persona
        app.persona_manager.clear_active_persona();

        // Verify deactivation
        assert_eq!(app.persona_manager.get_display_name(), "You");
        let final_prompt = app
            .persona_manager
            .get_modified_system_prompt("You are helpful.", None);
        assert_eq!(final_prompt, "You are helpful.");
    }

    #[test]
    fn test_persona_error_recovery() {
        // Test error handling and recovery in persona workflows

        let mut app = create_test_app();

        // Test with empty persona list
        let empty_config = Config::default();
        app.persona_manager =
            PersonaManager::load_personas(&empty_config).expect("Failed to load empty personas");

        // Should handle empty persona list gracefully
        assert!(app.persona_manager.list_personas().is_empty());
        assert!(app.persona_manager.get_active_persona().is_none());
        assert_eq!(app.persona_manager.get_display_name(), "You");

        // Test /persona command with no personas
        let result = process_input(&mut app, "/persona");
        assert!(matches!(result, CommandResult::OpenPersonaPicker)); // Should not crash

        // Test invalid persona activation
        let result = app.persona_manager.set_active_persona("nonexistent");
        assert!(result.is_err());
        assert!(app.persona_manager.get_active_persona().is_none());

        // Add personas and test recovery
        let config = create_test_config_with_personas();
        app.persona_manager =
            PersonaManager::load_personas(&config).expect("Failed to load personas");

        // Should work normally after recovery
        assert!(app.persona_manager.set_active_persona("alice-dev").is_ok());
        assert!(app.persona_manager.get_active_persona().is_some());
    }

    #[test]
    fn test_persona_command_variations() {
        // Test various persona command variations

        let mut app = create_test_app();

        // Set up personas
        let config = create_test_config_with_personas();
        app.persona_manager =
            PersonaManager::load_personas(&config).expect("Failed to load personas");

        // Test opening picker
        let result = process_input(&mut app, "/persona");
        assert!(matches!(result, CommandResult::OpenPersonaPicker));

        // Test activating each persona
        let result = process_input(&mut app, "/persona alice-dev");
        assert!(matches!(result, CommandResult::Continue));
        assert_eq!(
            app.persona_manager.get_active_persona().unwrap().id,
            "alice-dev"
        );

        let result = process_input(&mut app, "/persona bob-student");
        assert!(matches!(result, CommandResult::Continue));
        assert_eq!(
            app.persona_manager.get_active_persona().unwrap().id,
            "bob-student"
        );

        let result = process_input(&mut app, "/persona charlie-no-bio");
        assert!(matches!(result, CommandResult::Continue));
        assert_eq!(
            app.persona_manager.get_active_persona().unwrap().id,
            "charlie-no-bio"
        );

        // Test error handling for invalid persona
        let result = process_input(&mut app, "/persona invalid-persona");
        assert!(matches!(result, CommandResult::Continue));
        // Should still have the last valid persona active
        assert_eq!(
            app.persona_manager.get_active_persona().unwrap().id,
            "charlie-no-bio"
        );
    }
}