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
use super::shared_selection::{ManagedItem, SelectionState};
use crate::core::config::data::{Config, Persona};

impl ManagedItem for Persona {
    fn id(&self) -> &str {
        &self.id
    }
}

/// Manages persona state and operations
pub struct PersonaManager {
    shared: SelectionState<Persona>,
}

impl PersonaManager {
    /// Create a new PersonaManager and load personas from configuration
    pub fn load_personas(config: &Config) -> Result<Self, Box<dyn std::error::Error>> {
        let shared = SelectionState::load_from_config(
            config,
            |cfg| &cfg.personas,
            |cfg| &cfg.default_personas,
            Config::set_default_persona,
            Config::unset_default_persona,
            "Persona",
        )?;

        Ok(PersonaManager { shared })
    }

    /// Get the list of available personas
    pub fn list_personas(&self) -> &Vec<Persona> {
        self.shared.items()
    }

    /// Find a persona by its ID
    pub fn find_persona_by_id(&self, id: &str) -> Option<&Persona> {
        self.shared.find_by_id(id)
    }

    /// Set the active persona by ID
    pub fn set_active_persona(&mut self, persona_id: &str) -> Result<(), String> {
        self.shared.set_active(persona_id)
    }

    /// Clear the active persona (deactivate)
    pub fn clear_active_persona(&mut self) {
        self.shared.clear_active();
    }

    /// Get the currently active persona
    pub fn get_active_persona(&self) -> Option<&Persona> {
        self.shared.get_active()
    }

    /// Apply character and user substitutions to text
    /// {{char}} is replaced with the character name (or "Assistant" if None)
    /// {{user}} is replaced with the active persona name (or "Anon" if no persona)
    pub fn apply_substitutions(&self, text: &str, char_name: Option<&str>) -> String {
        let char_replacement = char_name.unwrap_or("Assistant");
        let user_replacement = self
            .shared
            .get_active()
            .map(|persona| persona.display_name.as_str())
            .unwrap_or("Anon");

        text.replace("{{char}}", char_replacement)
            .replace("{{user}}", user_replacement)
    }

    /// Get the display name for the user in conversations
    /// Returns the active persona's name or "You" if no persona is active
    pub fn get_display_name(&self) -> String {
        self.shared
            .get_active()
            .map(|persona| persona.display_name.clone())
            .unwrap_or_else(|| "You".to_string())
    }

    /// Get the modified system prompt with persona bio prepended
    /// If a persona is active, prepends the persona's bio (with substitutions applied) to the base prompt
    pub fn get_modified_system_prompt(&self, base_prompt: &str, char_name: Option<&str>) -> String {
        match self.shared.get_active() {
            Some(persona) => {
                if let Some(bio) = &persona.bio {
                    let substituted_bio = self.apply_substitutions(bio, char_name);
                    let trimmed_bio = substituted_bio.trim();
                    if trimmed_bio.is_empty() {
                        base_prompt.to_string()
                    } else {
                        format!("{}\n\n{}", trimmed_bio, base_prompt)
                    }
                } else {
                    base_prompt.to_string()
                }
            }
            None => base_prompt.to_string(),
        }
    }

    /// Get the default persona for a provider/model combination
    pub fn get_default_for_provider_model(&self, provider: &str, model: &str) -> Option<&str> {
        self.shared.get_default_for_provider_model(provider, model)
    }

    /// Set the default persona for a provider/model combination and persist to config
    pub fn set_default_for_provider_model_persistent(
        &mut self,
        provider: &str,
        model: &str,
        persona_id: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.shared
            .set_default_persistent(provider, model, persona_id)
    }

