rpi-cli 0.9.2

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
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
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
use super::*;

fn state_with_root(root: &std::path::Path) -> Arc<TuiState> {
    let mut state = test_tui_state();
    Arc::get_mut(&mut state).unwrap().session_dir = root.to_path_buf();
    state
}

fn assert_session_locked(path: &str) {
    let lock = std::fs::OpenOptions::new()
        .create(true)
        .write(true)
        .open(format!("{path}.lock"))
        .unwrap();
    assert!(
        fs2::FileExt::try_lock_exclusive(&lock).is_err(),
        "{path} must remain exclusively locked"
    );
}

/// An empty authenticated catalog: these tests exercise session plumbing, not
/// model resolution, so `restore_session_model` finds nothing to apply and
/// leaves the lane untouched.
fn empty_catalog() -> Arc<std::sync::RwLock<Vec<rpi_ai::Model>>> {
    Arc::new(std::sync::RwLock::new(Vec::new()))
}

#[tokio::test]
async fn tui_fork_locks_the_copy_and_keeps_the_selected_root_for_switch_and_picker() {
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path().join("project");
    std::fs::create_dir_all(&cwd).unwrap();
    let root = temporary.path().join("custom sessions");
    let source = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    source
        .append_message(user_message_with_images("custom-root history", vec![]))
        .await
        .unwrap();
    let initial_id = source.storage().metadata().id.clone();
    let harness = AgentHarness::create(Default::default()).await.unwrap();
    harness.set_session(source).await.unwrap();
    let state = state_with_root(&root);
    let context = rpi_extensions::ToolCallContext::new(cwd.to_string_lossy());
    fork_session(&harness, &cwd, &state.chat_container, &state, &context).await;
    let fork_id = harness.session().storage().metadata().id.clone();
    assert_ne!(fork_id, initial_id);
    let metadata = crate::session::list_session_metadata_in_dir(&cwd.to_string_lossy(), &root)
        .await
        .unwrap();
    assert_eq!(metadata.len(), 2);
    for row in &metadata {
        assert_session_locked(&row.path);
    }
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    assert!(
        switch_to_session(
            &harness,
            &lane,
            &initial_id,
            &cwd,
            &state.chat_container,
            &state,
            &context,
            &empty_catalog()
        )
        .await
    );
    assert_eq!(harness.session().storage().metadata().id, initial_id);
    let rendered = strip_ansi(&state.chat_container.render(160).join("\n"));
    assert!(rendered.contains("custom-root history"));

    let tui = Arc::new(TuiAltScreen::new(
        Box::new(ProcessTerminal::new()),
        true,
        None,
    ));
    let editor_container = Arc::new(Container::new());
    let (tx, mut rx) = mpsc::unbounded_channel();
    open_session_selector(&state, &editor_container, &state.editor, &tui, &tx);
    assert!(
        state.selector_open(),
        "picker must find sessions in the selected root"
    );
    let router = state
        .active_selector
        .lock()
        .unwrap()
        .as_ref()
        .unwrap()
        .0
        .clone();
    router.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
    let Some(TuiMessage::SwitchSession(selected)) =
        tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
            .await
            .unwrap()
    else {
        panic!("session selection expected")
    };
    assert!(metadata.iter().any(|row| row.path.contains(&selected)));
    assert!(!cwd.join(".rpi/sessions").exists());
}

