bamboo-server 2026.7.24

HTTP server and API layer for the Bamboo agent framework
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
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
use std::collections::BTreeMap;

use tempfile::tempdir;

use bamboo_config::OpenAIConfig;
use bamboo_llm::Config;

use super::common::{
    config_file_path, connect_backup_file_path, connect_file_path, model_limits_file_path,
    read_model_limits_file, redacted_config_json, write_model_limits_file,
};
use super::reset::remove_config_file_if_exists;

#[test]
fn config_file_path_appends_config_json_filename() {
    let dir = tempdir().expect("temp dir should be created");
    assert_eq!(config_file_path(dir.path()), dir.path().join("config.json"));
}

#[test]
fn model_limits_file_path_appends_model_limits_json_filename() {
    let dir = tempdir().expect("temp dir should be created");
    assert_eq!(
        model_limits_file_path(dir.path()),
        dir.path().join("model_limits.json")
    );
}

#[test]
fn connect_file_path_appends_connect_json_filename() {
    let dir = tempdir().expect("temp dir should be created");
    assert_eq!(
        connect_file_path(dir.path()),
        dir.path().join("connect.json")
    );
}

#[test]
fn connect_backup_file_path_appends_connect_json_bak_filename() {
    let dir = tempdir().expect("temp dir should be created");
    assert_eq!(
        connect_backup_file_path(dir.path()),
        dir.path().join("connect.json.bak")
    );
}

#[actix_web::test]
async fn redacted_config_json_masks_provider_api_key_and_hides_encrypted_proxy_auth() {
    let mut config = Config::default();
    config.providers_mut().openai = Some(OpenAIConfig {
        api_key: "sk-secret".to_string(),
        api_key_from_env: false,
        api_key_encrypted: None,
        base_url: None,
        model: None,
        fast_model: None,
        vision_model: None,
        reasoning_effort: None,
        responses_only_models: vec![],
        request_overrides: None,
        extra: BTreeMap::new(),
    });
    config.proxy_auth_encrypted = Some("enc:deadbeef".to_string());

    let dir = tempdir().expect("temp dir should be created");
    let value = redacted_config_json(&config, dir.path())
        .await
        .expect("redacted config should serialize");
    assert_eq!(value["providers"]["openai"]["api_key"], "****...****");
    assert!(value.get("proxy_auth_encrypted").is_none());
}

#[actix_web::test]
async fn remove_config_file_if_exists_deletes_existing_file() {
    let dir = tempdir().expect("temp dir should be created");
    let path = dir.path().join("config.json");
    tokio::fs::write(&path, "{}")
        .await
        .expect("test file should be written");

    remove_config_file_if_exists(&path)
        .await
        .expect("existing config file should be deleted");
    assert!(!path.exists());
}

#[actix_web::test]
async fn remove_config_file_if_exists_is_noop_when_missing() {
    let dir = tempdir().expect("temp dir should be created");
    let path = dir.path().join("config.json");

    remove_config_file_if_exists(&path)
        .await
        .expect("missing config file should not fail");
    assert!(!path.exists());
}

#[actix_web::test]
async fn redacted_config_json_injects_model_limits_from_file() {
    let dir = tempdir().expect("temp dir should be created");
    write_model_limits_file(
        dir.path(),
        Some(&serde_json::json!([
            {
                "model_pattern": "gpt-5",
                "max_context_tokens": 400000,
                "max_output_tokens": 128000,
                "safety_margin": 1000
            }
        ])),
    )
    .await
    .expect("model limits file should be written");

    let value = redacted_config_json(&Config::default(), dir.path())
        .await
        .expect("redacted config should serialize");
    assert_eq!(value["model_limits"][0]["model_pattern"], "gpt-5");
}

#[actix_web::test]
async fn remove_config_file_if_exists_deletes_model_limits_file() {
    let dir = tempdir().expect("temp dir should be created");
    let path = dir.path().join("model_limits.json");
    tokio::fs::write(&path, "[]")
        .await
        .expect("model limits file should be written");

    remove_config_file_if_exists(&path)
        .await
        .expect("existing model limits file should be deleted");
    assert!(!path.exists());
}

// --- Full persistence (all user-provided overrides are stored) ------------

/// All user-provided rows must be persisted, including rows that happen to
/// match the global default.
#[actix_web::test]
async fn write_model_limits_file_persists_all_rows_round_trip() {
    let dir = tempdir().expect("temp dir should be created");

    write_model_limits_file(
        dir.path(),
        Some(&serde_json::json!([
            { "model_pattern": "gpt-4o", "max_context_tokens": 128000, "max_output_tokens": 16384 },
            { "model_pattern": "some-default-model", "max_context_tokens": 1000000, "max_output_tokens": 64000 }
        ])),
    )
    .await
    .expect("model limits file should be written");

    let persisted = read_model_limits_file(dir.path())
        .await
        .expect("read should succeed")
        .expect("file should exist");

    let rows = persisted.as_array().expect("array");
    assert_eq!(rows.len(), 2, "all rows must be persisted");
    assert_eq!(rows[0]["model_pattern"], "gpt-4o");
    assert_eq!(rows[1]["model_pattern"], "some-default-model");
}

