use std::fs;
use pretty_assertions::assert_eq;
use rho_sdk::model::Message;
use rho_tools::WorkspaceMutationObserver as _;
use super::{RewindError, RewindPreview, RewoundConversation};
use crate::{
app::session_runtime::{test_support::idle_runtime, SessionRuntime},
config::Config,
permission::PermissionMode,
session::{
tree::NodeId,
workspace_checkpoint::{CheckpointOutcome, RestoreClassification},
},
};
fn leaf(runtime: &SessionRuntime) -> NodeId {
let stored = runtime.storage.file().expect("the session is saved");
stored
.active_checkpoint_target()
.unwrap()
.expect("the session saved a node")
.0
}
fn add(runtime: &mut SessionRuntime, text: &str) -> NodeId {
runtime
.append_context(
text.into(),
Message::user_text(text),
None,
[],
)
.unwrap();
leaf(runtime)
}
fn planned(preview: RewindPreview) -> (Vec<RestoreClassification>, Option<NodeId>) {
(
preview
.plan
.entries
.iter()
.map(|entry| entry.classification)
.collect(),
preview.returns_to,
)
}
#[tokio::test]
async fn a_rewind_puts_the_turns_files_and_conversation_back() {
let home = tempfile::tempdir().unwrap();
let config = Config {
provider: "test".into(),
model: "model".into(),
..Config::default()
};
let mut runtime = idle_runtime(home.path(), &config).await;
runtime.built.tools.take_checkpoints_for_tests();
let workspace = fs::canonicalize(home.path()).unwrap();
let (added, deleted, modified) = (
workspace.join("added.txt"),
workspace.join("deleted.txt"),
workspace.join("modified.txt"),
);
fs::write(&deleted, "deleted original").unwrap();
fs::write(&modified, "modified original").unwrap();
let before = add(&mut runtime, "before");
let begun = runtime.begin_workspace_checkpoint().unwrap();
let tracker = runtime.built.tools.checkpoint_tracker().clone();
let paths = [added.as_path(), deleted.as_path(), modified.as_path()];
tracker.before_mutation(&paths).await.unwrap();
fs::write(&added, "agent added").unwrap();
fs::remove_file(&deleted).unwrap();
fs::write(&modified, "agent modified").unwrap();
tracker.after_mutation(&paths).await.unwrap();
let turn = add(&mut runtime, "the turn");
let told = runtime.finalize_workspace_checkpoint(CheckpointOutcome::Completed);
let previewed = runtime.preview_rewind(&turn).unwrap();
let promised = (previewed.returns_to.clone(), previewed.turns.clone());
let preview = planned(previewed);
let rewind = runtime
.rewind_workspace(&turn, None, &config)
.await
.unwrap();
let read = |path: &std::path::Path| fs::read_to_string(path).ok();
let RewoundConversation::Moved { row } = &rewind.conversation else {
panic!("the conversation stayed: {:?}", rewind.conversation);
};
assert_eq!((Some(row.clone()), rewind.turns.clone()), promised);
assert_eq!(
(
(begun, told),
preview,
(read(&added), read(&deleted), read(&modified)),
leaf(&runtime),
),
(
(None, Vec::new()),
(
vec![
RestoreClassification::Delete,
RestoreClassification::Create,
RestoreClassification::Modify
],
Some(before.clone())
),
(
None,
Some("deleted original".to_owned()),
Some("modified original".to_owned())
),
before,
),
"audit: {:?}",
rewind.audit
);
runtime.shutdown().await;
}
#[tokio::test]
async fn a_rewind_that_cannot_restore_every_file_keeps_the_conversation() {
let home = tempfile::tempdir().unwrap();
let config = Config {
provider: "test".into(),
model: "model".into(),
..Config::default()
};
let mut runtime = idle_runtime(home.path(), &config).await;
runtime.built.tools.take_checkpoints_for_tests();
let file = fs::canonicalize(home.path()).unwrap().join("file.txt");
fs::write(&file, "original").unwrap();
add(&mut runtime, "before");
runtime.begin_workspace_checkpoint().unwrap();
let tracker = runtime.built.tools.checkpoint_tracker().clone();
tracker.before_mutation(&[file.as_path()]).await.unwrap();
fs::write(&file, "the turn's").unwrap();
tracker.after_mutation(&[file.as_path()]).await.unwrap();
let turn = add(&mut runtime, "the turn");
runtime.finalize_workspace_checkpoint(CheckpointOutcome::Completed);
let mode = std::mem::replace(&mut runtime.permission.mode, PermissionMode::Plan);
let planning = runtime.rewind_workspace(&turn, None, &config).await;
let previewed_planning = runtime.preview_rewind(&turn);
let after_refusal = fs::read_to_string(&file).unwrap();
runtime.permission.mode = mode;
fs::write(&file, "a later edit").unwrap();
let preview = planned(runtime.preview_rewind(&turn).unwrap());
let conflicted = runtime
.rewind_workspace(&turn, None, &config)
.await
.unwrap();
assert!(
matches!(
(&planning, &previewed_planning),
(Err(RewindError::Refused(_)), Err(RewindError::Refused(_)))
),
"{planning:?} {previewed_planning:?}"
);
assert_eq!(preview, (vec![RestoreClassification::Conflict], None));
let RewoundConversation::Stayed = conflicted.conversation else {
panic!("the conversation moved: {:?}", conflicted.conversation);
};
assert_eq!(
(
after_refusal.as_str(),
fs::read_to_string(&file).unwrap().as_str(),
leaf(&runtime)
),
("the turn's", "a later edit", turn),
"audit: {:?}",
conflicted.audit
);
runtime.shutdown().await;
}
#[tokio::test]
async fn a_rewind_undoes_every_later_turn_and_refuses_another_branch() {
let home = tempfile::tempdir().unwrap();
let config = Config {
provider: "test".into(),
model: "model".into(),
..Config::default()
};
let mut runtime = idle_runtime(home.path(), &config).await;
runtime.built.tools.take_checkpoints_for_tests();
let workspace = fs::canonicalize(home.path()).unwrap();
let (edited, created) = (workspace.join("edited.txt"), workspace.join("created.txt"));
fs::write(&edited, "original").unwrap();
let before = add(&mut runtime, "before");
let turn =
async |runtime: &mut SessionRuntime, prompt: &str, write: &[(&std::path::Path, &str)]| {
runtime.begin_workspace_checkpoint().unwrap();
let tracker = runtime.built.tools.checkpoint_tracker().clone();
let paths = write.iter().map(|(path, _)| *path).collect::<Vec<_>>();
tracker.before_mutation(&paths).await.unwrap();
for (path, text) in write {
fs::write(path, text).unwrap();
}
tracker.after_mutation(&paths).await.unwrap();
let node = add(runtime, prompt);
runtime.finalize_workspace_checkpoint(CheckpointOutcome::Completed);
node
};
let first = turn(&mut runtime, "first", &[(&edited, "first")]).await;
let second = turn(
&mut runtime,
"second",
&[(&edited, "second"), (&created, "new")],
)
.await;
let preview = runtime.preview_rewind(&first).unwrap();
let turns = preview.turns.clone();
let rewind = runtime
.rewind_workspace(&first, None, &config)
.await
.unwrap();
let after_rewind = (
fs::read_to_string(&edited).ok(),
fs::read_to_string(&created).ok(),
leaf(&runtime),
);
fs::write(&edited, "a later edit").unwrap();
let off_branch = runtime
.rewind_workspace(&second, None, &config)
.await;
let RewoundConversation::Moved { .. } = rewind.conversation else {
panic!("the conversation stayed: {:?}", rewind.conversation);
};
assert!(
matches!(off_branch, Err(RewindError::Refused(_))),
"{off_branch:?}"
);
assert_eq!(
(
turns,
planned(preview),
after_rewind,
fs::read_to_string(&edited).ok()
),
(
vec![first, second],
(
vec![RestoreClassification::Delete, RestoreClassification::Modify],
Some(before.clone())
),
(Some("original".to_owned()), None, before),
Some("a later edit".to_owned()),
),
"audit: {:?}",
rewind.audit
);
runtime.shutdown().await;
}
#[tokio::test]
async fn a_rewind_counts_the_later_turns_that_took_no_checkpoint() {
let home = tempfile::tempdir().unwrap();
let config = Config {
provider: "test".into(),
model: "model".into(),
..Config::default()
};
let mut runtime = idle_runtime(home.path(), &config).await;
runtime.built.tools.take_checkpoints_for_tests();
add(&mut runtime, "before");
let end = |runtime: &mut SessionRuntime| {
let checkpoint = runtime.install_continuation_checkpoint().unwrap();
runtime.persist_failed_turn(&checkpoint);
runtime.built.session.set_checkpoint_store(None).unwrap();
};
runtime.begin_workspace_checkpoint().unwrap();
add(&mut runtime, "first");
end(&mut runtime);
let first = leaf(&runtime);
runtime.finalize_workspace_checkpoint(CheckpointOutcome::Completed);
runtime.begin_workspace_checkpoint().unwrap();
add(&mut runtime, "second");
end(&mut runtime);
runtime.finalize_workspace_checkpoint(CheckpointOutcome::Completed);
add(&mut runtime, "third");
end(&mut runtime);
let preview = runtime.preview_rewind(&first).unwrap();
assert_eq!((preview.turns.len(), preview.plan.uncaptured_turns), (2, 1));
runtime.shutdown().await;
}
#[tokio::test]
async fn a_rewind_held_to_its_previewed_tip_refuses_once_the_conversation_moved() {
let home = tempfile::tempdir().unwrap();
let config = Config {
provider: "test".into(),
model: "model".into(),
..Config::default()
};
let mut runtime = idle_runtime(home.path(), &config).await;
runtime.built.tools.take_checkpoints_for_tests();
let file = fs::canonicalize(home.path()).unwrap().join("file.txt");
fs::write(&file, "original").unwrap();
add(&mut runtime, "before");
let turn = |runtime: &mut SessionRuntime, prompt: &str| {
runtime.begin_workspace_checkpoint().unwrap();
let node = add(runtime, prompt);
runtime.finalize_workspace_checkpoint(CheckpointOutcome::Completed);
node
};
let first = turn(&mut runtime, "first");
let previewed = runtime.preview_rewind(&first).unwrap().tip;
runtime.begin_workspace_checkpoint().unwrap();
let tracker = runtime.built.tools.checkpoint_tracker().clone();
tracker.before_mutation(&[file.as_path()]).await.unwrap();
fs::write(&file, "unseen").unwrap();
tracker.after_mutation(&[file.as_path()]).await.unwrap();
let unseen = add(&mut runtime, "unseen");
runtime.finalize_workspace_checkpoint(CheckpointOutcome::Completed);
let refused = runtime
.rewind_workspace(&first, Some(&previewed), &config)
.await;
let after_refusal = fs::read_to_string(&file).unwrap();
let held = runtime
.rewind_workspace(&first, Some(&unseen), &config)
.await;
let Err(RewindError::Moved { expected, now }) = refused else {
panic!("the rewind was not held: {refused:?}");
};
assert!(held.is_ok(), "{held:?}");
assert_eq!(
(
(expected, now),
after_refusal,
fs::read_to_string(&file).unwrap()
),
(
(previewed, unseen),
"unseen".to_owned(),
"original".to_owned()
)
);
runtime.shutdown().await;
}