#[tokio::test]
async fn tui_import_preserves_identity_history_and_source_across_cwds() {
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path().join("project");
    let old_cwd = temporary.path().join("original project");
    std::fs::create_dir_all(&cwd).unwrap();
    std::fs::create_dir_all(&old_cwd).unwrap();
    let root = temporary.path().join("custom sessions");
    let source_root = temporary.path().join("source");
    let source = crate::session::create_jsonl_session(&source_root, &old_cwd.to_string_lossy())
        .await
        .unwrap();
    source.set_name(Some("Imported history")).await.unwrap();
    source
        .append_message(user_message_with_images(
            "preserved imported prompt",
            vec![],
        ))
        .await
        .unwrap();
    let expected = source.storage().metadata().id.clone();
    let source_path = crate::session::list_session_files_sync(&source_root).remove(0);
    let original = std::fs::read(&source_path).unwrap();
    let harness = AgentHarness::create(Default::default()).await.unwrap();
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    let state = state_with_root(&root);
    let context = rpi_extensions::ToolCallContext::new(cwd.to_string_lossy());
    import_session(
        &harness,
        &lane,
        &source_path.to_string_lossy(),
        &cwd,
        &state.chat_container,
        &state,
        &context,
        &empty_catalog(),
    )
    .await;
    assert_eq!(harness.session().storage().metadata().id, expected);
    assert_eq!(
        harness.session().get_name().await.unwrap().as_deref(),
        Some("Imported history")
    );
    assert!(strip_ansi(&state.chat_container.render(160).join("\n"))
        .contains("preserved imported prompt"));
    let metadata = crate::session::list_session_metadata_in_dir(&cwd.to_string_lossy(), &root)
        .await
        .unwrap();
    assert_eq!(metadata.len(), 1);
    assert_eq!(metadata[0].cwd, old_cwd.to_string_lossy());
    assert_session_locked(&metadata[0].path);
    let restored =
        crate::session::open_session_by_id_in_dir(&expected, &cwd.to_string_lossy(), &root)
            .await
            .map_err(|error| error.to_string())
            .unwrap();
    assert_eq!(
        restored.get_name().await.unwrap().as_deref(),
        Some("Imported history")
    );
    let imported = std::fs::read(&metadata[0].path).unwrap();
    assert_eq!(imported, original);
    // Both repeated imports and importing a repository's own log must fail
    // without touching either saved history or the original source.
    for path in [&source_path, &std::path::PathBuf::from(&metadata[0].path)] {
        assert!(
            crate::session::import_session_file(path, &cwd.to_string_lossy(), &root)
                .await
                .err()
                .unwrap()
                .contains("already exists")
        );
    }
    assert_eq!(std::fs::read(&source_path).unwrap(), original);
    assert_eq!(std::fs::read(&metadata[0].path).unwrap(), imported);
    assert_eq!(crate::session::list_session_files_sync(&root).len(), 1);
}

#[tokio::test]
async fn invalid_import_leaves_the_active_session_and_repository_untouched() {
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path();
    let root = cwd.join("selected");
    let invalid = cwd.join("invalid.jsonl");
    std::fs::write(&invalid, "not a session\n").unwrap();
    let harness = AgentHarness::create(Default::default()).await.unwrap();
    let initial = harness.session().storage().metadata().id.clone();
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    let state = state_with_root(&root);
    let context = rpi_extensions::ToolCallContext::new(cwd.to_string_lossy());
    import_session(
        &harness,
        &lane,
        &invalid.to_string_lossy(),
        cwd,
        &state.chat_container,
        &state,
        &context,
        &empty_catalog(),
    )
    .await;
    assert_eq!(harness.session().storage().metadata().id, initial);
    assert!(crate::session::list_session_files_sync(&root).is_empty());
    assert!(
        std::fs::read_dir(&root).unwrap().next().is_none(),
        "staging files must be cleaned up"
    );
    assert_eq!(std::fs::read_to_string(invalid).unwrap(), "not a session\n");
}

/// Every path that rebuilds the transcript for another session must advertise
/// the session's REAL capability snapshot.
///
/// The regression this locks: those paths used to call `add_welcome_message`,
/// which passes empty slices, so a session with tools and skills still showed
/// `Tools (0) none` / `Skills (0) none` right after `/session`, `/import`,
/// `/fork` or tree navigation.
#[tokio::test]
async fn session_switch_banner_reports_real_capabilities() {
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path();
    let root = cwd.join("sessions");
    std::fs::create_dir_all(&root).unwrap();
    let first = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let first_id = first.storage().metadata().id.clone();
    first
        .append_message(user_message_with_images("first session history", vec![]))
        .await
        .unwrap();
    let second = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let second_id = second.storage().metadata().id.clone();
    assert_ne!(first_id, second_id);

    let harness = AgentHarness::create(Default::default()).await.unwrap();
    harness.set_session(second).await.unwrap();
    // One real tool so `Tools (N)` has something to count; the empty-sentinel
    // fallback would otherwise mask a broken banner.
    harness
        .set_tools(
            vec![rpi_harness::types::HarnessTool::new(Arc::new(
                BannerProbeTool::new("probe-tool"),
            ))],
            None,
        )
        .await
        .unwrap();
    harness
        .set_resources(rpi_harness::types::AgentHarnessResources {
            skills: Some(vec![rpi_harness::types::Skill {
                name: "demo-skill".into(),
                description: "a skill the banner must advertise".into(),
                content: String::new(),
                file_path: "/skills/demo-skill/SKILL.md".into(),
                disable_model_invocation: None,
            }]),
            ..Default::default()
        })
        .await
        .unwrap();
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    let state = state_with_root(&root);
    let context = rpi_extensions::ToolCallContext::new(cwd.to_string_lossy());

    assert!(
        switch_to_session(
            &harness,
            &lane,
            &first_id,
            cwd,
            &state.chat_container,
            &state,
            &context,
            &empty_catalog()
        )
        .await
    );

    let banner = strip_ansi(&state.chat_container.render(160).join("\n"));
    assert!(
        banner.contains("Skills (1)"),
        "the banner must count the session's skill: {banner}"
    );
    assert!(
        banner.contains("demo-skill"),
        "the banner must name the session's skill: {banner}"
    );
    // Reverse assertion: the empty-capability rendering must be gone. Without
    // it, a partially-empty implementation could still pass on unrelated text.
    assert!(
        !banner.contains("Skills (0)"),
        "the banner must not fall back to the empty capability state: {banner}"
    );
    assert!(
        !banner.contains("Tools (0) none"),
        "the banner must not report zero tools: {banner}"
    );
    assert!(
        banner.contains("Tools (1)") && banner.contains("probe-tool"),
        "the banner must count the session's tools: {banner}"
    );
}