/// Saving an empty overrides array must remove the file entirely so
/// everything falls back to the global default.
#[actix_web::test]
async fn write_model_limits_file_removes_file_when_empty() {
    let dir = tempdir().expect("temp dir should be created");
    let path = model_limits_file_path(dir.path());

    // Pre-existing override on disk.
    tokio::fs::write(
        &path,
        r#"[{"model_pattern":"gpt-4o","max_context_tokens":128000,"max_output_tokens":16384}]"#,
    )
    .await
    .expect("seed file");

    // User clears all overrides → empty array.
    write_model_limits_file(dir.path(), Some(&serde_json::json!([])))
        .await
        .expect("write should succeed");

    assert!(
        !path.exists(),
        "file should be removed when overrides list is empty"
    );
    assert!(read_model_limits_file(dir.path())
        .await
        .expect("read should succeed")
        .is_none());
}

/// An explicit safety margin must be persisted alongside the override.
#[actix_web::test]
async fn write_model_limits_file_keeps_custom_safety_margin() {
    let dir = tempdir().expect("temp dir should be created");

    write_model_limits_file(
        dir.path(),
        Some(&serde_json::json!([
            { "model_pattern": "gpt-4o", "max_context_tokens": 200000, "max_output_tokens": 64000, "safety_margin": 500 }
        ])),
    )
    .await
    .expect("write should succeed");

    let persisted = read_model_limits_file(dir.path())
        .await
        .expect("read should succeed")
        .expect("file should exist");
    let rows = persisted.as_array().expect("array");
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0]["safety_margin"], 500);
}

/// End-to-end over the real HTTP handlers + `AppState`: POST a config carrying
/// `model_limits` (two overrides), then GET it back. Asserts:
/// - ALL overrides are persisted (including default-equal rows),
/// - `config.json` does NOT carry the `model_limits` key (it is split out),
/// - GET re-injects `model_limits` from the dedicated file.
#[actix_web::test]
async fn set_then_get_bamboo_config_round_trips_all_overrides() {
    use crate::app_state::AppState;
    use actix_web::{test, web, App};

    let temp_dir = tempdir().expect("temp dir should be created");
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");
    let data_dir = state.app_data_dir.clone();
    let app_state = web::Data::new(state);

    let app = test::init_service(
        App::new()
            .app_data(app_state.clone())
            .route("/bamboo/config", web::get().to(super::get_bamboo_config))
            .route("/bamboo/config", web::post().to(super::set_bamboo_config)),
    )
    .await;

    let post = test::TestRequest::post()
        .uri("/bamboo/config")
        .set_json(serde_json::json!({
            "model": "gpt-4o",
            "model_limits": [
                { "model_pattern": "gpt-4o", "max_context_tokens": 128000, "max_output_tokens": 16384 },
                { "model_pattern": "noop", "max_context_tokens": 200000, "max_output_tokens": 64000 }
            ]
        }))
        .to_request();
    let post_resp = test::call_service(&app, post).await;
    assert!(post_resp.status().is_success(), "set config should succeed");

    // All overrides survive on disk (no diff-only filtering).
    let on_disk = read_model_limits_file(&data_dir)
        .await
        .expect("read should succeed")
        .expect("model_limits.json should exist");
    let rows = on_disk.as_array().expect("array");
    assert_eq!(rows.len(), 2, "all rows must be persisted");
    assert_eq!(rows[0]["model_pattern"], "gpt-4o");
    assert_eq!(rows[1]["model_pattern"], "noop");

    // config.json must not carry the model_limits key.
    let config_text = tokio::fs::read_to_string(config_file_path(&data_dir))
        .await
        .expect("config.json should exist after set");
    let config_json: serde_json::Value =
        serde_json::from_str(&config_text).expect("config.json should be valid json");
    assert!(
        config_json.get("model_limits").is_none(),
        "model_limits must be split out of config.json"
    );

    // GET re-injects model_limits from the dedicated file.
    let get = test::TestRequest::get().uri("/bamboo/config").to_request();
    let body: serde_json::Value = test::call_and_read_body_json(&app, get).await;
    let limits = body["model_limits"]
        .as_array()
        .expect("model_limits should be present in GET response");
    assert_eq!(limits.len(), 2);
    assert_eq!(limits[0]["model_pattern"], "gpt-4o");
    assert_eq!(limits[0]["max_context_tokens"], 128000);
}

