bamboo-engine 2026.11.1

Execution engine and orchestration for the Bamboo agent framework
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! Unit tests for title_gen helpers (no LLM/AppState dependencies).

use super::*;

#[tokio::test]
async fn routing_contract_title_uses_saved_global_fast_and_live_replacement_for_every_flag() {
    use crate::app_context::model_routing_test_support::RoutingContext;
    for flag in [None, Some(false), Some(true)] {
        let state = RoutingContext::new(flag);
        let context: Arc<dyn AgentSessionContext> = state.clone();
        let session = RoutingContext::session();
        assert_eq!(
            try_llm_title(&context, &session, "Synthetic title request")
                .await
                .unwrap(),
            "Synthetic routing title"
        );
        assert_eq!(
            state.requests("fast-b"),
            vec![("cheap-b".into(), "title_generation".into())]
        );
        assert!(state.requests("chat-a").is_empty());
        state.config.write().await.defaults.as_mut().unwrap().fast = Some(
            bamboo_domain::ProviderModelRef::new("memory-c", "background-c"),
        );
        try_llm_title(&context, &session, "Synthetic replacement request")
            .await
            .unwrap();
        assert_eq!(
            state.requests("memory-c"),
            vec![("background-c".into(), "title_generation".into())]
        );
        assert!(state.requests("chat-a").is_empty());
    }
}

#[tokio::test]
async fn routing_contract_title_invalid_explicit_fast_never_dispatches_a_fallback() {
    use crate::app_context::model_routing_test_support::RoutingContext;
    for flag in [None, Some(false), Some(true)] {
        let state = RoutingContext::new(flag);
        state
            .config
            .write()
            .await
            .defaults
            .as_mut()
            .unwrap()
            .fast
            .as_mut()
            .unwrap()
            .provider = "missing-account".into();
        let context: Arc<dyn AgentSessionContext> = state.clone();
        assert!(try_llm_title(
            &context,
            &RoutingContext::session(),
            "Synthetic invalid route"
        )
        .await
        .is_err());
        state.assert_no_requests();
    }
}

#[tokio::test]
async fn routing_contract_title_embedder_owned_removed_fast_keeps_sdk_route() {
    use crate::app_context::model_routing_test_support::RoutingContext;
    for flag in [None, Some(false), Some(true)] {
        let state = RoutingContext::new(flag);
        {
            let mut config = state.config.write().await;
            assert!(config.provider_instances.remove("fast-b").is_some());
            assert!(config.provider_instances.contains_key("chat-a"));
            assert_eq!(
                config
                    .defaults
                    .as_ref()
                    .unwrap()
                    .fast
                    .as_ref()
                    .unwrap()
                    .provider,
                "fast-b"
            );
        }
        assert!(state.registry.get("fast-b").is_some());
        assert_eq!(
            state.registry.runtime_models_for_provider("fast-b"),
            Some(vec!["cheap-b".to_string()])
        );

        let context: Arc<dyn AgentSessionContext> = state.clone();
        let result = try_llm_title(
            &context,
            &RoutingContext::session(),
            "Synthetic removed-account request",
        )
        .await;
        // This provider map belongs to the embedding application, not Config.
        // Managed removal is separately tested with ProviderRegistry::from_config.
        assert_eq!(result.unwrap(), "Synthetic routing title", "flag {flag:?}");
        assert_eq!(
            state.requests("fast-b"),
            vec![("cheap-b".into(), "title_generation".into())]
        );
        assert!(state.requests("chat-a").is_empty());
        assert!(state.requests("memory-c").is_empty());
    }
}