/// `/new` must start a NEW session file, not keep appending to the old one, and
/// must reset the per-session footer counters while keeping the environment.
#[tokio::test]
async fn new_session_creates_a_file_and_resets_footer() {
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path();
    let root = cwd.join("sessions");
    std::fs::create_dir_all(&root).unwrap();
    let source = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let previous_id = source.storage().metadata().id.clone();
    source
        .append_message(user_message_with_images(
            "history that stays behind",
            vec![],
        ))
        .await
        .unwrap();

    let harness = AgentHarness::create(Default::default()).await.unwrap();
    harness.set_session(source).await.unwrap();
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    let state = state_with_root(&root);
    let context = rpi_extensions::ToolCallContext::new(cwd.to_string_lossy());

    // Simulate a session that already accumulated usage before `/new`.
    state.footer.set_model("(prov) model");
    state.footer.set_context_window(200_000);
    state.footer.set_session_name(Some("old session"));
    state.footer.add_usage(12_000, 3_400, 40_000, 1_200, 0.421);
    state.footer.set_context_tokens(Some(126_400));

    assert!(
        start_new_session(
            &harness,
            &lane,
            cwd,
            &state.chat_container,
            &state,
            &context
        )
        .await
    );

    // (a) the harness serves a different session
    let new_id = harness.session().storage().metadata().id.clone();
    assert_ne!(new_id, previous_id, "`/new` must swap the session id");
    assert_eq!(
        std::env::var(rpi_plugin_sdk::SESSION_ID_ENV).unwrap_or_default(),
        new_id,
        "the plugin env channel must follow the swap"
    );
    assert_eq!(
        context.session_id().as_deref(),
        Some(new_id.as_str()),
        "the plugin tool context must follow the swap"
    );

    // (b) the new session file really exists under the session root. The JSONL
    // repo nests files under a cwd-derived directory, so walk the tree instead
    // of assuming a flat layout.
    let files = jsonl_files_under(&root);
    assert!(
        files.iter().any(|path| path.contains(&new_id)),
        "new session file missing under {}: {files:?}",
        root.display()
    );
    assert_eq!(
        files.iter().filter(|path| path.contains(&new_id)).count(),
        1,
        "exactly one file may back the new session: {files:?}"
    );
    // The previous session is preserved, not deleted: `/new` must not destroy
    // user data.
    assert!(
        files.iter().any(|path| path.contains(&previous_id)),
        "the previous session file must survive: {files:?}"
    );

    // (c) the footer's session-scoped numbers are gone, the environment stays.
    let stats = strip_ansi(&state.footer.render(120).join("\n"));
    assert!(!stats.contains("↑12k"), "usage must reset: {stats}");
    assert!(!stats.contains("$0.421"), "cost must reset: {stats}");
    assert!(!stats.contains("old session"), "name must reset: {stats}");
    assert!(
        !stats.contains("63.2%"),
        "context badge must reset: {stats}"
    );
    assert!(stats.contains("(prov) model"), "model kept: {stats}");
    assert!(stats.contains("200k"), "window kept: {stats}");

    // The transcript is the new (empty) session, not the old history.
    let banner = strip_ansi(&state.chat_container.render(160).join("\n"));
    assert!(
        !banner.contains("history that stays behind"),
        "the old transcript must not follow into the new session: {banner}"
    );
    assert!(
        banner.contains(&format!("Started new session {new_id}.")),
        "the note must name the new session: {banner}"
    );
}