/// End-to-end: POST an ntfy token, confirm the GET response masks it, then
/// POST again with the masked placeholder unchanged (as the UI would on an
/// unrelated field edit) — the exact-mask keep-on-save rule must resolve that
/// back to the live plaintext rather than wiping the stored secret. #430-style
/// contract, applied to the new notification channel secrets.
#[actix_web::test]
async fn set_then_get_bamboo_config_masks_and_preserves_ntfy_token() {
    use crate::app_state::AppState;
    use actix_web::{test, web, App};

    let temp_dir = tempdir().expect("temp dir should be created");
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");
    let data_dir = state.app_data_dir.clone();
    let app_state = web::Data::new(state);

    let app = test::init_service(
        App::new()
            .app_data(app_state.clone())
            .route("/bamboo/config", web::get().to(super::get_bamboo_config))
            .route("/bamboo/config", web::post().to(super::set_bamboo_config)),
    )
    .await;

    // 1) Set a real ntfy token.
    let post = test::TestRequest::post()
        .uri("/bamboo/config")
        .set_json(serde_json::json!({
            "notifications": {
                "ntfy": {
                    "enabled": true,
                    "base_url": "https://ntfy.sh",
                    "topic": "bamboo-alerts",
                    "token": "tk-real-secret"
                }
            }
        }))
        .to_request();
    let post_resp = test::call_service(&app, post).await;
    assert!(post_resp.status().is_success(), "set config should succeed");

    // The stored config.json must hold ciphertext, never the plaintext token.
    let config_text = tokio::fs::read_to_string(config_file_path(&data_dir))
        .await
        .expect("config.json should exist after set");
    assert!(
        config_text.contains("token_encrypted"),
        "ntfy token must be persisted encrypted"
    );
    assert!(
        !config_text.contains("tk-real-secret"),
        "plaintext ntfy token must never be persisted"
    );

    // 2) GET masks the token as configured.
    let get = test::TestRequest::get().uri("/bamboo/config").to_request();
    let body: serde_json::Value = test::call_and_read_body_json(&app, get).await;
    assert_eq!(body["notifications"]["ntfy"]["token"], "****...****");
    assert_eq!(body["notifications"]["ntfy"]["topic"], "bamboo-alerts");

    // 3) Re-POST with the masked placeholder (as the UI echoes it back) plus
    // an unrelated field change — the secret must survive untouched.
    let post2 = test::TestRequest::post()
        .uri("/bamboo/config")
        .set_json(serde_json::json!({
            "notifications": {
                "ntfy": {
                    "enabled": true,
                    "base_url": "https://ntfy.sh",
                    "topic": "renamed-topic",
                    "token": "****...****"
                }
            }
        }))
        .to_request();
    let post2_resp = test::call_service(&app, post2).await;
    assert!(
        post2_resp.status().is_success(),
        "second set config should succeed"
    );

    let get2 = test::TestRequest::get().uri("/bamboo/config").to_request();
    let body2: serde_json::Value = test::call_and_read_body_json(&app, get2).await;
    assert_eq!(
        body2["notifications"]["ntfy"]["token"], "****...****",
        "token must still read as configured"
    );
    assert_eq!(
        body2["notifications"]["ntfy"]["topic"], "renamed-topic",
        "unrelated field change must apply"
    );
}