#[tokio::test]
async fn routing_contract_title_accepts_an_embedder_owned_registry() {
    use crate::app_context::model_routing_test_support::RoutingContext;
    use std::collections::HashMap;

    for flag in [None, Some(false), Some(true)] {
        for explicit_admission in [false, true] {
            let state = RoutingContext::new(flag);
            {
                let mut config = state.config.write().await;
                config.provider_instances.clear();
                config.default_provider_instance = None;
            }
            let providers: HashMap<String, Arc<dyn bamboo_llm::LLMProvider>> = state
                .providers
                .iter()
                .map(|(id, provider)| {
                    (
                        id.clone(),
                        provider.clone() as Arc<dyn bamboo_llm::LLMProvider>,
                    )
                })
                .collect();
            let registry = bamboo_llm::ProviderRegistry::new(providers, "chat-a".into());
            if explicit_admission {
                registry.set_runtime_models(HashMap::from([(
                    "fast-b".to_string(),
                    vec!["cheap-b".to_string()],
                )]));
            }
            state.registry.replace_with(registry);
            assert_eq!(
                state
                    .registry
                    .runtime_models_for_provider("fast-b")
                    .is_some(),
                explicit_admission
            );

            let context: Arc<dyn AgentSessionContext> = state.clone();
            assert_eq!(
                try_llm_title(
                    &context,
                    &RoutingContext::session(),
                    "Synthetic embedded request",
                )
                .await
                .unwrap(),
                "Synthetic routing title"
            );
            assert_eq!(
                state.requests("fast-b"),
                vec![("cheap-b".into(), "title_generation".into())]
            );
            assert!(state.requests("chat-a").is_empty());
            assert!(state.requests("memory-c").is_empty());
        }
    }
}

#[tokio::test]
async fn routing_contract_title_accepts_an_enabled_synthesized_legacy_provider() {
    use crate::app_context::model_routing_test_support::RoutingContext;
    use std::collections::HashMap;

    for flag in [None, Some(false), Some(true)] {
        let state = RoutingContext::new(flag);
        {
            let mut config = state.config.write().await;
            config.provider_instances.clear();
            config.default_provider_instance = None;
            config.provider = "openai".to_string();
            config.providers_mut().openai = Some(bamboo_config::OpenAIConfig {
                model: Some("legacy-chat".into()),
                fast_model: Some("legacy-fast".into()),
                ..Default::default()
            });
            let defaults = config.defaults.as_mut().unwrap();
            defaults.chat = bamboo_domain::ProviderModelRef::new("openai", "legacy-chat");
            defaults.fast = Some(bamboo_domain::ProviderModelRef::new(
                "openai",
                "legacy-fast",
            ));
            assert!(bamboo_config::synthesize_legacy_instances(&config)
                .iter()
                .any(|(id, instance)| id == "openai" && instance.enabled));
        }

        state
            .registry
            .insert("openai".into(), state.providers["fast-b"].clone());
        state.registry.set_runtime_models(HashMap::from([(
            "openai".to_string(),
            vec!["legacy-fast".to_string()],
        )]));
        let context: Arc<dyn AgentSessionContext> = state.clone();
        assert_eq!(
            try_llm_title(
                &context,
                &RoutingContext::session(),
                "Synthetic legacy request",
            )
            .await
            .unwrap(),
            "Synthetic routing title"
        );
        assert_eq!(
            state.requests("fast-b"),
            vec![("legacy-fast".into(), "title_generation".into())]
        );
        assert!(state.requests("chat-a").is_empty());
        assert!(state.requests("memory-c").is_empty());
    }
}

// These tests use only local mock services, temporary roots, and fake keys.
async fn managed_title_mock() -> wiremock::MockServer {
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/chat/completions"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/event-stream")
                .set_body_string(concat!(
                    "data: {\"id\":\"mock\",\"object\":\"chat.completion.chunk\",\"created\":0,\"model\":\"fixture\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Synthetic routing title\"},\"finish_reason\":null}]}\n\n",
                    "data: [DONE]\n\n"
                )),
        )
        .mount(&server)
        .await;
    server
}

async fn managed_title_request_count(server: &wiremock::MockServer) -> usize {
    server.received_requests().await.unwrap().len()
}