/// Every `.jsonl` file under `root`, at any depth.
fn jsonl_files_under(root: &std::path::Path) -> Vec<String> {
    let mut found = Vec::new();
    let mut pending = vec![root.to_path_buf()];
    while let Some(dir) = pending.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                pending.push(path);
            } else if path.extension().is_some_and(|ext| ext == "jsonl") {
                found.push(path.to_string_lossy().into_owned());
            }
        }
    }
    found
}

/// A fresh in-memory session identical in shape to the one `--no-session`
/// builds (`session.rs`'s `ephemeral_session`), so the regression below
/// exercises the real persistence policy, not a hand-picked double.
fn ephemeral_harness_session() -> rpi_harness::session::Session {
    let storage = rpi_harness::session::memory::InMemorySessionStorage::new(
        rpi_harness::session::types::SessionMetadata {
            id: "ephemeral".into(),
            created_at: 0,
            parent_session_id: None,
        },
        Arc::new(rpi_harness::session::memory::SystemClock),
        Arc::new(rpi_harness::session::session::DefaultIdGenerator::new()),
    );
    rpi_harness::session::Session::new(Arc::new(storage), None)
}

// Local review probes for PR #98 (session-boundary regressions), kept as
// regression tests. They drive the real `start_new_session` swap path with
// the same in-memory storage `--no-session` installs; no network, real
// filesystem confined to a tempdir.

#[tokio::test]
async fn review_pr98_new_keeps_an_ephemeral_session_off_disk() {
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path();
    let root = cwd.join("sessions");
    let harness = AgentHarness::create(Default::default()).await.unwrap();
    harness
        .set_session(ephemeral_harness_session())
        .await
        .unwrap();
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    let state = state_with_root(&root);
    let context = rpi_extensions::ToolCallContext::new(cwd.to_string_lossy());
    assert!(!root.exists());
    assert!(
        start_new_session(
            &harness,
            &lane,
            cwd,
            &state.chat_container,
            &state,
            &context
        )
        .await
    );
    lane.append_message(user_message_with_images(
        "review-only ephemeral message",
        vec![],
    ))
    .await
    .unwrap();
    let files = jsonl_files_under(cwd);
    assert!(
        files.is_empty(),
        "--no-session must remain in memory after /new; persisted files: {files:?}"
    );
}

#[tokio::test]
async fn review_pr98_new_must_not_switch_under_an_unscoped_user_bash_run() {
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path();
    let root = cwd.join("sessions");
    let source = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let previous_id = source.storage().metadata().id.clone();
    let harness = AgentHarness::create(Default::default()).await.unwrap();
    harness.set_session(source).await.unwrap();
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    let state = state_with_root(&root);
    let context = rpi_extensions::ToolCallContext::new(cwd.to_string_lossy());
    let cancellation = state.begin_user_bash();
    assert!(*state.status.lock().unwrap() == RunStatus::Idle);
    let switched = start_new_session(
        &harness,
        &lane,
        cwd,
        &state.chat_container,
        &state,
        &context,
    )
    .await;
    // UserBashFinished has no originating-session field and appends through
    // this same live lane. It must not straddle a session swap uncoordinated.
    assert!(
        !switched
            || cancellation.is_cancelled()
            || harness.session().storage().metadata().id == previous_id,
        "/new switched while the previous session's unscoped !command remained active"
    );
}

// --- Session C (P4 + P5): model replay + footer usage restoration ----------

/// An assistant turn with the given provider/model and usage, shaped like the
/// entries a real session records (stop `Stop`, usage filled in).
fn recorded_assistant_turn(
    provider: &str,
    model: &str,
    usage: rpi_ai::types::Usage,
) -> AgentMessage {
    let mut a = rpi_ai::AssistantMessage::empty(
        rpi_ai::Api::Faux,
        provider,
        model,
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or_default(),
    );
    a.stop_reason = rpi_ai::StopReason::Stop;
    a.usage = usage;
    AgentMessage::Assistant(Box::new(a))
}