/// End-to-end for #455: a settings PATCH that sets a bamboo-connect platform
/// must persist into the standalone `connect.json` — NOT into `config.json`
/// — while the settings API (GET redaction, masked-token keep-on-save)
/// behaves exactly as it did before the persistence split.
#[actix_web::test]
async fn set_bamboo_config_persists_connect_into_connect_json_only_and_preserves_masked_token() {
    use crate::app_state::AppState;
    use actix_web::{test, web, App};
    use bamboo_config::encryption;

    // NOTE: deliberately NOT using `encryption::set_test_encryption_key` here —
    // the actual save happens inside `AppState::persist_config_snapshot`'s
    // `tokio::task::spawn_blocking`, a different OS thread than this test body,
    // and the test-key override is thread-local (by design, so parallel tests
    // don't clobber a process-global override). An override set here would
    // only apply to the `decrypt` calls below, not the `encrypt` that ran on
    // the blocking pool thread, and the two would silently use different keys.
    // The encryption key file itself is already stable for this whole test
    // binary process (`bamboo_dir()`'s "first call wins" OnceLock — see
    // `paths::tests::test_init_bamboo_dir_first_call_wins`), so plain
    // `encryption::decrypt` here round-trips correctly against whatever key
    // the blocking-thread `encrypt` used.
    let temp_dir = tempdir().expect("temp dir should be created");
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");
    let data_dir = state.app_data_dir.clone();
    let app_state = web::Data::new(state);

    let app = test::init_service(
        App::new()
            .app_data(app_state.clone())
            .route("/bamboo/config", web::get().to(super::get_bamboo_config))
            .route("/bamboo/config", web::post().to(super::set_bamboo_config)),
    )
    .await;

    // 1) Set a real Telegram bot token via the settings PATCH surface.
    let post = test::TestRequest::post()
        .uri("/bamboo/config")
        .set_json(serde_json::json!({
            "connect": {
                "platforms": [
                    { "type": "telegram", "token": "tg-real-secret", "allow_from": ["u1"] }
                ]
            }
        }))
        .to_request();
    let post_resp = test::call_service(&app, post).await;
    assert!(post_resp.status().is_success(), "set config should succeed");

    // config.json must NOT carry the `connect` key at all (#455 split).
    let config_text = tokio::fs::read_to_string(config_file_path(&data_dir))
        .await
        .expect("config.json should exist after set");
    assert!(
        !config_text.contains("\"connect\""),
        "config.json must not persist the connect key"
    );
    assert!(
        !config_text.contains("tg-real-secret"),
        "plaintext connect token must never be persisted anywhere"
    );

    // connect.json holds the platform, encrypted at rest.
    let connect_path = data_dir.join("connect.json");
    let connect_text = tokio::fs::read_to_string(&connect_path)
        .await
        .expect("connect.json should exist after set");
    assert!(
        connect_text.contains("token_encrypted"),
        "connect token must be persisted encrypted in connect.json"
    );
    assert!(
        !connect_text.contains("tg-real-secret"),
        "plaintext connect token must never be persisted in connect.json"
    );
    let connect_json: serde_json::Value =
        serde_json::from_str(&connect_text).expect("connect.json should parse");
    let token_encrypted = connect_json["platforms"][0]["token_encrypted"]
        .as_str()
        .expect("token_encrypted should be present")
        .to_string();
    assert_eq!(
        encryption::decrypt(&token_encrypted).expect("token should decrypt"),
        "tg-real-secret"
    );

    // 2) GET masks the token exactly as before the split (settings API surface
    // is unchanged; it reads the in-memory Config, unaware of the file split).
    let get = test::TestRequest::get().uri("/bamboo/config").to_request();
    let body: serde_json::Value = test::call_and_read_body_json(&app, get).await;
    assert_eq!(body["connect"]["platforms"][0]["token"], "****...****");
    assert_eq!(body["connect"]["platforms"][0]["type"], "telegram");

    // 3) Re-POST with the masked placeholder (as the UI echoes it back) plus
    // an unrelated field change — the secret must survive untouched, and
    // still land only in connect.json.
    let post2 = test::TestRequest::post()
        .uri("/bamboo/config")
        .set_json(serde_json::json!({
            "connect": {
                "platforms": [
                    { "type": "telegram", "token": "****...****", "allow_from": ["u1", "u2"] }
                ]
            }
        }))
        .to_request();
    let post2_resp = test::call_service(&app, post2).await;
    assert!(
        post2_resp.status().is_success(),
        "second set config should succeed"
    );

    let get2 = test::TestRequest::get().uri("/bamboo/config").to_request();
    let body2: serde_json::Value = test::call_and_read_body_json(&app, get2).await;
    assert_eq!(
        body2["connect"]["platforms"][0]["token"], "****...****",
        "token must still read as configured"
    );
    assert_eq!(
        body2["connect"]["platforms"][0]["allow_from"],
        serde_json::json!(["u1", "u2"]),
        "unrelated field change must apply"
    );

    let connect_text_after = tokio::fs::read_to_string(&connect_path)
        .await
        .expect("connect.json should still exist");
    let connect_json_after: serde_json::Value =
        serde_json::from_str(&connect_text_after).expect("connect.json should parse");
    let token_encrypted_after = connect_json_after["platforms"][0]["token_encrypted"]
        .as_str()
        .expect("token_encrypted should still be present")
        .to_string();
    assert_eq!(
        encryption::decrypt(&token_encrypted_after).expect("token should decrypt"),
        "tg-real-secret",
        "masked round-trip preserves the real token across the split files"
    );

    let config_text_after = tokio::fs::read_to_string(config_file_path(&data_dir))
        .await
        .expect("config.json should still exist");
    assert!(
        !config_text_after.contains("\"connect\""),
        "config.json must still not carry the connect key after the second PATCH"
    );
}

