rcom/tests/undo_runtime.rs
2026-12-05 23:30:06 +03:00

700 lines
24 KiB
Rust

use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use rcom::actions::{
EntryMutationKind, EntryMutationNode, EntryMutationPlan, TrashRecord, UndoEntry,
};
use rcom::app::{
AppState, Command, Effect, Overlay, PaneId, PaneMode, UndoInverseKind, UndoRecord,
};
use rcom::domain::{Entry, EntryKind, HostAlias, Location, SourceId};
use rcom::fs::{BackendRegistry, FileOperations, FsError, LocalFs, ReadFileSystem};
use rcom::operations::{
CommitOutcome, EntryFingerprint, ItemId, ItemOutcome, ItemPhase, OperationEventKind,
PlanGeneration, PlanId, SourceCleanupOutcome, TaskStatus,
};
use rcom::runtime::EffectRunner;
use rcom::ssh::{ConnectionManager, SshConnector};
use rcom::test_support::MemoryTransferFs;
use tempfile::TempDir;
use tokio::sync::mpsc;
use uuid::Uuid;
struct NoNetwork;
#[async_trait]
impl SshConnector for NoNetwork {
async fn connect(&self, _host: &HostAlias) -> Result<Arc<dyn ReadFileSystem>, FsError> {
panic!("undo runtime tests must remain local")
}
}
#[derive(Clone, Default)]
struct RemoteTree {
transfer: Arc<std::sync::Mutex<Option<Arc<MemoryTransferFs>>>>,
}
impl RemoteTree {
fn fixture(host: &HostAlias, epoch: u64) -> MemoryTransferFs {
let root = Location::ssh(host.clone(), "/work");
MemoryTransferFs::new(SourceId::Ssh(host.clone()), epoch)
.with_file(root.join("plain.txt"), b"plain")
.with_dir(root.join("tree/nested"))
.with_file(root.join("tree/nested/leaf.txt"), b"confirmed leaf")
}
}
#[async_trait]
impl SshConnector for RemoteTree {
async fn connect(&self, host: &HostAlias) -> Result<Arc<dyn ReadFileSystem>, FsError> {
Ok(Arc::new(Self::fixture(host, 0)))
}
async fn connect_with_operations(
&self,
host: &HostAlias,
epoch: u64,
) -> Result<(Arc<dyn ReadFileSystem>, Option<Arc<dyn FileOperations>>), FsError> {
let transfer = Arc::new(Self::fixture(host, epoch));
*self
.transfer
.lock()
.unwrap_or_else(|error| error.into_inner()) = Some(transfer.clone());
Ok((transfer.clone(), Some(transfer)))
}
}
struct Harness {
app: AppState,
runner: EffectRunner,
results: mpsc::Receiver<Command>,
}
impl Harness {
fn new(root: &std::path::Path) -> Self {
let connections = ConnectionManager::new(
Arc::new(NoNetwork),
BackendRegistry::new(Arc::new(LocalFs::new())),
);
Self::with_connections(Location::local(root), connections)
}
fn with_connections(root: Location, connections: ConnectionManager) -> Self {
let (runner, results) = EffectRunner::new(connections);
Self {
app: AppState::new(root),
runner,
results,
}
}
fn dispatch(&mut self, command: Command) -> Vec<Effect> {
let effects = self.app.reduce(command);
for effect in &effects {
self.runner.execute(effect.clone());
}
effects
}
async fn next(&mut self) -> Command {
tokio::time::timeout(Duration::from_secs(5), self.results.recv())
.await
.expect("undo runtime timed out")
.expect("runtime result channel closed")
}
async fn finish_task(&mut self) -> OperationEventKind {
loop {
let command = self.next().await;
let terminal = match &command {
Command::OperationEvent(event)
if matches!(
event.kind,
OperationEventKind::Completed
| OperationEventKind::CancellationAcknowledged
) =>
{
Some(event.kind.clone())
}
_ => None,
};
self.dispatch(command);
if let Some(terminal) = terminal {
return terminal;
}
}
}
async fn prepare_undo(&mut self) {
let effects = self.dispatch(Command::Undo);
assert_eq!(effects.len(), 1, "a non-empty journal starts preparation");
assert!(matches!(effects[0], Effect::PrepareUndo(_)));
loop {
let command = self.next().await;
if let Command::UndoPrepared(result) = command {
assert!(
result.result.is_ok(),
"undo preparation failed: {:?}",
result.result
);
self.dispatch(Command::UndoPrepared(result));
assert_eq!(self.app.overlay, Overlay::Undo);
assert!(self.app.undo.as_ref().unwrap().summary.is_some());
return;
}
self.dispatch(command);
}
}
async fn prepare_undo_error(&mut self) {
self.dispatch(Command::Undo);
loop {
let command = self.next().await;
if let Command::UndoPrepared(result) = command {
assert!(result.result.is_err(), "stale/conflicting undo prepared");
self.dispatch(Command::UndoPrepared(result));
assert!(self.app.undo.as_ref().unwrap().summary.is_none());
assert!(self.app.undo.as_ref().unwrap().notice.is_some());
return;
}
self.dispatch(command);
}
}
async fn confirm_undo(&mut self) -> OperationEventKind {
self.dispatch(Command::ConfirmOperation);
let tasks = self.app.task_manager.len();
assert!(self.dispatch(Command::ConfirmOperation).is_empty());
assert_eq!(
self.app.task_manager.len(),
tasks,
"double confirm started work"
);
self.finish_task().await
}
}
fn input_name(harness: &mut Harness, name: &str) {
while !harness.app.entry_action.as_ref().unwrap().input.is_empty() {
harness.dispatch(Command::EntryBackspace);
}
for character in name.chars() {
harness.dispatch(Command::EntryInput(character));
}
harness.dispatch(Command::SubmitEntry);
assert_eq!(harness.app.overlay, Overlay::ConfirmEntryAction);
}
async fn create_file(harness: &mut Harness, name: &str) {
harness.dispatch(Command::CreateFile);
input_name(harness, name);
harness.dispatch(Command::ConfirmEntryAction);
assert_eq!(harness.finish_task().await, OperationEventKind::Completed);
assert_eq!(harness.app.undo_journal.len(), 1);
}
#[tokio::test]
async fn create_undo_consumes_only_after_full_success_and_double_confirm_is_idempotent() {
let fixture = TempDir::new().unwrap();
let created = fixture.path().join("created.txt");
let mut harness = Harness::new(fixture.path());
create_file(&mut harness, "created.txt").await;
assert!(created.exists());
assert!(matches!(
harness.app.undo_journal.latest(),
Some(UndoEntry::Create { .. })
));
harness.prepare_undo().await;
let summary = harness.app.undo.as_ref().unwrap().summary.as_ref().unwrap();
assert_eq!(summary.inverse_kind, UndoInverseKind::DeleteCreated);
assert_eq!(summary.source, Location::local(&created));
assert_eq!(summary.destination, None);
assert_eq!(harness.confirm_undo().await, OperationEventKind::Completed);
assert!(!created.exists());
assert!(harness.app.undo_journal.is_empty());
let task = harness.app.task_manager.tasks().last().unwrap();
assert_eq!(task.plan().work_kind(), rcom::operations::WorkKind::Undo);
assert_eq!(task.status(), TaskStatus::Succeeded);
assert!(harness.app.reduce(Command::Undo).is_empty());
assert_eq!(harness.app.overlay, Overlay::Undo);
assert!(harness.app.undo.is_none());
}
#[tokio::test]
async fn rename_undo_restores_original_name_and_post_mutation_fingerprint() {
let fixture = TempDir::new().unwrap();
let original = fixture.path().join("old.txt");
let renamed = fixture.path().join("new.txt");
std::fs::write(&original, b"contents").unwrap();
let entry = LocalFs::new()
.metadata(&Location::local(&original))
.await
.unwrap();
let mut harness = Harness::new(fixture.path());
harness.app.active_pane_mut().entries = vec![entry];
harness.app.active_pane_mut().selection.set(Some(0), 1);
harness.dispatch(Command::Rename);
input_name(&mut harness, "new.txt");
harness.dispatch(Command::ConfirmEntryAction);
assert_eq!(harness.finish_task().await, OperationEventKind::Completed);
assert!(matches!(
harness.app.undo_journal.latest(),
Some(UndoEntry::Rename { .. })
));
assert_eq!(std::fs::read(&renamed).unwrap(), b"contents");
harness.prepare_undo().await;
let summary = harness.app.undo.as_ref().unwrap().summary.as_ref().unwrap();
assert_eq!(summary.inverse_kind, UndoInverseKind::RenameBack);
assert_eq!(summary.source, Location::local(&renamed));
assert_eq!(summary.destination, Some(Location::local(&original)));
assert_eq!(harness.confirm_undo().await, OperationEventKind::Completed);
assert_eq!(std::fs::read(&original).unwrap(), b"contents");
assert!(!renamed.exists());
assert!(harness.app.undo_journal.is_empty());
}
#[tokio::test]
async fn trash_undo_restores_each_record_to_its_original_path() {
let fixture = TempDir::new().unwrap();
let work = fixture.path().join("work");
let trash = fixture.path().join("trash");
let original = work.join("trashed.txt");
let id = Uuid::from_u128(42);
let trashed = trash.join("files").join(id.to_string());
std::fs::create_dir_all(&work).unwrap();
std::fs::create_dir_all(trashed.parent().unwrap()).unwrap();
std::fs::write(&original, b"restore me").unwrap();
let fingerprint = EntryFingerprint::from(
&LocalFs::new()
.metadata(&Location::local(&original))
.await
.unwrap(),
);
std::fs::rename(&original, &trashed).unwrap();
let original = Location::local(&original);
let trashed = Location::local(&trashed);
let record = TrashRecord::new(
original.clone(),
trashed.clone(),
fingerprint.clone(),
0,
id,
)
.unwrap();
let plan = EntryMutationPlan::new(
PlanId::new(1),
PlanGeneration::new(1),
EntryMutationKind::Trash,
Location::local(&work),
Some(Location::local(&trash)),
vec![EntryMutationNode::new(
ItemId::new(1),
original.clone(),
"trashed.txt",
Some(fingerprint),
)],
BTreeMap::new(),
)
.unwrap();
let outcome = ItemOutcome::new(
ItemId::new(1),
ItemPhase::Succeeded,
CommitOutcome::Committed,
SourceCleanupOutcome::Removed,
);
let mut harness = Harness::new(&work);
harness.dispatch(Command::RecordUndo(UndoRecord::Trash {
plan,
records: vec![record],
outcomes: vec![outcome],
}));
assert_eq!(harness.app.undo_journal.len(), 1);
harness.prepare_undo().await;
assert_eq!(
harness
.app
.undo
.as_ref()
.unwrap()
.summary
.as_ref()
.unwrap()
.inverse_kind,
UndoInverseKind::RestoreTrash
);
assert_eq!(harness.confirm_undo().await, OperationEventKind::Completed);
assert_eq!(std::fs::read(original.path()).unwrap(), b"restore me");
assert!(!trashed.path().exists());
assert!(harness.app.undo_journal.is_empty());
}
#[tokio::test]
async fn fixed_tree_multi_root_trash_runtime_undo_restores_all_and_rejects_changed_descendant() {
let host = HostAlias::new("edge");
let root = Location::ssh(host.clone(), "/work");
let tree = root.join("tree");
let plain = root.join("plain.txt");
let connector = RemoteTree::default();
let connections = ConnectionManager::new(
Arc::new(connector.clone()),
BackendRegistry::new(Arc::new(LocalFs::new())),
);
let connection = connections.connect(&host).await.unwrap();
let transfer = connector
.transfer
.lock()
.unwrap_or_else(|error| error.into_inner())
.clone()
.unwrap();
let plain_metadata = FileOperations::metadata(transfer.as_ref(), &plain, false)
.await
.unwrap();
let mut harness = Harness::with_connections(root.clone(), connections);
harness.app.active_pane_mut().session_epoch = Some(connection.epoch);
harness.app.active_pane_mut().entries = vec![
Entry::new("plain.txt", EntryKind::File).with_metadata(plain_metadata.size, None, None),
Entry::new("tree", EntryKind::Directory),
];
harness.app.active_pane_mut().selection.set(Some(0), 2);
harness
.app
.active_pane_mut()
.selection_set
.insert(root.entry_id("plain.txt"));
harness
.app
.active_pane_mut()
.selection_set
.insert(root.entry_id("tree"));
harness.dispatch(Command::Trash);
let prepared = loop {
let command = harness.next().await;
if let Command::EntryActionPrepared(result) = command {
let prepared = result.result.as_ref().unwrap();
assert_eq!(prepared.trash_records.len(), 2);
assert_eq!(
prepared
.plan
.nodes()
.iter()
.filter(|node| node.is_root())
.count(),
2
);
assert_eq!(prepared.plan.nodes().len(), 4);
let prepared = result.result.clone().unwrap();
harness.dispatch(Command::EntryActionPrepared(result));
break prepared;
}
harness.dispatch(command);
};
let tree_record = prepared
.trash_records
.iter()
.find(|record| record.original() == &tree)
.unwrap()
.clone();
let plain_record = prepared
.trash_records
.iter()
.find(|record| record.original() == &plain)
.unwrap()
.clone();
assert!(
FileOperations::metadata(transfer.as_ref(), &tree, false)
.await
.is_ok()
);
harness.dispatch(Command::ConfirmEntryAction);
assert_eq!(harness.finish_task().await, OperationEventKind::Completed);
assert_eq!(
transfer.file_contents(&tree.join("nested/leaf.txt")),
Err(FsError::NotFound)
);
assert_eq!(transfer.file_contents(&plain), Err(FsError::NotFound));
assert_eq!(
transfer
.file_contents(&tree_record.trashed().join("nested/leaf.txt"))
.unwrap(),
b"confirmed leaf"
);
let Some(UndoEntry::Trash { plan, records }) = harness.app.undo_journal.latest() else {
panic!("runtime did not record fixed-tree trash")
};
assert_eq!(plan.nodes().len(), 4);
assert_eq!(records.len(), 2);
assert_eq!(harness.app.task_manager.len(), 1);
assert_eq!(
harness
.app
.task_manager
.tasks()
.last()
.unwrap()
.outcomes()
.count(),
2
);
// A changed descendant must stop the whole batch before the other valid root is restored.
transfer.insert_file(
tree_record.trashed().join("nested/leaf.txt"),
b"changed after trash",
);
harness.prepare_undo_error().await;
assert_eq!(transfer.file_contents(&plain), Err(FsError::NotFound));
assert_eq!(
FileOperations::metadata(transfer.as_ref(), &tree, false).await,
Err(FsError::NotFound)
);
assert_eq!(
transfer.file_contents(plain_record.trashed()).unwrap(),
b"plain"
);
assert_eq!(harness.app.undo_journal.len(), 1);
assert_eq!(harness.app.task_manager.len(), 1);
// The in-memory SSH adapter has no mtimes, so restoring the exact bytes also restores the
// confirmed fingerprint. A fresh preparation and confirmation are still mandatory.
transfer.insert_file(
tree_record.trashed().join("nested/leaf.txt"),
b"confirmed leaf",
);
harness.dispatch(Command::CloseOverlay);
harness.prepare_undo().await;
assert_eq!(
harness
.app
.undo
.as_ref()
.unwrap()
.summary
.as_ref()
.unwrap()
.sources
.len(),
2
);
assert_eq!(harness.confirm_undo().await, OperationEventKind::Completed);
assert_eq!(transfer.file_contents(&plain).unwrap(), b"plain");
assert_eq!(
transfer
.file_contents(&tree.join("nested/leaf.txt"))
.unwrap(),
b"confirmed leaf"
);
assert_eq!(
FileOperations::metadata(transfer.as_ref(), tree_record.trashed(), false).await,
Err(FsError::NotFound)
);
assert_eq!(
FileOperations::metadata(transfer.as_ref(), plain_record.trashed(), false).await,
Err(FsError::NotFound)
);
assert!(harness.app.undo_journal.is_empty());
let task = harness.app.task_manager.tasks().last().unwrap();
assert_eq!(task.status(), TaskStatus::Succeeded);
assert_eq!(task.outcomes().count(), 2);
}
#[tokio::test]
async fn move_undo_uses_complete_destination_fingerprint_snapshot() {
let fixture = TempDir::new().unwrap();
let source = fixture.path().join("source");
let destination = fixture.path().join("destination");
std::fs::create_dir(&source).unwrap();
std::fs::create_dir(&destination).unwrap();
std::fs::write(source.join("move.txt"), b"moved").unwrap();
let entry = LocalFs::new()
.metadata(&Location::local(source.join("move.txt")))
.await
.unwrap();
let mut harness = Harness::new(&source);
harness.app.mode = PaneMode::Dual;
harness.app.pane_mut(PaneId::Right).location = Location::local(&destination);
harness.app.active_pane_mut().entries = vec![entry];
harness.app.active_pane_mut().selection.set(Some(0), 1);
harness.dispatch(Command::Move);
loop {
let command = harness.next().await;
if let Command::PlanFinished(result) = command {
assert!(
result.result.is_ok(),
"move planning failed: {:?}",
result.result
);
harness.dispatch(Command::PlanFinished(result));
break;
}
harness.dispatch(command);
}
harness.dispatch(Command::ConfirmOperation);
assert_eq!(harness.finish_task().await, OperationEventKind::Completed);
assert!(!source.join("move.txt").exists());
assert_eq!(
std::fs::read(destination.join("move.txt")).unwrap(),
b"moved"
);
let Some(UndoEntry::Move {
operation,
destination_fingerprints,
}) = harness.app.undo_journal.latest()
else {
panic!("move did not create an undo entry")
};
assert_eq!(destination_fingerprints.len(), operation.items().len());
harness.prepare_undo().await;
assert_eq!(
harness
.app
.undo
.as_ref()
.unwrap()
.summary
.as_ref()
.unwrap()
.inverse_kind,
UndoInverseKind::MoveBack
);
assert_eq!(harness.confirm_undo().await, OperationEventKind::Completed);
assert_eq!(std::fs::read(source.join("move.txt")).unwrap(), b"moved");
assert!(!destination.join("move.txt").exists());
assert!(harness.app.undo_journal.is_empty());
}
#[tokio::test]
async fn stale_missing_and_conflicting_entries_require_fresh_review_without_starting_work() {
let fixture = TempDir::new().unwrap();
let created = fixture.path().join("created.txt");
let mut harness = Harness::new(fixture.path());
create_file(&mut harness, "created.txt").await;
let original_tasks = harness.app.task_manager.len();
std::fs::write(&created, b"external change").unwrap();
harness.prepare_undo_error().await;
assert_eq!(harness.app.task_manager.len(), original_tasks);
assert_eq!(harness.app.undo_journal.len(), 1);
assert_eq!(std::fs::read(&created).unwrap(), b"external change");
harness.dispatch(Command::CloseOverlay);
assert_eq!(harness.app.undo_journal.len(), 1);
std::fs::remove_file(&created).unwrap();
harness.prepare_undo_error().await;
assert_eq!(harness.app.task_manager.len(), original_tasks);
assert_eq!(harness.app.undo_journal.len(), 1);
}
#[tokio::test]
async fn post_confirmation_failure_retains_entry_and_never_automatically_retries() {
let fixture = TempDir::new().unwrap();
let created = fixture.path().join("created.txt");
let mut harness = Harness::new(fixture.path());
create_file(&mut harness, "created.txt").await;
harness.prepare_undo().await;
let expected = harness.app.undo_journal.latest().cloned().unwrap();
// Preparation was fresh, but execution must still reject a changed source after confirmation.
std::fs::write(&created, b"changed after review").unwrap();
assert_eq!(harness.confirm_undo().await, OperationEventKind::Completed);
assert_eq!(harness.app.undo_journal.latest(), Some(&expected));
assert_eq!(std::fs::read(&created).unwrap(), b"changed after review");
let task = harness.app.task_manager.tasks().last().unwrap();
assert_eq!(task.status(), TaskStatus::Failed);
assert!(task.outcomes().all(|outcome| {
outcome.commit() == CommitOutcome::NotAttempted && outcome.phase() == ItemPhase::Failed
}));
let previous_id = task.plan().id();
// No background retry occurs: another attempt is visible only as a new preparation request.
let effects = harness.dispatch(Command::Undo);
assert_eq!(effects.len(), 1);
let new_id = match &effects[0] {
Effect::PrepareUndo(request) => request.plan_id,
_ => panic!("expected fresh undo preparation"),
};
assert_ne!(new_id, previous_id);
}
#[tokio::test]
async fn rename_undo_original_path_conflict_is_not_overwritten() {
let fixture = TempDir::new().unwrap();
let original = fixture.path().join("old.txt");
let renamed = fixture.path().join("new.txt");
std::fs::write(&original, b"original").unwrap();
let entry = LocalFs::new()
.metadata(&Location::local(&original))
.await
.unwrap();
let mut harness = Harness::new(fixture.path());
harness.app.active_pane_mut().entries = vec![entry];
harness.app.active_pane_mut().selection.set(Some(0), 1);
harness.dispatch(Command::Rename);
input_name(&mut harness, "new.txt");
harness.dispatch(Command::ConfirmEntryAction);
harness.finish_task().await;
std::fs::write(&original, b"do not overwrite").unwrap();
harness.prepare_undo_error().await;
assert_eq!(std::fs::read(&original).unwrap(), b"do not overwrite");
assert_eq!(std::fs::read(&renamed).unwrap(), b"original");
assert_eq!(harness.app.undo_journal.len(), 1);
assert_eq!(harness.app.task_manager.len(), 1);
}
#[tokio::test]
async fn cancellation_and_review_cancel_retain_journal_without_automatic_retry() {
let fixture = TempDir::new().unwrap();
let created = fixture.path().join("created.txt");
let mut harness = Harness::new(fixture.path());
create_file(&mut harness, "created.txt").await;
harness.prepare_undo().await;
harness.dispatch(Command::CloseOverlay);
assert!(created.exists());
assert_eq!(harness.app.undo_journal.len(), 1);
assert_eq!(harness.app.task_manager.len(), 1);
harness.prepare_undo().await;
harness.dispatch(Command::ConfirmOperation);
harness.dispatch(Command::OpenTasks);
harness.dispatch(Command::CancelSelectedTask);
assert_eq!(
harness.finish_task().await,
OperationEventKind::CancellationAcknowledged
);
assert!(created.exists());
assert_eq!(harness.app.undo_journal.len(), 1);
assert_eq!(
harness.app.task_manager.tasks().last().unwrap().status(),
TaskStatus::Cancelled
);
}
#[test]
fn restart_starts_with_an_empty_journal_and_non_executing_undo_state() {
let mut app = AppState::new(Location::local("/work"));
assert!(app.undo_journal.is_empty());
assert!(app.reduce(Command::Undo).is_empty());
assert_eq!(app.overlay, Overlay::Undo);
assert!(app.undo.is_none());
assert!(app.task_manager.is_empty());
assert!(
app.deferred_action
.as_ref()
.unwrap()
.message
.contains("empty")
);
}