#[tokio::test]
async fn routing_contract_title_config_managed_removed_instance_never_dispatches() {
    use crate::app_context::model_routing_test_support::RoutingContext;

    let mut observations = Vec::new();
    for flag in [None, Some(false), Some(true)] {
        let chat = managed_title_mock().await;
        let fast = managed_title_mock().await;
        let memory = managed_title_mock().await;
        let state = RoutingContext::new(flag);
        let config_snapshot = {
            let mut config = state.config.write().await;
            // The client's loopback exclusion prevents use of inherited proxies.
            config.http_proxy = "https://127.0.0.1:9".into();
            config.https_proxy.clear();
            config.proxy_auth = None;
            for (id, server) in [("chat-a", &chat), ("fast-b", &fast), ("memory-c", &memory)] {
                let instance = config.provider_instances.get_mut(id).unwrap();
                instance.api_key = "fixture-only-not-a-credential".into();
                instance.base_url = Some(server.uri());
            }
            config.clone()
        };
        let root = tempfile::tempdir().unwrap();
        let managed =
            bamboo_llm::ProviderRegistry::from_config(&config_snapshot, root.path().to_path_buf())
                .await
                .unwrap();
        assert!(managed.get("fast-b").is_some());
        state.registry.replace_with(managed);
        let old_handle = state.registry.get("fast-b").unwrap();
        let context: Arc<dyn AgentSessionContext> = state.clone();
        let session = RoutingContext::session();

        // Positive control proves that the selected managed provider really
        // reaches the Fast endpoint and that its stream is consumable.
        assert_eq!(
            try_llm_title(&context, &session, "Synthetic managed title")
                .await
                .unwrap(),
            "Synthetic routing title"
        );
        let requests = fast.received_requests().await.unwrap();
        assert_eq!(requests.len(), 1);
        let body: serde_json::Value = serde_json::from_slice(&requests[0].body).unwrap();
        assert_eq!(body["model"], "cheap-b");
        assert_eq!(managed_title_request_count(&chat).await, 0);
        assert_eq!(managed_title_request_count(&memory).await, 0);

        {
            let mut config = state.config.write().await;
            assert!(config.provider_instances.remove("fast-b").is_some());
            assert!(config.provider_instances.contains_key("chat-a"));
            assert_eq!(
                config
                    .defaults
                    .as_ref()
                    .unwrap()
                    .fast
                    .as_ref()
                    .unwrap()
                    .provider,
                "fast-b"
            );
        }
        assert!(Arc::ptr_eq(
            &old_handle,
            &state.registry.get("fast-b").unwrap()
        ));
        let rejected = try_llm_title(&context, &session, "Synthetic stale managed title")
            .await
            .is_err();
        observations.push((
            flag,
            rejected,
            managed_title_request_count(&fast).await,
            managed_title_request_count(&chat).await,
            managed_title_request_count(&memory).await,
        ));
    }
    assert_eq!(observations.len(), 3);
    assert!(
        observations
            .iter()
            .all(|(_, rejected, fast, chat, memory)| *rejected
                && *fast == 1
                && *chat == 0
                && *memory == 0),
        "removed managed Fast must not dispatch, for any flag: {observations:?}"
    );
}