/// Feishu adapter config plumbing (epic #447 phase 3, §2a): `app_id`/`domain`
/// are plain fields, `app_secret` follows the exact same encrypted-at-rest +
/// masked-GET + masked-preserve-on-PATCH contract as the Telegram `token`
/// above.
#[actix_web::test]
async fn set_bamboo_config_persists_feishu_app_secret_encrypted_and_preserves_masked_value() {
    use crate::app_state::AppState;
    use actix_web::{test, web, App};
    use bamboo_config::encryption;

    // See the long NOTE on the Telegram equivalent above for why the
    // process-global (not thread-local) encryption key is relied on here.
    let temp_dir = tempdir().expect("temp dir should be created");
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");
    let data_dir = state.app_data_dir.clone();
    let app_state = web::Data::new(state);

    let app = test::init_service(
        App::new()
            .app_data(app_state.clone())
            .route("/bamboo/config", web::get().to(super::get_bamboo_config))
            .route("/bamboo/config", web::post().to(super::set_bamboo_config)),
    )
    .await;

    // 1) Set a Feishu entry with app_id, app_secret, domain via the settings
    // PATCH surface.
    let post = test::TestRequest::post()
        .uri("/bamboo/config")
        .set_json(serde_json::json!({
            "connect": {
                "platforms": [
                    {
                        "type": "feishu",
                        "app_id": "cli_real_app_id",
                        "app_secret": "feishu-real-secret",
                        "domain": "lark",
                        "allow_from": ["ou_1"]
                    }
                ]
            }
        }))
        .to_request();
    let post_resp = test::call_service(&app, post).await;
    assert!(post_resp.status().is_success(), "set config should succeed");

    // config.json must NOT carry the `connect` key at all (#455 split).
    let config_text = tokio::fs::read_to_string(config_file_path(&data_dir))
        .await
        .expect("config.json should exist after set");
    assert!(
        !config_text.contains("\"connect\""),
        "config.json must not persist the connect key"
    );
    assert!(
        !config_text.contains("feishu-real-secret"),
        "plaintext app_secret must never be persisted anywhere"
    );

    // connect.json holds app_id/domain in plain and app_secret encrypted.
    let connect_path = data_dir.join("connect.json");
    let connect_text = tokio::fs::read_to_string(&connect_path)
        .await
        .expect("connect.json should exist after set");
    assert!(
        connect_text.contains("app_secret_encrypted"),
        "app_secret must be persisted encrypted in connect.json"
    );
    assert!(
        !connect_text.contains("feishu-real-secret"),
        "plaintext app_secret must never be persisted in connect.json"
    );
    let connect_json: serde_json::Value =
        serde_json::from_str(&connect_text).expect("connect.json should parse");
    assert_eq!(connect_json["platforms"][0]["app_id"], "cli_real_app_id");
    assert_eq!(connect_json["platforms"][0]["domain"], "lark");
    let app_secret_encrypted = connect_json["platforms"][0]["app_secret_encrypted"]
        .as_str()
        .expect("app_secret_encrypted should be present")
        .to_string();
    assert_eq!(
        encryption::decrypt(&app_secret_encrypted).expect("app_secret should decrypt"),
        "feishu-real-secret"
    );

    // 2) GET masks app_secret but leaves app_id/domain visible.
    let get = test::TestRequest::get().uri("/bamboo/config").to_request();
    let body: serde_json::Value = test::call_and_read_body_json(&app, get).await;
    assert_eq!(body["connect"]["platforms"][0]["app_secret"], "****...****");
    assert_eq!(body["connect"]["platforms"][0]["app_id"], "cli_real_app_id");
    assert_eq!(body["connect"]["platforms"][0]["domain"], "lark");

    // 3) Re-POST with the masked placeholder plus an unrelated field change —
    // the secret must survive untouched.
    let post2 = test::TestRequest::post()
        .uri("/bamboo/config")
        .set_json(serde_json::json!({
            "connect": {
                "platforms": [
                    {
                        "type": "feishu",
                        "app_id": "cli_real_app_id",
                        "app_secret": "****...****",
                        "domain": "lark",
                        "allow_from": ["ou_1", "ou_2"]
                    }
                ]
            }
        }))
        .to_request();
    let post2_resp = test::call_service(&app, post2).await;
    assert!(
        post2_resp.status().is_success(),
        "second set config should succeed"
    );

    let get2 = test::TestRequest::get().uri("/bamboo/config").to_request();
    let body2: serde_json::Value = test::call_and_read_body_json(&app, get2).await;
    assert_eq!(
        body2["connect"]["platforms"][0]["app_secret"], "****...****",
        "app_secret must still read as configured"
    );
    assert_eq!(
        body2["connect"]["platforms"][0]["allow_from"],
        serde_json::json!(["ou_1", "ou_2"]),
        "unrelated field change must apply"
    );

    let connect_text_after = tokio::fs::read_to_string(&connect_path)
        .await
        .expect("connect.json should still exist");
    let connect_json_after: serde_json::Value =
        serde_json::from_str(&connect_text_after).expect("connect.json should parse");
    let app_secret_encrypted_after = connect_json_after["platforms"][0]["app_secret_encrypted"]
        .as_str()
        .expect("app_secret_encrypted should still be present")
        .to_string();
    assert_eq!(
        encryption::decrypt(&app_secret_encrypted_after).expect("app_secret should decrypt"),
        "feishu-real-secret",
        "masked round-trip preserves the real app_secret across the split files"
    );
}