    /// Unset the default persona for a provider/model combination and persist to config
    pub fn unset_default_for_provider_model_persistent(
        &mut self,
        provider: &str,
        model: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.shared.unset_default_persistent(provider, model)
    }
}

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

    fn create_test_config() -> Config {
        Config {
            personas: vec![
                Persona {
                    id: "alice-dev".to_string(),
                    display_name: "Alice".to_string(),
                    bio: Some("You are talking to {{user}}, a senior developer.".to_string()),
                },
                Persona {
                    id: "bob-student".to_string(),
                    display_name: "Bob".to_string(),
                    bio: Some(
                        "{{user}} is a computer science student learning about AI.".to_string(),
                    ),
                },
                Persona {
                    id: "charlie-no-bio".to_string(),
                    display_name: "Charlie".to_string(),
                    bio: None,
                },
            ],
            ..Default::default()
        }
    }

    #[test]
    fn test_persona_loading_from_configuration() {
        let config = create_test_config();
        let manager = PersonaManager::load_personas(&config).expect("Failed to load personas");

        assert_eq!(manager.list_personas().len(), 3);
        assert!(manager.find_persona_by_id("alice-dev").is_some());
        assert!(manager.find_persona_by_id("bob-student").is_some());
        assert!(manager.find_persona_by_id("charlie-no-bio").is_some());
        assert!(manager.find_persona_by_id("nonexistent").is_none());
    }

    #[test]
    fn test_persona_activation_and_deactivation() {
        let config = create_test_config();
        let mut manager = PersonaManager::load_personas(&config).expect("Failed to load personas");

        // Initially no persona is active
        assert!(manager.get_active_persona().is_none());

        // Activate a persona
        assert!(manager.set_active_persona("alice-dev").is_ok());
        let active = manager.get_active_persona().expect("No active persona");
        assert_eq!(active.id, "alice-dev");
        assert_eq!(active.display_name, "Alice");

        // Switch to another persona
        assert!(manager.set_active_persona("bob-student").is_ok());
        let active = manager.get_active_persona().expect("No active persona");
        assert_eq!(active.id, "bob-student");
        assert_eq!(active.display_name, "Bob");

        // Deactivate persona
        manager.clear_active_persona();
        assert!(manager.get_active_persona().is_none());
    }

    #[test]
    fn test_invalid_persona_id_error_handling() {
        let config = create_test_config();
        let mut manager = PersonaManager::load_personas(&config).expect("Failed to load personas");

        let result = manager.set_active_persona("nonexistent");
        assert!(result.is_err());

        let error_msg = result.unwrap_err();
        assert!(error_msg.contains("Persona 'nonexistent' not found"));
        assert!(error_msg.contains("alice-dev"));
        assert!(error_msg.contains("bob-student"));
        assert!(error_msg.contains("charlie-no-bio"));
    }

    #[test]
    fn test_substitution_logic_with_no_persona() {
        let config = create_test_config();
        let manager = PersonaManager::load_personas(&config).expect("Failed to load personas");

        let text = "Hello {{user}}, meet {{char}}!";
        let result = manager.apply_substitutions(text, Some("Assistant"));
        assert_eq!(result, "Hello Anon, meet Assistant!");

        let result_no_char = manager.apply_substitutions(text, None);
        assert_eq!(result_no_char, "Hello Anon, meet Assistant!");
    }

    #[test]
    fn test_substitution_logic_with_active_persona() {
        let config = create_test_config();
        let mut manager = PersonaManager::load_personas(&config).expect("Failed to load personas");

        manager
            .set_active_persona("alice-dev")
            .expect("Failed to activate persona");

        let text = "Hello {{user}}, meet {{char}}!";
        let result = manager.apply_substitutions(text, Some("ChatBot"));
        assert_eq!(result, "Hello Alice, meet ChatBot!");

        let result_no_char = manager.apply_substitutions(text, None);
        assert_eq!(result_no_char, "Hello Alice, meet Assistant!");
    }

    #[test]
    fn test_display_name_with_no_persona() {
        let config = create_test_config();
        let manager = PersonaManager::load_personas(&config).expect("Failed to load personas");

        assert_eq!(manager.get_display_name(), "You");
    }

    #[test]
    fn test_display_name_with_active_persona() {
        let config = create_test_config();
        let mut manager = PersonaManager::load_personas(&config).expect("Failed to load personas");

        manager
            .set_active_persona("alice-dev")
            .expect("Failed to activate persona");
        assert_eq!(manager.get_display_name(), "Alice");

        manager
            .set_active_persona("bob-student")
            .expect("Failed to activate persona");
        assert_eq!(manager.get_display_name(), "Bob");
    }

    #[test]
    fn test_system_prompt_modification_no_persona() {
        let config = create_test_config();
        let manager = PersonaManager::load_personas(&config).expect("Failed to load personas");

        let base_prompt = "You are a helpful assistant.";
        let result = manager.get_modified_system_prompt(base_prompt, None);
        assert_eq!(result, base_prompt);
    }

    #[test]
    fn test_system_prompt_modification_with_persona_bio() {
        let config = create_test_config();
        let mut manager = PersonaManager::load_personas(&config).expect("Failed to load personas");

        manager
            .set_active_persona("alice-dev")
            .expect("Failed to activate persona");

        let base_prompt = "You are a helpful assistant.";
        let result = manager.get_modified_system_prompt(base_prompt, None);
        let expected =
            "You are talking to Alice, a senior developer.\n\nYou are a helpful assistant.";
        assert_eq!(result, expected);
    }

    #[test]
    fn test_system_prompt_modification_with_persona_no_bio() {
        let config = create_test_config();
        let mut manager = PersonaManager::load_personas(&config).expect("Failed to load personas");

        manager
            .set_active_persona("charlie-no-bio")
            .expect("Failed to activate persona");

        let base_prompt = "You are a helpful assistant.";
        let result = manager.get_modified_system_prompt(base_prompt, None);
        assert_eq!(result, base_prompt);
    }

    #[test]
    fn test_system_prompt_modification_ignores_empty_or_whitespace_bio() {
        let config = Config {
            personas: vec![
                Persona {
                    id: "dana-empty".to_string(),
                    display_name: "Dana".to_string(),
                    bio: Some(String::new()),
                },
                Persona {
                    id: "erin-whitespace".to_string(),
                    display_name: "Erin".to_string(),
                    bio: Some("   \n\t".to_string()),
                },
            ],
            ..Default::default()
        };

        let mut manager = PersonaManager::load_personas(&config).expect("Failed to load personas");
        let base_prompt = "You are a helpful assistant.";

        manager
            .set_active_persona("dana-empty")
            .expect("Failed to activate persona");
        let result_empty = manager.get_modified_system_prompt(base_prompt, None);
        assert_eq!(result_empty, base_prompt);

        manager
            .set_active_persona("erin-whitespace")
            .expect("Failed to activate persona");
        let result_whitespace = manager.get_modified_system_prompt(base_prompt, None);
        assert_eq!(result_whitespace, base_prompt);
    }

    #[test]
    fn test_persona_bio_substitution() {
        let config = create_test_config();
        let mut manager = PersonaManager::load_personas(&config).expect("Failed to load personas");

        manager
            .set_active_persona("bob-student")
            .expect("Failed to activate persona");

        let base_prompt = "You are a helpful assistant.";
        let result = manager.get_modified_system_prompt(base_prompt, None);
        let expected =
            "Bob is a computer science student learning about AI.\n\nYou are a helpful assistant.";
        assert_eq!(result, expected);
    }

    #[test]
    fn test_ui_display_name_integration() {
        use crate::core::app::ui_state::UiState;
        use crate::ui::theme::Theme;

        let config = create_test_config();
        let mut manager = PersonaManager::load_personas(&config).expect("Failed to load personas");
        let mut ui = UiState::new_basic(Theme::dark_default(), true, true, None);

        // Initially should show "You"
        assert_eq!(ui.user_display_name, "You");

        // Activate a persona and update UI
        manager
            .set_active_persona("alice-dev")
            .expect("Failed to activate persona");
        let display_name = manager.get_display_name();
        ui.update_user_display_name(display_name);

        // Should now show persona name
        assert_eq!(ui.user_display_name, "Alice");

        // Deactivate persona and update UI
        manager.clear_active_persona();
        let display_name = manager.get_display_name();
        ui.update_user_display_name(display_name);

        // Should be back to "You"
        assert_eq!(ui.user_display_name, "You");
    }

    #[test]
    fn test_default_persona_loading_from_config() {
        let mut config = create_test_config();

        // Add some default personas to the config
        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(),
        );

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

        // Check that defaults were loaded correctly
        assert_eq!(
            manager.get_default_for_provider_model("openai", "gpt-4"),
            Some("alice-dev")
        );
        assert_eq!(
            manager.get_default_for_provider_model("anthropic", "claude-3-opus"),
            Some("bob-student")
        );
        assert!(manager
            .get_default_for_provider_model("openai", "gpt-3.5-turbo")
            .is_none());
    }

    #[test]
    fn test_default_persona_lookup_case_and_underscores() {
        let mut config = create_test_config();

        config.set_default_persona(
            "OpenAI".to_string(),
            "gpt_4o_mini".to_string(),
            "alice-dev".to_string(),
        );
        config.set_default_persona(
            "openai_lab".to_string(),
            "research_model".to_string(),
            "bob-student".to_string(),
        );
        config.set_default_persona(
            "foo_bar".to_string(),
            "baz".to_string(),
            "charlie-no-bio".to_string(),
        );
        config.set_default_persona(
            "foo".to_string(),
            "bar_baz".to_string(),
            "alice-dev".to_string(),
        );

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

        assert_eq!(
            manager.get_default_for_provider_model("OPENAI", "gpt_4o_mini"),
            Some("alice-dev")
        );
        assert_eq!(
            manager.get_default_for_provider_model("OpenAI_Lab", "research_model"),
            Some("bob-student")
        );
        assert_eq!(
            manager.get_default_for_provider_model("foo_bar", "baz"),
            Some("charlie-no-bio")
        );
        assert_eq!(
            manager.get_default_for_provider_model("foo", "bar_baz"),
            Some("alice-dev")
        );
    }
}
#[test]
fn test_message_rendering_with_persona_display_name() {
    use crate::core::message::Message;
    use crate::ui::markdown::{render_message_with_config, MessageRenderConfig};
    use crate::ui::theme::Theme;

    let theme = Theme::dark_default();
    let message = Message {
        role: "user".to_string(),
        content: "Hello world".to_string(),
    };

    // Test with default "You:"
    let config_default = MessageRenderConfig::markdown(false, false);
    let rendered_default = render_message_with_config(&message, &theme, config_default);
    let first_line_default = rendered_default.lines.first().unwrap().to_string();
    assert!(first_line_default.starts_with("You: "));

    // Test with persona display name
    let config_persona = MessageRenderConfig::markdown(false, false)
        .with_user_display_name(Some("Alice".to_string()));
    let rendered_persona = render_message_with_config(&message, &theme, config_persona);
    let first_line_persona = rendered_persona.lines.first().unwrap().to_string();
    assert!(first_line_persona.starts_with("Alice: "));
}