/// Switching back to a session must put the lane on THAT session's model: the
/// session log (its `ModelChange`/assistant entries) is the authority, not
/// whatever `/model` last picked in the session the user is leaving.
#[tokio::test]
async fn switching_back_to_a_session_restores_its_model() {
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path();
    let root = cwd.join("sessions");
    std::fs::create_dir_all(&root).unwrap();
    let first = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let first_id = first.storage().metadata().id.clone();
    // The first session's assistant turn names the model it ran on.
    first
        .append_message(recorded_assistant_turn(
            "faux",
            "second-model",
            rpi_ai::types::Usage::zero(),
        ))
        .await
        .unwrap();
    let second = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let second_id = second.storage().metadata().id.clone();
    assert_ne!(first_id, second_id);

    let harness = AgentHarness::create(Default::default()).await.unwrap();
    harness.set_session(second).await.unwrap();
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    // The user's last `/model` pick (in the session being left) was `first`.
    lane.set_model(rpi_ai::Model::new(
        "first-model",
        "first",
        rpi_ai::Api::Faux,
        "faux",
        "http://x",
    ))
    .await
    .unwrap();

    let state = state_with_root(&root);
    let context = rpi_extensions::ToolCallContext::new(cwd.to_string_lossy());
    // The authenticated catalog carries the session's recorded model.
    let catalog: Arc<std::sync::RwLock<Vec<rpi_ai::Model>>> =
        Arc::new(std::sync::RwLock::new(vec![
            rpi_ai::Model::new(
                "first-model",
                "first",
                rpi_ai::Api::Faux,
                "faux",
                "http://x",
            ),
            rpi_ai::Model::new(
                "second-model",
                "second",
                rpi_ai::Api::Faux,
                "faux",
                "http://x",
            ),
        ]));

    assert!(
        switch_to_session(
            &harness,
            &lane,
            &first_id,
            cwd,
            &state.chat_container,
            &state,
            &context,
            &catalog
        )
        .await
    );

    let model = lane.get_model().await.unwrap();
    assert_eq!(
        model.id, "second-model",
        "the lane must run the resumed session's own model"
    );
    let footer = strip_ansi(&state.footer.render(120).join("\n"));
    assert!(
        footer.contains("(faux) second-model"),
        "the footer must show the resumed session's model: {footer}"
    );
}

/// Switching back to a session must restore THAT session's usage totals,
/// cache-hit rate and context badge — neither blank nor the previous
/// session's numbers.
#[tokio::test]
async fn switching_back_to_a_session_restores_its_footer_usage() {
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path();
    let root = cwd.join("sessions");
    std::fs::create_dir_all(&root).unwrap();
    let first = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let first_id = first.storage().metadata().id.clone();
    // Two recorded turns: 12k in / 3.4k out with heavy cache reads, then a
    // turn establishing the final context size.
    first
        .append_message(user_message_with_images("history prompt", vec![]))
        .await
        .unwrap();
    first
        .append_message(recorded_assistant_turn(
            "faux",
            "m",
            rpi_ai::types::Usage {
                input: 12_000,
                output: 3_400,
                cache_read: 40_000,
                cache_write: 1_200,
                ..rpi_ai::types::Usage::zero()
            },
        ))
        .await
        .unwrap();
    first
        .append_message(recorded_assistant_turn(
            "faux",
            "m",
            rpi_ai::types::Usage {
                input: 6_000,
                output: 1_000,
                cache_read: 20_000,
                cache_write: 0,
                total_tokens: 126_400,
                ..rpi_ai::types::Usage::zero()
            },
        ))
        .await
        .unwrap();
    let second = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let second_id = second.storage().metadata().id.clone();
    assert_ne!(first_id, second_id);

    let harness = AgentHarness::create(Default::default()).await.unwrap();
    harness.set_session(second).await.unwrap();
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    // The session being left had accumulated DIFFERENT live counters.
    let state = state_with_root(&root);
    state.footer.set_context_window(200_000);
    state.footer.add_usage(111_111, 22_222, 0, 0, 9.999);

    assert!(
        switch_to_session(
            &harness,
            &lane,
            &first_id,
            cwd,
            &state.chat_container,
            &state,
            &rpi_extensions::ToolCallContext::new(cwd.to_string_lossy()),
            &empty_catalog()
        )
        .await
    );

    let stats = strip_ansi(&state.footer.render(120).join("\n"));
    // The first session's restored totals (12k + 6k in, 3.4k + 1k out), not
    // the numbers the previous session left behind…
    assert!(stats.contains("↑18k"), "input totals restored: {stats}");
    assert!(stats.contains("↓4.4k"), "output totals restored: {stats}");
    assert!(
        !stats.contains("↑111k"),
        "stale totals must be gone: {stats}"
    );
    // …and its latest turn's cache-hit share (20k read / 26k billed), under
    // the same latest-turn semantics as the live `MessageEnd` handler.
    assert!(stats.contains("76.9%"), "cache hit rate restored: {stats}");
    // The last recorded context size, against the live window.
    assert!(stats.contains("63.2%"), "context badge restored: {stats}");
}

