use std::sync::Arc; use std::time::Duration; use async_trait::async_trait; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use rcom::actions::EditorCommand; use rcom::app::{AppState, Command, Effect, PaneId, PaneMode}; use rcom::domain::{Entry, EntryKind, HostAlias, Location, SourceId}; use rcom::fs::{BackendRegistry, FileOperations, FsError, LocalFs, ReadFileSystem}; use rcom::session::Application; use rcom::ssh::{ConnectionManager, DiscoveryResult, SshConnector}; use rcom::test_support::{FaultInjectEditor, FaultInjectFs, FsOperation, MemoryTransferFs}; use tempfile::TempDir; use tokio::sync::mpsc; struct NoNetwork; #[async_trait] impl SshConnector for NoNetwork { async fn connect(&self, _host: &HostAlias) -> Result, FsError> { panic!("local refresh must not access SSH") } } #[derive(Clone)] struct Remote { transfer: Arc, read: Arc, } #[async_trait] impl SshConnector for Remote { async fn connect(&self, _host: &HostAlias) -> Result, FsError> { Ok(self.read.clone()) } async fn connect_with_operations( &self, _host: &HostAlias, _epoch: u64, ) -> Result<(Arc, Option>), FsError> { Ok((self.read.clone(), Some(self.transfer.clone()))) } } async fn settle(application: &mut Application, results: &mut mpsc::Receiver) { loop { match tokio::time::timeout(Duration::from_millis(60), results.recv()).await { Ok(Some(command)) => application.dispatch(command), Ok(None) => panic!("result channel closed"), Err(_) => return, } } } #[test] fn refresh_panel_uses_typed_origin_and_rejects_stale_responses() { let mut app = AppState::new(Location::local("/left")); app.mode = PaneMode::Dual; app.panes[1].location = Location::local("/right"); app.panes[1].entries = vec![Entry::new("old", EntryKind::File)]; app.panes[1].selection.set(Some(0), 1); let left = app.pane(PaneId::Left).clone(); let effects: [Effect; 1] = app .reduce(Command::RefreshPane(PaneId::Right)) .try_into() .unwrap(); let [Effect::LoadListing(request)] = effects else { panic!("expected right listing"); }; assert_eq!(request.target, Location::local("/right")); let generation = request.generation; app.reduce(Command::ListingFinished( request.into_result(Ok(vec![Entry::new("new", EntryKind::File)])), )); assert_eq!(app.pane(PaneId::Right).entries[0].name, "new"); assert_eq!(app.pane(PaneId::Left), &left); assert_eq!(app.active, PaneId::Left); let effects: [Effect; 1] = app .reduce(Command::RefreshPane(PaneId::Right)) .try_into() .unwrap(); let [Effect::LoadListing(latest)] = effects else { panic!("expected latest listing"); }; let stale = rcom::app::ListingResult { pane: PaneId::Right, generation, target: Location::local("/right"), session_epoch: None, result: Ok(Vec::new()), }; assert!(app.reduce(Command::ListingFinished(stale)).is_empty()); assert_eq!(app.pane(PaneId::Right).entries[0].name, "new"); assert_eq!(latest.generation, generation + 1); } #[test] fn background_mode_preserves_request_guards_and_resets_for_foreground_transitions() { let mut app = AppState::new(Location::local("/left")); app.active_pane_mut().entries = vec![Entry::new("old", EntryKind::File)]; let effects: [Effect; 1] = app .reduce(Command::RefreshPane(PaneId::Left)) .try_into() .unwrap(); let [Effect::LoadListing(request)] = effects else { panic!("expected background listing"); }; assert!(app.active_pane().background_refresh); assert!(app.active_pane().loading); assert_eq!(app.active_pane().pending_target, Some(request.target)); assert_eq!(app.active_pane().listing_generation, request.generation); app.reduce(Command::Refresh); assert!(!app.active_pane().background_refresh); app.reduce(Command::RefreshPane(PaneId::Left)); app.reduce(Command::GoHome(Location::local("/other"))); assert!(!app.active_pane().background_refresh); app.reduce(Command::RefreshPane(PaneId::Left)); app.reduce(Command::ConnectSsh(HostAlias::new("edge"))); assert!(!app.active_pane().background_refresh); app.reduce(Command::RefreshPane(PaneId::Left)); app.reduce(Command::TogglePaneMode); assert!(app.pane(PaneId::Left).background_refresh); assert!(!app.pane(PaneId::Right).background_refresh); } #[test] fn background_mode_ends_only_for_the_current_terminal_listing_response() { let mut app = AppState::new(Location::local("/left")); app.active_pane_mut().entries = vec![Entry::new("old", EntryKind::File)]; app.active_pane_mut().selection.set(Some(0), 1); let first = match app.reduce(Command::RefreshPane(PaneId::Left)).as_slice() { [Effect::LoadListing(request)] => request.clone(), _ => panic!("expected first background listing"), }; let second = match app.reduce(Command::RefreshPane(PaneId::Left)).as_slice() { [Effect::LoadListing(request)] => request.clone(), _ => panic!("expected second background listing"), }; assert!( app.reduce(Command::ListingFinished(first.into_result(Ok(Vec::new())))) .is_empty() ); assert!(app.active_pane().background_refresh); assert_eq!(app.active_pane().entries[0].name, "old"); app.reduce(Command::ListingFinished( second.into_result(Ok(vec![Entry::new("new", EntryKind::File)])), )); assert!(!app.active_pane().background_refresh); assert_eq!(app.active_pane().entries[0].name, "new"); let failing = match app.reduce(Command::RefreshPane(PaneId::Left)).as_slice() { [Effect::LoadListing(request)] => request.clone(), _ => panic!("expected failing background listing"), }; assert!(app.active_pane().error.is_none()); app.reduce(Command::ListingFinished( failing.into_result(Err(FsError::PermissionDenied)), )); assert!(!app.active_pane().background_refresh); assert_eq!(app.active_pane().error, Some(FsError::PermissionDenied)); let recovery = match app.reduce(Command::RefreshPane(PaneId::Left)).as_slice() { [Effect::LoadListing(request)] => request.clone(), _ => panic!("expected background recovery"), }; assert!(app.active_pane().background_refresh); assert_eq!(app.active_pane().error, Some(FsError::PermissionDenied)); app.reduce(Command::ListingFinished( recovery.into_result(Ok(Vec::new())), )); assert!(!app.active_pane().background_refresh); assert!(app.active_pane().error.is_none()); assert!(app.active_pane().entries.is_empty()); } #[tokio::test] async fn polling_pauses_across_editor_preparation_process_and_result_application() { let fixture = TempDir::new().unwrap(); std::fs::write(fixture.path().join("note.txt"), b"before").unwrap(); let editor = Arc::new(FaultInjectEditor::new()); editor.queue_nonzero(Some(7)); let connections = ConnectionManager::new( Arc::new(NoNetwork), BackendRegistry::new(Arc::new(LocalFs::new())), ); let (mut application, mut results) = Application::new_with_editor_command( Location::local(fixture.path()), connections, DiscoveryResult::default(), EditorCommand::parse("unused-editor").unwrap(), editor.clone(), ); application.start(); settle(&mut application, &mut results).await; application.handle_key(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::NONE), 10); let generation = application.state().active_pane().listing_generation; application.refresh_visible(); let prepared = tokio::time::timeout(Duration::from_secs(1), results.recv()) .await .expect("editor preparation must not be starved") .unwrap(); assert!(matches!(prepared, Command::EditorPrepared(_))); application.dispatch(prepared); assert_eq!( application.state().active_pane().listing_generation, generation ); application.refresh_visible(); application.run_pending_editor().await; assert_eq!(editor.invocations().len(), 1); assert!(application.state().editor.is_none()); assert_eq!( std::fs::read(fixture.path().join("note.txt")).unwrap(), b"before" ); application.dispatch(Command::CloseOverlay); application.refresh_visible(); settle(&mut application, &mut results).await; assert_eq!( application.state().active_pane().listing_generation, generation + 1 ); } #[tokio::test] async fn visible_refresh_updates_local_and_fake_ssh_without_user_input_and_skips_loading() { let fixture = TempDir::new().unwrap(); std::fs::write(fixture.path().join("selected.txt"), b"selected").unwrap(); let connections = ConnectionManager::new( Arc::new(NoNetwork), BackendRegistry::new(Arc::new(LocalFs::new())), ); let (mut local, mut results) = Application::new( Location::local(fixture.path()), connections, DiscoveryResult::default(), ); local.start(); settle(&mut local, &mut results).await; let selected = local .state() .active_pane() .selected_entry() .map(|entry| entry.name.clone()); std::fs::write(fixture.path().join("external.txt"), b"external").unwrap(); local.refresh_visible(); settle(&mut local, &mut results).await; assert!( local .state() .active_pane() .entries .iter() .any(|entry| entry.name == "external.txt") ); assert_eq!( local .state() .active_pane() .selected_entry() .map(|entry| &entry.name), selected.as_ref() ); assert_eq!(local.state().active, PaneId::Left); local.state_mut_for_test().active_pane_mut().loading = true; local.refresh_visible(); assert!( tokio::time::timeout(Duration::from_millis(60), results.recv()) .await .is_err() ); let host = HostAlias::new("edge"); let root = Location::ssh(host.clone(), "/work"); let remote = MemoryTransferFs::new(SourceId::Ssh(host.clone()), 1) .with_dir(root.clone()) .with_file(root.join("selected.txt"), b"selected"); let remote = Arc::new(remote); let read = Arc::new(FaultInjectFs::new(remote.clone())); let connections = ConnectionManager::new( Arc::new(Remote { transfer: remote.clone(), read: read.clone(), }), BackendRegistry::new(Arc::new(LocalFs::new())), ); let connection = connections.connect(&host).await.unwrap(); let (mut application, mut results) = Application::new(root.clone(), connections, DiscoveryResult::default()); application .state_mut_for_test() .active_pane_mut() .session_epoch = Some(connection.epoch); application.start(); settle(&mut application, &mut results).await; let remote_selected = application .state() .active_pane() .selected_entry() .map(|entry| entry.name.clone()); remote.insert_file(root.join("external.txt"), b"external"); application.refresh_visible(); settle(&mut application, &mut results).await; assert!( application .state() .active_pane() .entries .iter() .any(|entry| entry.name == "external.txt") ); remote.insert_file(root.join("selected.txt"), b"modified contents"); application.refresh_visible(); settle(&mut application, &mut results).await; let selected_entry = application.state().active_pane().selected_entry().unwrap(); assert_eq!(selected_entry.name, remote_selected.unwrap()); assert_eq!(selected_entry.size, Some(b"modified contents".len() as u64)); let external = root.join("external.txt"); let renamed = root.join("renamed.txt"); remote.rename(&external, &renamed).await.unwrap(); application.refresh_visible(); settle(&mut application, &mut results).await; assert!( application .state() .active_pane() .entries .iter() .any(|entry| entry.name == "renamed.txt") ); assert!( application .state() .active_pane() .entries .iter() .all(|entry| entry.name != "external.txt") ); remote.remove_file(&renamed).await.unwrap(); application.refresh_visible(); settle(&mut application, &mut results).await; assert!( application .state() .active_pane() .entries .iter() .all(|entry| entry.name != "renamed.txt") ); read.fail_next( FsOperation::List, FsError::Other("injected polling failure".into()), ); application.refresh_visible(); settle(&mut application, &mut results).await; assert!(application.state().active_pane().error.is_some()); assert_eq!( application .state() .active_pane() .selected_entry() .unwrap() .name, "selected.txt" ); remote.insert_file(root.join("after-error.txt"), b"recovered"); application.refresh_visible(); settle(&mut application, &mut results).await; assert!(application.state().active_pane().error.is_none()); assert!( application .state() .active_pane() .entries .iter() .any(|entry| entry.name == "after-error.txt") ); assert_eq!( application .state() .active_pane() .selected_entry() .unwrap() .name, "selected.txt" ); assert_eq!(application.state().active, PaneId::Left); }