/// #490 end-to-end: the settings PATCH surface must preserve a masked secret
/// even when a preceding platform entry is removed in the same request,
/// shifting the kept entry's array index. Stored platforms are
/// `[telegram, feishu]`; the client disables telegram and re-POSTs only the
/// (still-masked) feishu entry, which now lands at index 0 instead of 1.
/// Before the #490 fix, the positional type-guard (added for #454) saw
/// telegram≠feishu at index 0 and silently dropped the feishu app_secret.
#[actix_web::test]
async fn set_bamboo_config_preserves_masked_secret_when_preceding_platform_removed() {
    use crate::app_state::AppState;
    use actix_web::{test, web, App};
    use bamboo_config::encryption;

    // See the long NOTE on the Telegram test above for why the process-global
    // (not thread-local) encryption key is relied on here.
    let temp_dir = tempdir().expect("temp dir should be created");
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");
    let data_dir = state.app_data_dir.clone();
    let app_state = web::Data::new(state);

    let app = test::init_service(
        App::new()
            .app_data(app_state.clone())
            .route("/bamboo/config", web::get().to(super::get_bamboo_config))
            .route("/bamboo/config", web::post().to(super::set_bamboo_config)),
    )
    .await;

    // 1) Set both a Telegram bot token and a Feishu app_secret, in that order.
    let post = test::TestRequest::post()
        .uri("/bamboo/config")
        .set_json(serde_json::json!({
            "connect": {
                "platforms": [
                    { "type": "telegram", "token": "tg-real-secret", "allow_from": ["u1"] },
                    {
                        "type": "feishu",
                        "app_id": "cli_real_app_id",
                        "app_secret": "feishu-real-secret",
                        "domain": "lark",
                        "allow_from": ["ou_1"]
                    }
                ]
            }
        }))
        .to_request();
    let post_resp = test::call_service(&app, post).await;
    assert!(post_resp.status().is_success(), "set config should succeed");

    // 2) GET, confirm both entries round-trip masked, in stored order.
    let get = test::TestRequest::get().uri("/bamboo/config").to_request();
    let body: serde_json::Value = test::call_and_read_body_json(&app, get).await;
    assert_eq!(body["connect"]["platforms"][0]["type"], "telegram");
    assert_eq!(body["connect"]["platforms"][1]["type"], "feishu");
    assert_eq!(body["connect"]["platforms"][1]["app_secret"], "****...****");

    // 3) Re-POST with telegram removed — the UI's echoed feishu entry (still
    // masked) now sits at index 0, not index 1 where it was stored.
    let post2 = test::TestRequest::post()
        .uri("/bamboo/config")
        .set_json(serde_json::json!({
            "connect": {
                "platforms": [
                    {
                        "type": "feishu",
                        "app_id": "cli_real_app_id",
                        "app_secret": "****...****",
                        "domain": "lark",
                        "allow_from": ["ou_1"]
                    }
                ]
            }
        }))
        .to_request();
    let post2_resp = test::call_service(&app, post2).await;
    assert!(
        post2_resp.status().is_success(),
        "second set config should succeed"
    );

    // The feishu app_secret must still read as configured, not wiped.
    let get2 = test::TestRequest::get().uri("/bamboo/config").to_request();
    let body2: serde_json::Value = test::call_and_read_body_json(&app, get2).await;
    assert_eq!(
        body2["connect"]["platforms"][0]["type"], "feishu",
        "telegram entry should be gone, feishu now at index 0"
    );
    assert_eq!(
        body2["connect"]["platforms"][0]["app_secret"], "****...****",
        "app_secret must still read as configured after the index shift"
    );

    // And the plaintext on disk (encrypted at rest) must be unchanged, not
    // wiped by the removed-entry-shifted-index case.
    let connect_path = data_dir.join("connect.json");
    let connect_text_after = tokio::fs::read_to_string(&connect_path)
        .await
        .expect("connect.json should still exist");
    let connect_json_after: serde_json::Value =
        serde_json::from_str(&connect_text_after).expect("connect.json should parse");
    assert_eq!(connect_json_after["platforms"].as_array().unwrap().len(), 1);
    let app_secret_encrypted_after = connect_json_after["platforms"][0]["app_secret_encrypted"]
        .as_str()
        .expect("app_secret_encrypted should still be present")
        .to_string();
    assert_eq!(
        encryption::decrypt(&app_secret_encrypted_after).expect("app_secret should decrypt"),
        "feishu-real-secret",
        "masked secret must resolve by type after a preceding entry was removed, not be dropped"
    );
}

/// #455 gap: a full config reset must also clear `connect.json`, or a
/// bamboo-connect bot token would silently survive `POST
/// /bamboo/config/reset` and get re-merged back onto the freshly-defaulted
/// config on the very next load (`Config::merge_connect_config` adopts
/// whatever connect.json still has).
#[actix_web::test]
async fn reset_bamboo_config_also_deletes_connect_json() {
    use crate::app_state::AppState;
    use actix_web::{test, web, App};

    let temp_dir = tempdir().expect("temp dir should be created");
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");
    let data_dir = state.app_data_dir.clone();
    let app_state = web::Data::new(state);

    let app = test::init_service(
        App::new()
            .app_data(app_state.clone())
            .route("/bamboo/config", web::get().to(super::get_bamboo_config))
            .route("/bamboo/config", web::post().to(super::set_bamboo_config))
            .route(
                "/bamboo/config/reset",
                web::post().to(super::reset_bamboo_config),
            ),
    )
    .await;

    // Configure a connect platform (creates connect.json).
    let post = test::TestRequest::post()
        .uri("/bamboo/config")
        .set_json(serde_json::json!({
            "connect": {
                "platforms": [
                    { "type": "telegram", "token": "tg-reset-me", "allow_from": ["u1"] }
                ]
            }
        }))
        .to_request();
    assert!(test::call_service(&app, post).await.status().is_success());

    let connect_path = data_dir.join("connect.json");
    assert!(
        connect_path.exists(),
        "connect.json should exist before reset"
    );

    // Reset.
    let reset = test::TestRequest::post()
        .uri("/bamboo/config/reset")
        .to_request();
    assert!(
        test::call_service(&app, reset).await.status().is_success(),
        "reset should succeed"
    );

    assert!(
        !connect_path.exists(),
        "connect.json must be deleted by a full config reset"
    );

    // The in-memory config must also be clear, not silently re-merged.
    let get = test::TestRequest::get().uri("/bamboo/config").to_request();
    let body: serde_json::Value = test::call_and_read_body_json(&app, get).await;
    assert!(
        body["connect"]["platforms"]
            .as_array()
            .map(|a| a.is_empty())
            .unwrap_or(true),
        "connect config must be empty after reset, not re-adopted from a stale file"
    );
}