#[tokio::test]
async fn routing_contract_title_config_managed_same_id_legacy_requires_new_registry() {
    use crate::app_context::model_routing_test_support::RoutingContext;

    let mut observations = Vec::new();
    for flag in [None, Some(false), Some(true)] {
        let instance_endpoint = managed_title_mock().await;
        let legacy_endpoint = managed_title_mock().await;
        let other_endpoint = managed_title_mock().await;
        let state = RoutingContext::new(flag);
        let config_snapshot = {
            let mut config = state.config.write().await;
            config.http_proxy = "https://127.0.0.1:9".into();
            config.https_proxy.clear();
            config.proxy_auth = None;
            config.provider = "openai".into();
            config.default_provider_instance = Some("openai".into());
            config.provider_instances.clear();
            config.provider_instances.insert(
                "openai".into(),
                serde_json::from_value(serde_json::json!({
                    "provider_type": "openai", "enabled": true,
                    "api_key": "fixture-instance-not-a-credential",
                    "base_url": instance_endpoint.uri(), "model": "same-model",
                    "runtime_models": ["same-model"]
                }))
                .unwrap(),
            );
            // Keep one native instance after removing "openai" so the
            // legacy alias is rebuilt in hybrid mode, without constructing
            // the unrelated default Copilot provider.
            config.provider_instances.insert(
                "other-account".into(),
                serde_json::from_value(serde_json::json!({
                    "provider_type": "openai", "enabled": true,
                    "api_key": "fixture-other-not-a-credential",
                    "base_url": other_endpoint.uri(), "model": "other-model",
                    "runtime_models": ["other-model"]
                }))
                .unwrap(),
            );
            config.providers_mut().openai = Some(bamboo_config::OpenAIConfig {
                api_key: "fixture-legacy-not-a-credential".into(),
                base_url: Some(legacy_endpoint.uri()),
                model: Some("same-model".into()),
                fast_model: Some("same-model".into()),
                ..Default::default()
            });
            config.defaults = Some(
                serde_json::from_value(serde_json::json!({
                    "chat": {"provider":"openai", "model":"same-model"},
                    "fast": {"provider":"openai", "model":"same-model"}
                }))
                .unwrap(),
            );
            assert!(!bamboo_config::synthesize_legacy_instances(&config)
                .iter()
                .any(|(id, _)| id == "openai"));
            config.clone()
        };
        let root = tempfile::tempdir().unwrap();
        let managed =
            bamboo_llm::ProviderRegistry::from_config(&config_snapshot, root.path().to_path_buf())
                .await
                .unwrap();
        assert!(managed.get("openai").is_some());
        state.registry.replace_with(managed);
        let old_handle = state.registry.get("openai").unwrap();
        let context: Arc<dyn AgentSessionContext> = state.clone();
        let session = RoutingContext::session();

        assert_eq!(
            try_llm_title(&context, &session, "Synthetic instance title")
                .await
                .unwrap(),
            "Synthetic routing title"
        );
        assert_eq!(managed_title_request_count(&instance_endpoint).await, 1);
        assert_eq!(managed_title_request_count(&legacy_endpoint).await, 0);
        assert_eq!(managed_title_request_count(&other_endpoint).await, 0);

        let replacement_config = {
            let mut config = state.config.write().await;
            assert!(config.provider_instances.remove("openai").is_some());
            assert!(config.provider_instances.contains_key("other-account"));
            let legacy = bamboo_config::synthesize_legacy_instances(&config);
            let (_, instance) = legacy.iter().find(|(id, _)| id == "openai").unwrap();
            assert_eq!(instance.model.as_deref(), Some("same-model"));
            let legacy_url = legacy_endpoint.uri();
            assert_eq!(instance.base_url.as_deref(), Some(legacy_url.as_str()));
            config.clone()
        };
        assert!(Arc::ptr_eq(
            &old_handle,
            &state.registry.get("openai").unwrap()
        ));
        let rejected = try_llm_title(&context, &session, "Synthetic stale instance title")
            .await
            .is_err();
        let old_after_stale = managed_title_request_count(&instance_endpoint).await;
        let new_after_stale = managed_title_request_count(&legacy_endpoint).await;
        let other_after_stale = managed_title_request_count(&other_endpoint).await;

        // Once the registry is built from the new legacy source, the identical
        // ID and model must select the new endpoint, proving compatibility.
        let refreshed = bamboo_llm::ProviderRegistry::from_config(
            &replacement_config,
            root.path().to_path_buf(),
        )
        .await
        .unwrap();
        assert!(refreshed.get("openai").is_some());
        state.registry.replace_with(refreshed);
        assert_eq!(
            try_llm_title(&context, &session, "Synthetic legacy title")
                .await
                .unwrap(),
            "Synthetic routing title"
        );
        assert_eq!(
            managed_title_request_count(&instance_endpoint).await,
            old_after_stale
        );
        assert_eq!(
            managed_title_request_count(&legacy_endpoint).await,
            new_after_stale + 1
        );
        assert_eq!(
            managed_title_request_count(&other_endpoint).await,
            other_after_stale
        );
        observations.push((
            flag,
            rejected,
            old_after_stale,
            new_after_stale,
            other_after_stale,
        ));
    }
    assert_eq!(observations.len(), 3);
    assert!(
        observations
            .iter()
            .all(|(_, rejected, old, legacy, other)| *rejected
                && *old == 1
                && *legacy == 0
                && *other == 0),
        "same ID must not route through the old source, for any flag: {observations:?}"
    );
}