/// The replay is best-effort by contract: a session whose recorded model is no
/// longer in the authenticated catalog must still open, leaving the current
/// lane model untouched instead of failing the switch.
#[tokio::test]
async fn unknown_session_model_leaves_the_current_model_in_place() {
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path();
    let root = cwd.join("sessions");
    std::fs::create_dir_all(&root).unwrap();
    let first = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let first_id = first.storage().metadata().id.clone();
    // The session was last driven by a model that has since disappeared from
    // the catalog.
    first
        .append_message(recorded_assistant_turn(
            "faux",
            "retired-model",
            rpi_ai::types::Usage::zero(),
        ))
        .await
        .unwrap();
    let second = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let second_id = second.storage().metadata().id.clone();
    assert_ne!(first_id, second_id);

    let harness = AgentHarness::create(Default::default()).await.unwrap();
    harness.set_session(second).await.unwrap();
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    let before = lane.get_model().await.unwrap();

    let state = state_with_root(&root);
    // Catalog carries only an unrelated model.
    let catalog: Arc<std::sync::RwLock<Vec<rpi_ai::Model>>> =
        Arc::new(std::sync::RwLock::new(vec![rpi_ai::Model::new(
            "first-model",
            "first",
            rpi_ai::Api::Faux,
            "faux",
            "http://x",
        )]));

    assert!(
        switch_to_session(
            &harness,
            &lane,
            &first_id,
            cwd,
            &state.chat_container,
            &state,
            &rpi_extensions::ToolCallContext::new(cwd.to_string_lossy()),
            &catalog
        )
        .await,
        "switching must succeed even when the recorded model is unavailable"
    );
    let after = lane.get_model().await.unwrap();
    assert_eq!(after.id, before.id, "the lane model must stay untouched");
    assert_eq!(
        harness.session().storage().metadata().id,
        first_id,
        "the switch itself must have completed"
    );
}

fn pr104_review_model(id: &str) -> rpi_ai::Model {
    rpi_ai::Model::new(id, id, rpi_ai::Api::Faux, "faux", "http://x")
}

#[tokio::test]
async fn review_pr104_replay_preserves_the_live_cache_hit_rate() {
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path();
    let root = cwd.join("sessions");
    let source = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let source_id = source.storage().metadata().id.clone();
    let messages = [
        recorded_assistant_turn(
            "faux",
            "m",
            rpi_ai::types::Usage {
                input: 100,
                output: 1,
                cache_read: 900,
                ..rpi_ai::types::Usage::zero()
            },
        ),
        recorded_assistant_turn(
            "faux",
            "m",
            rpi_ai::types::Usage {
                input: 900,
                output: 1,
                cache_read: 100,
                ..rpi_ai::types::Usage::zero()
            },
        ),
    ];
    for message in &messages {
        source.append_message(message.clone()).await.unwrap();
    }
    let target = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let harness = AgentHarness::create(Default::default()).await.unwrap();
    harness.set_session(target).await.unwrap();
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    let state = state_with_root(&root);
    let tui = Arc::new(TuiAltScreen::new(
        Box::new(ProcessTerminal::new()),
        true,
        None,
    ));
    // Run the actual live MessageEnd handler; the latest turn is a 10% hit.
    for message in messages {
        handle_agent_event(
            AgentEvent::MessageEnd { message },
            &tui,
            &state,
            &state.chat_container,
            &lane,
        )
        .await;
    }
    let before = strip_ansi(&state.footer.render(120).join("\n"));
    assert!(before.contains("CH10.0%"), "live hit rate: {before}");
    assert!(
        switch_to_session(
            &harness,
            &lane,
            &source_id,
            cwd,
            &state.chat_container,
            &state,
            &rpi_extensions::ToolCallContext::new(cwd.to_string_lossy()),
            &empty_catalog(),
        )
        .await
    );
    let after = strip_ansi(&state.footer.render(120).join("\n"));
    assert!(
        after.contains("CH10.0%"),
        "restoring the same two turns must preserve the live rate, not average all turns: {after}"
    );
}