/// #457: a full config reset must also clear `connect.json.bak`. Unlike
/// `config.json.bak` (a low-sensitivity config snapshot intentionally left
/// alone by reset, for recovery), connect.json(.bak) holds an encrypted IM
/// bot token — an immediately-usable remote-control credential — that must
/// not stay recoverable straight off disk after the user asks for a full
/// reset.
#[actix_web::test]
async fn reset_bamboo_config_also_deletes_connect_json_bak() {
    use crate::app_state::AppState;
    use actix_web::{test, web, App};

    let temp_dir = tempdir().expect("temp dir should be created");
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");
    let data_dir = state.app_data_dir.clone();
    let app_state = web::Data::new(state);

    let app = test::init_service(
        App::new()
            .app_data(app_state.clone())
            .route("/bamboo/config", web::get().to(super::get_bamboo_config))
            .route("/bamboo/config", web::post().to(super::set_bamboo_config))
            .route(
                "/bamboo/config/reset",
                web::post().to(super::reset_bamboo_config),
            ),
    )
    .await;

    // Configure a connect platform, then change it again so a
    // `connect.json.bak` gets written (the save path backs up the previous
    // connect.json before overwriting it).
    for token in ["tg-first-token", "tg-second-token"] {
        let post = test::TestRequest::post()
            .uri("/bamboo/config")
            .set_json(serde_json::json!({
                "connect": {
                    "platforms": [
                        { "type": "telegram", "token": token, "allow_from": ["u1"] }
                    ]
                }
            }))
            .to_request();
        assert!(test::call_service(&app, post).await.status().is_success());
    }

    let connect_path = data_dir.join("connect.json");
    let connect_backup_path = data_dir.join("connect.json.bak");
    assert!(
        connect_path.exists(),
        "connect.json should exist before reset"
    );
    assert!(
        connect_backup_path.exists(),
        "connect.json.bak should exist before reset (written by the second save)"
    );

    // Reset.
    let reset = test::TestRequest::post()
        .uri("/bamboo/config/reset")
        .to_request();
    assert!(
        test::call_service(&app, reset).await.status().is_success(),
        "reset should succeed"
    );

    assert!(
        !connect_path.exists(),
        "connect.json must be deleted by a full config reset"
    );
    assert!(
        !connect_backup_path.exists(),
        "connect.json.bak must also be deleted by a full config reset — it holds \
         a live, immediately-usable bot token"
    );
}

// ── config-corruption recovery status + confirm API (#153) ─────────────────