#[test]
fn test_heuristic_title_strips_code_fences_and_caps_length() {
    let input = "```rust\nfn main() {}\n```\nHelp me debug this Rust program please";
    let t = heuristic_title(input);
    assert!(!t.is_empty());
    assert!(!t.contains("```"));
    assert!(!t.contains("fn main"));
    assert!(t.starts_with("Help me debug this Rust program"));

    let long = "a ".repeat(200);
    let t2 = heuristic_title(&long);
    assert!(t2.chars().count() <= 60);
}

#[test]
fn test_heuristic_title_first_sentence_only() {
    let input = "Refactor the auth module. Then add tests. Finally ship it!";
    assert_eq!(heuristic_title(input), "Refactor the auth module");
}

#[test]
fn test_heuristic_title_trims_punctuation_tail() {
    let input = "Plan a trip to Tokyo,";
    let t = heuristic_title(input);
    assert_eq!(t, "Plan a trip to Tokyo");
}

#[test]
fn test_heuristic_title_caps_without_splitting_a_word() {
    // 60 characters lands inside "detai|ls"; the title must not keep the fragment.
    let input =
        "Wrangle the deployment pipeline for every microservice before the release window closes";
    let title = heuristic_title(input);
    assert!(title.chars().count() <= 60, "{title:?}");
    assert!(
        input.starts_with(&title),
        "title must be a prefix of the input: {title:?}"
    );
    // The cut falls on a word boundary, so the title ends a whole word.
    let next = input[title.len()..].chars().next();
    assert!(
        next.is_none_or(|c| c.is_whitespace()),
        "title ends mid-word: {title:?} then {next:?}"
    );
}

#[test]
fn test_heuristic_title_keeps_a_word_that_ends_exactly_at_the_limit() {
    // This sentence's 60th character is the space after "logs", so the whole word
    // fits inside the limit and must not be dropped by a second retreat.
    let input = "Investigate failed authentication request in production logs before deploying";
    assert_eq!(
        &input[..60],
        "Investigate failed authentication request in production logs"
    );
    assert!(input[60..].starts_with(' '));
    assert_eq!(
        heuristic_title(input),
        "Investigate failed authentication request in production logs"
    );
}

#[test]
fn test_heuristic_title_keeps_cjk_text_that_has_no_word_spaces() {
    // A CJK sentence has no whitespace to retreat to; it must keep the hard cut
    // instead of collapsing to an empty title.
    let input = "帮我把这个部署流水线在发布窗口关闭之前全部分析清楚并且给出改进建议";
    let title = heuristic_title(input);
    assert!(!title.is_empty());
    assert!(title.chars().count() <= 60, "{title:?}");
    assert!(input.starts_with(&title), "{title:?}");
}

#[test]
fn test_heuristic_title_drops_a_pasted_banner_joined_on_one_line() {
    // Reproduces the reported title: a selection over the banner joined its title
    // and <summary> label into one line, followed by the error body.
    let input = concat!(
        "Message sent, but generation was interrupted Technical details\n",
        "LLM error: initial response headers timed out\n",
        "\n",
        "\n",
        "Why does this keep happening? And here is my diagnostics bundle.\n"
    );
    let title = heuristic_title(input);
    assert_eq!(title, "Why does this keep happening");
}

#[test]
fn test_heuristic_title_drops_a_pasted_banner_on_separate_lines() {
    let input = concat!(
        "Message sent, but generation was interrupted\n",
        "Technical details\n",
        "LLM error: initial response headers timed out\n",
        "\n",
        "The retry policy never recovers on its own.\n"
    );
    let title = heuristic_title(input);
    assert_eq!(title, "The retry policy never recovers on its own");
}

#[test]
fn test_heuristic_title_drops_a_pasted_banner_without_details() {
    let input = "Message sent, but generation was interrupted\n\nHow do I stop this?\n";
    assert_eq!(heuristic_title(input), "How do I stop this");
}