#[tokio::test]
async fn review_pr104_restore_model_must_follow_the_selected_branch() {
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path();
    let root = cwd.join("sessions");
    let source = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let source_id = source.storage().metadata().id.clone();
    let selected = source
        .append_message(recorded_assistant_turn(
            "faux",
            "selected",
            rpi_ai::types::Usage::zero(),
        ))
        .await
        .unwrap();
    source
        .append_message(recorded_assistant_turn(
            "faux",
            "abandoned",
            rpi_ai::types::Usage::zero(),
        ))
        .await
        .unwrap();
    // This is the move made by /tree before leaving/reopening the session.
    source.move_lane("main", Some(&selected)).await.unwrap();
    let target = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let harness = AgentHarness::create(Default::default()).await.unwrap();
    harness.set_session(target).await.unwrap();
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    lane.set_model(pr104_review_model("selected"))
        .await
        .unwrap();
    let state = state_with_root(&root);
    let catalog = Arc::new(std::sync::RwLock::new(vec![
        pr104_review_model("selected"),
        pr104_review_model("abandoned"),
    ]));
    assert!(
        switch_to_session(
            &harness,
            &lane,
            &source_id,
            cwd,
            &state.chat_container,
            &state,
            &rpi_extensions::ToolCallContext::new(cwd.to_string_lossy()),
            &catalog,
        )
        .await
    );
    assert_eq!(
        lane.get_tip_id().await.unwrap().as_deref(),
        Some(selected.as_str())
    );
    assert_eq!(
        lane.get_model().await.unwrap().id,
        "selected",
        "a later entry outside the selected branch must not select the model"
    );
}

#[tokio::test]
async fn review_pr104_restore_model_must_ignore_a_child_lane() {
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path();
    let root = cwd.join("sessions");
    let source = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let source_id = source.storage().metadata().id.clone();
    let parent = source
        .append_message(recorded_assistant_turn(
            "faux",
            "parent-model",
            rpi_ai::types::Usage::zero(),
        ))
        .await
        .unwrap();
    source
        .create_lane("child-review", Some(&parent))
        .await
        .unwrap();
    source
        .view("child-review")
        .append_message(recorded_assistant_turn(
            "faux",
            "child-model",
            rpi_ai::types::Usage::zero(),
        ))
        .await
        .unwrap();
    let target = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let harness = AgentHarness::create(Default::default()).await.unwrap();
    harness.set_session(target).await.unwrap();
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    lane.set_model(pr104_review_model("parent-model"))
        .await
        .unwrap();
    let state = state_with_root(&root);
    let catalog = Arc::new(std::sync::RwLock::new(vec![
        pr104_review_model("parent-model"),
        pr104_review_model("child-model"),
    ]));
    assert!(
        switch_to_session(
            &harness,
            &lane,
            &source_id,
            cwd,
            &state.chat_container,
            &state,
            &rpi_extensions::ToolCallContext::new(cwd.to_string_lossy()),
            &catalog,
        )
        .await
    );
    assert_eq!(
        lane.get_model().await.unwrap().id,
        "parent-model",
        "a child lane's later assistant turn must not replace the parent's model"
    );
}

#[tokio::test]
async fn review_pr104_fork_preserves_a_model_pick_before_the_next_turn() {
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path();
    let root = cwd.join("sessions");
    let source = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    source
        .append_message(recorded_assistant_turn(
            "faux",
            "old-model",
            rpi_ai::types::Usage::zero(),
        ))
        .await
        .unwrap();
    let previous_id = source.storage().metadata().id.clone();
    let harness = AgentHarness::create(Default::default()).await.unwrap();
    harness.set_session(source).await.unwrap();
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    let state = state_with_root(&root);
    // The real /model path does not persist settings or a ModelChange entry.
    apply_model_selection(&lane, &state, pr104_review_model("new-model"), false)
        .await
        .unwrap();
    fork_session(
        &harness,
        cwd,
        &state.chat_container,
        &state,
        &rpi_extensions::ToolCallContext::new(cwd.to_string_lossy()),
    )
    .await;
    assert_ne!(harness.session().storage().metadata().id, previous_id);
    assert_eq!(
        lane.get_model().await.unwrap().id,
        "new-model",
        "/fork must not undo a successful /model selection made before the next assistant turn"
    );
}

fn review_084_context_turn(model: &str, tokens: i64) -> AgentMessage {
    recorded_assistant_turn(
        "faux",
        model,
        rpi_ai::types::Usage {
            input: tokens,
            output: 1,
            total_tokens: tokens,
            ..rpi_ai::types::Usage::zero()
        },
    )
}