/// GET /bamboo/config/recovery-status reports no pending recovery on a clean
/// config.json, and a full pending status (source + quarantine path) after
/// booting against a corrupt one.
#[actix_web::test]
async fn get_config_recovery_status_reports_pending_state_after_corrupt_boot() {
    use crate::app_state::AppState;
    use actix_web::{test, web, App};

    // No pending recovery on a totally fresh data dir.
    let clean_dir = tempdir().expect("temp dir should be created");
    let clean_state = AppState::new(clean_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");
    let clean_app = test::init_service(App::new().app_data(web::Data::new(clean_state)).route(
        "/bamboo/config/recovery-status",
        web::get().to(super::get_config_recovery_status),
    ))
    .await;
    let get = test::TestRequest::get()
        .uri("/bamboo/config/recovery-status")
        .to_request();
    let body: serde_json::Value = test::call_and_read_body_json(&clean_app, get).await;
    assert_eq!(body["pending"], false);

    // Boot against a corrupt config.json (no .bak) -> defaults + pending recovery.
    let corrupt_dir = tempdir().expect("temp dir should be created");
    std::fs::write(corrupt_dir.path().join("config.json"), "}}} broken").unwrap();
    let corrupt_state = AppState::new(corrupt_dir.path().to_path_buf())
        .await
        .expect("app state should still initialize");
    let corrupt_app = test::init_service(App::new().app_data(web::Data::new(corrupt_state)).route(
        "/bamboo/config/recovery-status",
        web::get().to(super::get_config_recovery_status),
    ))
    .await;
    let get = test::TestRequest::get()
        .uri("/bamboo/config/recovery-status")
        .to_request();
    let body: serde_json::Value = test::call_and_read_body_json(&corrupt_app, get).await;
    assert_eq!(body["pending"], true);
    assert_eq!(body["status"]["confirmed"], false);
    assert_eq!(body["status"]["source"]["kind"], "defaults");
    assert!(
        body["status"]["quarantine_path"].is_string(),
        "quarantine_path should point at the preserved corrupt original"
    );
}

/// POST /bamboo/config/recovery/confirm with `{"accept": true}` persists the
/// recovered config and flips `pending` to `false`; a subsequent GET agrees.
#[actix_web::test]
async fn confirm_config_recovery_endpoint_accept_clears_pending_state() {
    use crate::app_state::AppState;
    use actix_web::{test, web, App};

    let temp_dir = tempdir().expect("temp dir should be created");
    std::fs::write(
        temp_dir.path().join("config.json"),
        r#"{"http_proxy":"http://salvaged","env_vars":"bad-type"}"#,
    )
    .unwrap();
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");
    let data_dir = state.app_data_dir.clone();
    let app = test::init_service(
        App::new()
            .app_data(web::Data::new(state))
            .route(
                "/bamboo/config/recovery-status",
                web::get().to(super::get_config_recovery_status),
            )
            .route(
                "/bamboo/config/recovery/confirm",
                web::post().to(super::confirm_config_recovery),
            ),
    )
    .await;

    let confirm = test::TestRequest::post()
        .uri("/bamboo/config/recovery/confirm")
        .set_json(serde_json::json!({ "accept": true }))
        .to_request();
    let confirm_resp = test::call_service(&app, confirm).await;
    assert!(
        confirm_resp.status().is_success(),
        "accepting a pending recovery should succeed"
    );
    let body: serde_json::Value = test::read_body_json(confirm_resp).await;
    assert_eq!(body["pending"], false);

    let get = test::TestRequest::get()
        .uri("/bamboo/config/recovery-status")
        .to_request();
    let body: serde_json::Value = test::call_and_read_body_json(&app, get).await;
    assert_eq!(
        body["pending"], false,
        "a follow-up GET agrees the recovery is resolved"
    );

    let on_disk = tokio::fs::read_to_string(config_file_path(&data_dir))
        .await
        .expect("config.json should exist");
    assert!(
        on_disk.contains("http://salvaged"),
        "the recovered state was actually persisted to config.json"
    );
}

/// POST with `{"accept": false}` leaves config.json untouched and `pending`
/// still `true`.
#[actix_web::test]
async fn confirm_config_recovery_endpoint_reject_leaves_pending_state() {
    use crate::app_state::AppState;
    use actix_web::{test, web, App};

    let temp_dir = tempdir().expect("temp dir should be created");
    let corrupt_bytes = "}}} broken";
    std::fs::write(temp_dir.path().join("config.json"), corrupt_bytes).unwrap();
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");
    let data_dir = state.app_data_dir.clone();
    let app = test::init_service(App::new().app_data(web::Data::new(state)).route(
        "/bamboo/config/recovery/confirm",
        web::post().to(super::confirm_config_recovery),
    ))
    .await;

    let confirm = test::TestRequest::post()
        .uri("/bamboo/config/recovery/confirm")
        .set_json(serde_json::json!({ "accept": false }))
        .to_request();
    let confirm_resp = test::call_service(&app, confirm).await;
    assert!(confirm_resp.status().is_success());
    let body: serde_json::Value = test::read_body_json(confirm_resp).await;
    assert_eq!(body["pending"], true, "reject leaves the recovery pending");

    let on_disk = tokio::fs::read_to_string(config_file_path(&data_dir))
        .await
        .expect("config.json should exist");
    assert_eq!(
        on_disk, corrupt_bytes,
        "reject must not touch the on-disk corrupt original"
    );
}

/// POST /bamboo/config/recovery/confirm with nothing pending is a 400, not a
/// silent success.
#[actix_web::test]
async fn confirm_config_recovery_endpoint_errors_when_nothing_pending() {
    use crate::app_state::AppState;
    use actix_web::{test, web, App};

    let temp_dir = tempdir().expect("temp dir should be created");
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");
    let app = test::init_service(App::new().app_data(web::Data::new(state)).route(
        "/bamboo/config/recovery/confirm",
        web::post().to(super::confirm_config_recovery),
    ))
    .await;

    let confirm = test::TestRequest::post()
        .uri("/bamboo/config/recovery/confirm")
        .set_json(serde_json::json!({ "accept": true }))
        .to_request();
    let confirm_resp = test::call_service(&app, confirm).await;
    assert_eq!(
        confirm_resp.status(),
        actix_web::http::StatusCode::BAD_REQUEST
    );
}