#[test]
fn test_heuristic_title_drops_a_pasted_banner_in_chinese() {
    let input = concat!(
        "消息已发送,但生成中断 技术详情\n",
        "LLM error: initial response headers timed out\n",
        "\n",
        "老是有这个问题 是为什么?\n"
    );
    assert_eq!(heuristic_title(input), "老是有这个问题 是为什么");
}

#[test]
fn test_heuristic_title_falls_back_to_banner_copy_when_nothing_else_remains() {
    // Stripping everything would lose the title entirely, so the banner copy is
    // kept rather than emitting an empty session title.
    let input = "Message sent, but generation was interrupted\n";
    assert_eq!(
        heuristic_title(input),
        "Message sent, but generation was interrupted"
    );
}

#[test]
fn test_heuristic_title_leaves_ordinary_messages_untouched() {
    // Only a banner at the very start is stripped. A message that merely quotes
    // the banner copy keeps its own words, and the long line still caps normally.
    let input = "Why does the banner say \"Message sent, but generation was interrupted\"?";
    let title = heuristic_title(input);
    assert!(title.starts_with("Why does the banner say"), "{title:?}");

    // A banner phrase that is not the first line is not stripped. Only the strip
    // is asserted here: whitespace collapsing predates this fix and joins the
    // lines, so the exact title text is not this fix's contract.
    assert!(
        heuristic_title("Explain this\nMessage sent, but generation was interrupted")
            .starts_with("Explain this")
    );
    assert_eq!(
        heuristic_title("Refactor the auth module"),
        "Refactor the auth module"
    );
}

#[test]
fn test_sanitize_strips_quotes_and_caps() {
    assert_eq!(sanitize("\"Hello world.\""), "Hello world");
    assert_eq!(sanitize("  'A quoted title'  "), "A quoted title");
    assert_eq!(sanitize("First line\nSecond line"), "First line");

    let long = "x".repeat(120);
    let s = sanitize(&long);
    assert!(s.chars().count() <= MAX_TITLE_LEN);
}

#[test]
fn test_sanitize_empty_input() {
    assert_eq!(sanitize(""), "");
    assert_eq!(sanitize("   \n  "), "");
}

#[test]
fn test_build_title_messages_truncates_to_2000_chars() {
    let huge: String = "z".repeat(5000);
    let msgs = build_title_messages(&huge);
    assert_eq!(msgs.len(), 2);
    // First message is system, second is user.
    let user_msg = &msgs[1];
    assert_eq!(user_msg.role, bamboo_agent_core::Role::User);
    assert_eq!(user_msg.content.chars().count(), 2000);
}

#[test]
fn test_build_title_messages_short_input_passthrough() {
    let msgs = build_title_messages("Hi there");
    assert_eq!(msgs.len(), 2);
    assert_eq!(msgs[1].content, "Hi there");
    assert_eq!(msgs[0].role, bamboo_agent_core::Role::System);
}

#[test]
fn first_user_text_skips_textless_turn_so_a_later_message_can_retry() {
    let mut session = Session::new("retry-title", "model");
    session.add_message(Message::user("   "));
    session.add_message(Message::assistant("Image acknowledged", None));
    session.add_message(Message::user("Use this later text for the title"));

    assert_eq!(
        first_user_text(&session).as_deref(),
        Some("Use this later text for the title")
    );
}

#[test]
fn first_user_text_stays_empty_until_a_text_turn_exists() {
    let mut session = Session::new("pending-title", "model");
    session.add_message(Message::user("\n\t"));

    assert!(first_user_text(&session).is_none());
}

#[test]
fn title_provider_fallback_uses_default_provider_instance() {
    let mut config = bamboo_config::Config::default();
    let instance = serde_json::from_value(serde_json::json!({
        "provider_type": "openai",
        "enabled": true
    }))
    .unwrap();
    config.provider = "anthropic".to_string();
    config
        .provider_instances
        .insert("work-openai".to_string(), instance);
    config.default_provider_instance = Some("work-openai".to_string());
    let session = Session::new("title-provider-instance", "model");

    assert_eq!(
        title_provider_name(&config, &session),
        "work-openai",
        "title generation must route through the instance authority"
    );
}