#[tokio::test]
async fn rereview_pr104_context_must_not_come_from_a_child_lane() {
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path();
    let root = cwd.join("sessions");
    let source = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let source_id = source.storage().metadata().id.clone();
    let main_tip = source
        .append_message(review_084_context_turn("parent-model", 50_000))
        .await
        .unwrap();
    source
        .create_lane("child-context", Some(&main_tip))
        .await
        .unwrap();
    source
        .view("child-context")
        .append_message(review_084_context_turn("child-model", 190_000))
        .await
        .unwrap();
    let target = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let harness = AgentHarness::create(Default::default()).await.unwrap();
    harness.set_session(target).await.unwrap();
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    let state = state_with_root(&root);
    let mut parent_model = pr104_review_model("parent-model");
    parent_model.context_window = 200_000;
    let catalog = Arc::new(std::sync::RwLock::new(vec![parent_model]));
    assert!(
        switch_to_session(
            &harness,
            &lane,
            &source_id,
            cwd,
            &state.chat_container,
            &state,
            &rpi_extensions::ToolCallContext::new(cwd.to_string_lossy()),
            &catalog,
        )
        .await
    );
    // The previous model fix works, but usage replay still queries all lanes.
    assert_eq!(lane.get_model().await.unwrap().id, "parent-model");
    let footer = strip_ansi(&state.footer.render(160).join("\n"));
    assert!(
        footer.contains("25.0%/200k"),
        "the main context is 50k/200k, not the child's 190k/200k: {footer}"
    );
}

#[tokio::test]
async fn rereview_pr104_compaction_must_invalidate_pre_compaction_context() {
    use rpi_harness::session::types::{ProvisionedEntry, ProvisionedKind};
    let temporary = tempfile::tempdir().unwrap();
    let cwd = temporary.path();
    let root = cwd.join("sessions");
    let source = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let source_id = source.storage().metadata().id.clone();
    source
        .append_message(review_084_context_turn("model", 100_000))
        .await
        .unwrap();
    // Seed the durable state after a successful /compact, without a model call.
    // run_compact() explicitly clears the live context badge for this state.
    source
        .append_entry(
            ProvisionedEntry {
                id: "review-context-compaction".into(),
                kind: ProvisionedKind::Compaction {
                    summary: "Small replacement summary".into(),
                    retained_tail: vec![],
                    tokens_before: 100_000,
                    details: None,
                    usage: None,
                },
            },
            "main",
        )
        .await
        .unwrap();
    let target = crate::session::create_jsonl_session(&root, &cwd.to_string_lossy())
        .await
        .unwrap();
    let harness = AgentHarness::create(Default::default()).await.unwrap();
    harness.set_session(target).await.unwrap();
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    let state = state_with_root(&root);
    let mut model = pr104_review_model("model");
    model.context_window = 200_000;
    let catalog = Arc::new(std::sync::RwLock::new(vec![model]));
    assert!(
        switch_to_session(
            &harness,
            &lane,
            &source_id,
            cwd,
            &state.chat_container,
            &state,
            &rpi_extensions::ToolCallContext::new(cwd.to_string_lossy()),
            &catalog,
        )
        .await
    );
    let footer = strip_ansi(&state.footer.render(160).join("\n"));
    assert!(
        footer.split_whitespace().any(|part| part == "0.0%/200k"),
        "after compaction there is no new context report; old 50% must not reappear: {footer}"
    );
}

/// A tool that exists only to give the banner something to count.
struct BannerProbeTool {
    schema: rpi_ai::types::Tool,
}

impl BannerProbeTool {
    fn new(name: &str) -> Self {
        Self {
            schema: rpi_ai::types::Tool {
                name: name.to_string(),
                description: "probe tool".into(),
                parameters: rpi_ai::types::Schema::new(serde_json::json!({
                    "type": "object",
                    "properties": {},
                })),
                constrained_sampling: None,
            },
        }
    }
}

#[async_trait::async_trait]
impl rpi_agent::AgentTool for BannerProbeTool {
    fn schema(&self) -> &rpi_ai::types::Tool {
        &self.schema
    }
    fn label(&self) -> &str {
        &self.schema.name
    }
    fn execution_mode(&self) -> rpi_agent::types::ToolExecutionMode {
        rpi_agent::types::ToolExecutionMode::Parallel
    }
    async fn execute(
        &self,
        _tool_call_id: &str,
        _params: serde_json::Value,
        _signal: tokio_util::sync::CancellationToken,
        _on_update: Arc<dyn Fn(rpi_agent::types::ToolResultPartial) + Send + Sync>,
    ) -> Result<rpi_agent::types::AgentToolResult, rpi_agent::AgentError> {
        Ok(rpi_agent::types::AgentToolResult::text("probe"))
    }
}