use super::*;
#[test]
fn persistence_advisory_only_for_nonpersistent_remote_sessions() {
assert!(super::remote_persistence_status(true, false).is_some());
assert!(super::remote_persistence_status(true, true).is_none());
assert!(super::remote_persistence_status(false, false).is_none());
assert!(super::remote_persistence_status(false, true).is_none());
}
#[test]
fn drop_to_local_with_unsaved_edits_asks_first() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, a) = app_with_unsaved_file(tmp.path());
app.session.is_remote = true;
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('l'), KeyModifiers::NONE))
.unwrap();
assert!(!app.quit && !app.drop_to_local);
assert_eq!(app.pending_unsaved, Some(UnsavedExit::DropToLocal));
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
assert!(app.drop_to_local && app.quit);
assert_eq!(std::fs::read_to_string(&a).unwrap(), "xalpha\n");
}
fn handoff_events() -> [crate::install_session::InstallEvent; 2] {
use crate::install_session::InstallEvent;
[InstallEvent::CanLaunch, InstallEvent::Done(Ok(()))]
}
#[test]
fn a_remote_handoff_asks_about_edits_made_during_the_install() {
for event in handoff_events() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "alpha\n");
type_keys(&mut app, "x");
ready_to_hand_off(&mut app, event);
app.poll_install_session();
assert!(!app.quit, "the unsaved a.txt must not go with the handoff");
assert!(app.pending_unsaved.is_some(), "it asks");
let screen = draw_screen(&mut app, 160, 40);
assert!(screen.contains("ave all and connect"), "{screen}");
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
assert!(app.quit, "saved, so it hands off: {}", app.status);
assert!(app.remote_launch.is_some(), "to the remote croft");
let a = tmp.path().join("a.txt");
assert_eq!(std::fs::read_to_string(&a).unwrap(), "xalpha\n");
}
}
#[test]
fn a_remote_handoff_with_nothing_unsaved_goes_at_once() {
for event in handoff_events() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "alpha\n");
ready_to_hand_off(&mut app, event);
app.poll_install_session();
assert!(app.quit);
assert!(app.pending_unsaved.is_none(), "nothing to ask about");
assert!(app.remote_launch.is_some());
}
}
#[test]
fn cancelling_the_remote_handoff_stays_here_with_the_edits() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, a) = app_with_unsaved_file(tmp.path());
ready_to_hand_off(&mut app, crate::install_session::InstallEvent::CanLaunch);
app.poll_install_session();
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(!app.quit);
assert!(app.remote_launch.is_none(), "the launch is dropped");
assert!(app.install_session.is_none());
assert!(app.editor.dirty && app.editor.lines[0] == "xalpha");
assert_eq!(std::fs::read_to_string(&a).unwrap(), "alpha\n");
assert!(app.status.contains("did not connect"), "{}", app.status);
}
#[test]
fn a_remote_install_whose_thread_crashed_fails_the_connect() {
let _serial = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let _restore = override_cache_dir(tmp.path().join("cache"));
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.connect_dialog = Some(crate::widgets::connect_dialog::ConnectDialog::new(
String::from("devbox"),
));
app.install_session = Some(crate::install_session::InstallSession::crashing("devbox"));
crate::test_budget::await_spawned(
std::time::Duration::from_secs(1),
"the crashed install to end",
|| {
app.poll_install_session();
app.install_session.is_none()
},
);
let dialog = app.connect_dialog.as_ref().expect("the dialog says why");
assert_eq!(
dialog.phase,
crate::widgets::connect_dialog::DialogPhase::Failed
);
assert_eq!(
dialog.error.as_deref(),
Some(crate::install_session::CRASHED_DETAIL)
);
assert!(
!app.status.contains("Remote install failed"),
"the status line is left to the crash notice: {}",
app.status
);
app.handle_connect_dialog_key(key(KeyCode::Esc, KeyModifiers::NONE));
assert!(app.connect_dialog.is_none(), "Esc closes it");
}
#[test]
fn a_failed_remote_install_closes_its_ssh_connection() {
let _serial = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let _restore = override_cache_dir(tmp.path().join("cache"));
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let socket_dir = tmp.path().join("ctl");
std::fs::create_dir(&socket_dir).unwrap();
let adopted = crate::remote::AdoptedMaster {
host: String::from("devbox"),
socket_dir: socket_dir.clone(),
socket_path: socket_dir.join("ctl"),
};
app.connect_dialog = Some(crate::widgets::connect_dialog::ConnectDialog::new(
String::from("devbox"),
));
app.install_session = Some(crate::install_session::InstallSession::with_events(
"devbox",
None,
Some(adopted),
vec![crate::install_session::InstallEvent::Done(Err(
String::from("no space left on device"),
))],
));
app.poll_install_session();
assert!(app.install_session.is_none());
assert!(
!socket_dir.exists(),
"the connection's socket directory is gone"
);
}
#[test]
fn a_refused_save_at_the_remote_handoff_drops_the_launch() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, a) = app_with_unsaved_file(tmp.path());
std::fs::write(&a, "changed elsewhere\n").unwrap();
ready_to_hand_off(&mut app, crate::install_session::InstallEvent::CanLaunch);
app.poll_install_session();
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
assert!(!app.quit);
assert!(app.status.contains("Did not connect"), "{}", app.status);
assert!(app.remote_launch.is_none(), "not left armed");
assert_eq!(std::fs::read_to_string(&a).unwrap(), "changed elsewhere\n");
}
#[test]
fn ssh_empty_state_overlay_arms_image_clear_when_user_switches_off_remote_view() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.ssh.set_displayed(true);
app.set_sidebar_view(SidebarView::Explorer);
app.flush_ssh_empty_state_overlay(&ratatui::buffer::Buffer::empty(app.last_frame_area));
assert!(
app.consume_ssh_empty_state_image_clear(),
"leaving the Remote view after the illustration was painted must arm one terminal.clear() so iTerm2 evicts the cached image cells — otherwise the server-rack PNG ghosts onto the Explorer tree the user just clicked to"
);
assert!(!app.overlays.ssh.is_displayed());
}
#[test]
fn ssh_empty_state_overlay_arms_image_clear_when_modal_opens_on_top() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Remote);
app.overlays.ssh.set_displayed(true);
app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
.unwrap();
app.flush_ssh_empty_state_overlay(&ratatui::buffer::Buffer::empty(app.last_frame_area));
assert!(
app.consume_ssh_empty_state_image_clear(),
"F1 opening the shortcuts modal over the SSH empty state must arm an image-clear so the illustration doesn't bleed through the modal text"
);
}
#[test]
fn cmd_shift_r_jumps_to_remote_from_any_pane() {
let mut app = editor_app_with_lines(&["x"]);
app.focus_pane(Pane::Editor);
app.handle_key(key(
KeyCode::Char('r'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(app.sidebar_view, SidebarView::Remote);
}
#[test]
fn cmd_k_l_on_remote_requests_drop_to_local() {
let mut app = editor_app_with_lines(&["x"]);
app.session.is_remote = true;
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('l'), KeyModifiers::NONE))
.unwrap();
assert!(
app.drop_to_local && app.quit,
"Cmd+K L on a remote-launched croft must request a clean hand-back to the local croft"
);
let mut app = editor_app_with_lines(&["x"]);
app.session.is_remote = true;
app.run_command(crate::widgets::command_palette::Command::DropToLocal);
assert!(
app.drop_to_local && app.quit,
"and so does the palette's row"
);
}
#[test]
fn cmd_shift_l_selects_all_occurrences_on_remote_too() {
for remote in [false, true] {
let mut app = editor_app_with_lines(&["foo bar foo", "foo"]);
app.session.is_remote = remote;
app.handle_key(key(
KeyCode::Char('l'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert!(!app.drop_to_local && !app.quit, "remote={remote}");
assert!(
app.status.contains("Selected 3 occurrences"),
"remote={remote}: {}",
app.status
);
}
}
#[test]
fn drop_to_local_on_local_says_there_is_nothing_to_leave() {
let mut app = editor_app_with_lines(&["x"]);
app.session.is_remote = false;
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('l'), KeyModifiers::NONE))
.unwrap();
assert!(!app.drop_to_local && !app.quit);
assert!(
app.status.contains("not a remote session"),
"{}",
app.status
);
}
#[test]
fn remote_launched_drop_queues_pull_request_via_relay_log() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let workspace = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Explorer);
app.focus_pane(Pane::Tree);
let (log, _) = with_relay_home(home.path(), || {
let log = app.relay_log_path().expect("relay log path derivable");
app.handle_paste("/Users/vitali/Documents/foo.txt\n");
(log, ())
});
let written = std::fs::read_to_string(&log).expect("relay log was written");
assert!(
written.starts_with("pull\t"),
"relay log entry must be a pull request, got: {written:?}",
);
assert!(
written.contains("/Users/vitali/Documents/foo.txt"),
"relay log must carry the foreign path, got: {written:?}",
);
assert_eq!(app.pending_remote_pulls.len(), 1);
}
#[test]
fn copying_on_a_relay_session_pushes_the_text_to_the_local_clipboard() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from("sleep 60")],
tmp.path(),
)
.unwrap();
app.show_terminal = true;
app.focus_pane(Pane::Terminal);
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let inner = app.terminals[0].last_inner;
app.terminals[0].feed_bytes_for_test(b"copy-me-538\r\n");
let (lines, top) = app.terminals[0].grid_lines();
let vrow = (top
+ lines
.iter()
.position(|l| l.starts_with("copy-me-538"))
.expect("the fed text reached the grid") as i32) as u16;
app.terminals[0].start_selection_at(inner.x, inner.y + vrow);
app.terminals[0].extend_selection_to(inner.x + 20, inner.y + vrow);
let expected = app.terminals[0].selection_text();
assert!(
expected.contains("copy-me-538"),
"precondition: the selection covers the fed text, got {expected:?}"
);
app.session.relay_key = Some(String::from("testrelay"));
let (log, inbox_for_assert) = with_relay_home(home.path(), || {
let log = app.relay_log_path().expect("relay log path derivable");
let inbox = app.relay_inbox_path().expect("relay inbox path derivable");
app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER))
.unwrap();
(log, inbox)
});
let written = std::fs::read_to_string(&log).expect("relay log was written");
assert!(
written.starts_with("copy\t"),
"a copy on a relay session must queue a copy request, got {written:?}"
);
let request_id = written
.trim_end()
.split('\t')
.nth(1)
.expect("the request carries an id");
assert_eq!(
written.trim_end().split('\t').count(),
2,
"no path belongs on the wire, got {written:?}"
);
let payload_path = inbox_for_assert.join(format!("{request_id}.txt"));
let payload = std::fs::read_to_string(&payload_path).expect("the payload file was written");
assert_eq!(
payload, expected,
"the payload must be exactly what was selected"
);
assert!(
app.status.contains("local"),
"and the status must say WHERE it went, got {:?}",
app.status
);
}
#[test]
fn remote_finder_drag_queues_pull_without_tree_focus() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let workspace = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Explorer);
app.focus_pane(Pane::Editor); let log = with_relay_home(home.path(), || {
let log = app.relay_log_path().expect("relay log path derivable");
app.handle_paste("/Users/vitali/Documents/dragged.txt\n");
log
});
let written = std::fs::read_to_string(&log).expect("relay log was written");
assert!(
written.starts_with("pull\t") && written.contains("/Users/vitali/Documents/dragged.txt"),
"a pure-path drag must queue a pull even without tree focus, got: {written:?}",
);
assert_eq!(app.pending_remote_pulls.len(), 1);
}
#[test]
fn drain_remote_pulls_imports_file_when_relay_signals_ok() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let workspace = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Explorer);
app.focus_pane(Pane::Tree);
let request_dir = with_relay_home(home.path(), || {
let inbox = app.relay_inbox_path().expect("relay inbox derivable");
let request_dir = inbox.join("test-req-1");
std::fs::create_dir_all(&request_dir).unwrap();
std::fs::write(request_dir.join("foo.txt"), "payload").unwrap();
std::fs::write(request_dir.join(".ok"), b"").unwrap();
app.pending_remote_pulls.push(PendingRemotePull {
request_id: String::from("test-req-1"),
src_display: String::from("/Users/v/Docs/foo.txt"),
basename: String::from("foo.txt"),
dest_dir: workspace.path().to_path_buf(),
started_at: std::time::Instant::now(),
kind: RemotePullKind::File,
open_after_forward: None,
remote_ipv6: false,
});
let changed = app.drain_remote_pulls();
assert!(changed);
request_dir
});
assert!(app.pending_remote_pulls.is_empty());
let landed = workspace.path().join("foo.txt");
assert!(landed.exists(), "file should land in workspace");
assert_eq!(std::fs::read_to_string(&landed).unwrap(), "payload");
assert!(
!request_dir.exists(),
"relay request dir must be cleaned up after import",
);
assert!(app.status.contains("Pulled"));
}
#[test]
fn drain_remote_pulls_surfaces_relay_error_message() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let workspace = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
with_relay_home(home.path(), || {
let inbox = app.relay_inbox_path().expect("relay inbox derivable");
let request_dir = inbox.join("req-2");
std::fs::create_dir_all(&request_dir).unwrap();
std::fs::write(request_dir.join(".err"), b"scp exited with 1").unwrap();
app.pending_remote_pulls.push(PendingRemotePull {
request_id: String::from("req-2"),
src_display: String::from("/Users/v/missing.txt"),
basename: String::from("missing.txt"),
dest_dir: workspace.path().to_path_buf(),
started_at: std::time::Instant::now(),
kind: RemotePullKind::File,
open_after_forward: None,
remote_ipv6: false,
});
let changed = app.drain_remote_pulls();
assert!(changed);
});
assert!(app.status.contains("scp exited with 1"));
}
#[test]
fn clicking_the_ports_tab_switches_the_panel_view() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let r = app.panel_hits.ports_tab;
assert!(r.width > 0, "the PORTS tab must have a hit rect");
left_click(&mut app, r.x, r.y);
assert_eq!(
app.bottom_panel_tab,
BottomPanelTab::Ports,
"a click on the PORTS tab activates that view",
);
}
#[test]
fn a_detected_port_renders_in_the_ports_panel() {
use crate::widgets::ports::PortOrigin;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.bottom_panel_tab = BottomPanelTab::Ports;
app.ports
.upsert(3000, None, Some("node".into()), PortOrigin::Local);
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer().clone();
let text: String = buf.content().iter().map(|c| c.symbol()).collect();
assert!(text.contains("3000"), "the detected port is listed");
assert!(text.contains("node"), "its process is listed");
}
#[test]
fn a_port_poll_whose_thread_crashed_lets_the_next_one_run() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(
app.terminals.iter().any(|t| t.pid().is_some()),
"setup: a pane with a shell to poll"
);
app.port_poll = Some(
crate::jobs::Job::spawn("port-poll", crate::jobs::Start::Now, || -> PortPoll {
panic!("the poll crashed (on purpose, in a test)")
})
.unwrap(),
);
app.last_port_poll = std::time::Instant::now();
crate::test_budget::await_spawned(
std::time::Duration::from_secs(1),
"the crashed poll to settle",
|| {
app.drain_ports_and_poll();
app.port_poll.is_none()
},
);
app.last_port_poll = std::time::Instant::now()
.checked_sub(crate::app::bottom_panel::PORT_POLL_INTERVAL)
.expect("the clock is past one poll interval");
app.drain_ports_and_poll();
assert!(app.port_poll.is_some(), "the next poll started");
}
#[test]
fn opening_a_forwarded_remote_port_routes_to_the_local_browser_via_relay() {
use crate::widgets::ports::{PortOrigin, PortsPanel};
let mut p = PortsPanel::new();
p.upsert(3000, None, None, PortOrigin::Remote("box".into()));
p.mark_forwarded(3000, 3001);
let entry = p.selected().unwrap();
match super::plan_port_open(entry, true) {
super::PortOpenAction::OpenViaRelay(url) => assert_eq!(url, "http://127.0.0.1:3001/"),
other => panic!("expected relay open, got {other:?}"),
}
}
#[test]
fn opening_an_unforwarded_remote_port_forwards_first() {
use crate::widgets::ports::{PortOrigin, PortsPanel};
let mut p = PortsPanel::new();
p.upsert(3000, None, None, PortOrigin::Remote("box".into()));
let entry = p.selected().unwrap();
assert!(matches!(
super::plan_port_open(entry, true),
super::PortOpenAction::Forward(3000)
));
}
#[test]
fn opening_a_local_port_opens_directly_not_via_relay() {
use crate::widgets::ports::{PortOrigin, PortsPanel};
let mut p = PortsPanel::new();
p.upsert(8000, None, None, PortOrigin::Local);
let entry = p.selected().unwrap();
match super::plan_port_open(entry, false) {
super::PortOpenAction::OpenDirect(url) => assert!(url.contains("8000"), "{url}"),
other => panic!("expected direct open, got {other:?}"),
}
}
#[test]
fn double_clicking_a_port_row_opens_it() {
use crate::widgets::ports::PortOrigin;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.bottom_panel_tab = BottomPanelTab::Ports;
app.ports
.upsert(3000, None, None, PortOrigin::Remote("box".into()));
draw(&mut app, 140, 50);
let x = app.ports.last_area.x + 2;
let y = app.ports.last_area.y + 1; left_click(&mut app, x, y);
assert!(
!app.status.contains("orward"),
"a single click must not open the port: {}",
app.status
);
left_click(&mut app, x, y);
assert!(
app.status.contains("orward"),
"a double click opens (forwards) the port: {}",
app.status
);
}
#[test]
fn a_modified_click_does_not_pair_with_a_plain_one_in_the_ports_table() {
use crate::widgets::ports::PortOrigin;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.bottom_panel_tab = BottomPanelTab::Ports;
app.ports
.upsert(3000, None, None, PortOrigin::Remote("box".into()));
draw(&mut app, 140, 50);
let x = app.ports.last_area.x + 2;
let y = app.ports.last_area.y + 1;
let click_with = |app: &mut App, modifiers| {
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: x,
row: y,
modifiers,
});
};
click_with(&mut app, KeyModifiers::CONTROL);
click_with(&mut app, KeyModifiers::empty());
assert!(
!app.status.contains("orward"),
"a plain click after a ctrl+click must not open the port: {}",
app.status
);
click_with(&mut app, KeyModifiers::empty());
app.status.clear();
click_with(&mut app, KeyModifiers::CONTROL);
assert!(
!app.status.contains("orward"),
"a ctrl+click must not complete a double-click: {}",
app.status
);
app.status.clear();
click_with(&mut app, KeyModifiers::empty());
click_with(&mut app, KeyModifiers::empty());
assert!(
app.status.contains("orward"),
"two ordinary clicks must still open the port: {}",
app.status
);
}
#[test]
fn clicking_the_port_toast_dismiss_button_clears_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.show_port_toast(3000, Some("node".into()));
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let dismiss = app
.port_toast
.as_ref()
.expect("toast is showing")
.buttons
.iter()
.find(|(_, a)| matches!(a, super::PortToastAction::Dismiss))
.map(|(r, _)| *r)
.expect("the toast has a dismiss button");
left_click(&mut app, dismiss.x, dismiss.y);
assert!(
app.port_toast.is_none(),
"clicking dismiss clears the toast"
);
}
#[test]
fn croft_loch_port_toast_is_a_raised_card() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.theme = crate::theme::Theme::from_id("loch");
let t = crate::theme::tones(app.theme).unwrap();
app.show_port_toast(3000, Some("node".into()));
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let buttons = app.port_toast.as_ref().unwrap().buttons.clone();
let (open, _) = buttons[0];
let (dismiss, _) = *buttons.last().unwrap();
let top = open.y - 2;
let x0 = open.x - 2;
assert_eq!(buf[(x0, top)].symbol(), "\u{2594}");
assert_eq!(buf[(x0, top)].fg, t.accent(), "the lip");
let edge: String = (x0..x0 + 20).map(|x| buf[(x, top)].symbol()).collect();
assert!(!edge.contains("PORT"), "{edge}");
assert_eq!(buf[(open.x - 1, open.y)].bg, t.raised());
assert_eq!(buf[(open.x, open.y)].bg, app.theme.button());
assert!(!buf[(open.x, open.y)].modifier.contains(Modifier::BOLD));
assert_eq!(buf[(dismiss.x + 1, dismiss.y)].fg, t.muted());
assert_eq!(buf[(dismiss.x + 1, dismiss.y)].bg, t.raised());
}
#[test]
fn relay_request_ids_are_unique_per_request() {
let ids: Vec<String> = (0..64).map(|_| App::relay_request_id("forward")).collect();
let unique: std::collections::HashSet<&String> = ids.iter().collect();
assert_eq!(unique.len(), ids.len(), "every request id must be distinct");
assert!(ids[0].starts_with("forward-"), "kind stays in the id");
}
#[test]
fn losing_the_relay_reconnects_instead_of_typing_into_the_void() {
use std::time::{Duration, Instant};
let tmp = tempfile::tempdir().unwrap();
let socket = tmp.path().join("collab.sock");
let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
let mut guest = App::new(tmp.path().to_path_buf()).unwrap();
guest.collab.config = Some((socket.clone(), crate::collab::CollabRole::Guest));
guest.poll_collab();
assert!(guest.collab.session.is_some(), "first connect");
let (peer, _) = listener.accept().unwrap();
drop(peer);
let deadline = Instant::now() + Duration::from_secs(3);
while guest.collab.session.is_some() {
assert!(
Instant::now() < deadline,
"the dead session was never dropped"
);
guest.poll_collab();
std::thread::sleep(Duration::from_millis(10));
}
let deadline = Instant::now() + Duration::from_secs(5);
while guest.collab.session.is_none() {
assert!(Instant::now() < deadline, "never reconnected");
guest.poll_collab();
std::thread::sleep(Duration::from_millis(50));
}
}
#[test]
fn a_relay_failure_releases_the_host_lock() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.pair.record_path = tmp.path().join("x.pair.json");
app.pair.socket = tmp.path().join("missing-dir").join("collab.sock");
app.pair.host_lock_path = tmp.path().join("x.host.lock");
app.pair.spawn_override = Some(Box::new(|_| panic!("must not reach the spawn")));
crate::session::write_pair_record(
&app.pair.record_path,
&crate::session::PairRecord {
model: None,
name: "nav".into(),
enabled: true,
task: None,
provider: None,
base_url: None,
},
)
.unwrap();
app.pair.last_check = None;
app.maybe_seat_navigator();
assert!(app.pair.host.is_none());
assert!(
app.status.contains("relay failed"),
"the failure is announced: {}",
app.status
);
assert!(
app.pair.host_lock.is_none(),
"a window without a relay cannot host; the lock must be released"
);
}
#[test]
fn a_fleet_run_reports_through_the_channel_rather_than_blocking() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(!app.drain_fleet_results(), "no run, nothing to report");
let results = vec![
crate::fleet::HostResult {
host: String::from("a"),
output: String::from("5.15.0"),
exit: Some(0),
elapsed: std::time::Duration::ZERO,
},
crate::fleet::HostResult {
host: String::from("b"),
output: String::from("5.15.0"),
exit: Some(0),
elapsed: std::time::Duration::ZERO,
},
crate::fleet::HostResult {
host: String::from("odd"),
output: String::from("6.1.0"),
exit: Some(0),
elapsed: std::time::Duration::ZERO,
},
crate::fleet::HostResult {
host: String::from("down"),
output: String::from("timed out"),
exit: None,
elapsed: std::time::Duration::ZERO,
},
];
app.fleet_run = Some(crate::jobs::Job::finished(results));
assert!(app.drain_fleet_results(), "a delivered result must report");
assert!(app.fleet_run.is_none(), "the run is no longer in flight");
assert!(
app.status.contains("2 identical") && app.status.contains("1 differ"),
"the summary must reach the user: {}",
app.status
);
assert!(app.status.contains("1 failed"), "status: {}", app.status);
assert!(!app.drain_fleet_results(), "results are consumed once");
}
#[test]
fn an_ssh_session_raises_the_offer_once_and_drops_it_when_the_session_ends() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.remote_offer_refused.clear();
let pane = app.terminals[0].uid();
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(
app.ssh_offer
.as_ref()
.is_some_and(|o| o.pane == pane && o.host == "db-1"),
"a new session offers"
);
assert!(
app.status.starts_with("Connected to db-1"),
"{:?}",
app.status
);
app.status = String::from("something else happened");
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert_eq!(
app.status, "something else happened",
"the same session sampled again does not re-prompt"
);
app.status = String::from("Connected to db-1 · Open workspace here?");
app.consider_ssh_offer(pane, None);
assert!(
app.ssh_offer.is_none(),
"the session ended: the offer is gone"
);
assert!(app.status.is_empty(), "and its status line with it");
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(app.ssh_offer.is_some());
}
#[test]
fn the_offer_respects_the_global_switch_the_host_list_and_learned_refusals() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.remote_offer_refused.clear();
let pane = app.terminals[0].uid();
app.remote_offer_excluded = vec![String::from("DB-1")];
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(
app.ssh_offer.is_none(),
"per-host opt-out, case-insensitive"
);
app.remote_offer_excluded.clear();
app.remote_offer_refused
.insert(String::from("db-1"), std::time::SystemTime::now());
app.consider_ssh_offer(pane, None);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(
app.ssh_offer.is_none(),
"a host that refused provisioning is not offered"
);
app.remote_offer_refused.clear();
app.remote_offer_disabled = true;
app.consider_ssh_offer(pane, None);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(app.ssh_offer.is_none(), "the global switch");
app.remote_offer_disabled = false;
app.consider_ssh_offer(pane, None);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(
app.ssh_offer.is_some(),
"and with every gate open it offers"
);
}
#[test]
fn accepting_or_dismissing_the_offer_clears_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.remote_offer_refused.clear();
let pane = app.terminals[0].uid();
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert_eq!(
app.accept_ssh_offer().map(|(host, _)| host).as_deref(),
Some("db-1")
);
assert!(app.ssh_offer.is_none() && app.status.is_empty());
assert_eq!(app.accept_ssh_offer(), None, "nothing to accept twice");
app.consider_ssh_offer(pane, None);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(app.ssh_offer.is_some());
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(app.ssh_offer.is_none(), "Esc dismissed the offer");
assert!(app.status.is_empty());
}
#[test]
fn taking_a_host_off_the_exclusion_list_offers_the_session_already_on_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.remote_offer_refused.clear();
let pane = app.terminals[0].uid();
let mut prefs = crate::prefs::Prefs {
remote_offer_excluded_hosts: vec![String::from("DB-1")],
..Default::default()
};
app.apply_merged_settings(&prefs);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(app.ssh_offer.is_none(), "excluded: no offer");
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(
app.ssh_offer.is_none(),
"still the same session, still excluded"
);
prefs.remote_offer_excluded_hosts.clear();
app.apply_merged_settings(&prefs);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(
app.ssh_offer
.as_ref()
.is_some_and(|o| o.pane == pane && o.host == "db-1"),
"the live session is offered once its host is allowed again"
);
prefs.remote_offer_excluded_hosts = vec![String::from("jump"), String::from("db-1")];
app.apply_merged_settings(&prefs);
assert!(
app.ssh_offer.is_none(),
"re-excluding db-1 takes its offer down"
);
app.consider_ssh_offer(pane, Some(String::from("jump")));
prefs.remote_offer_excluded_hosts = vec![String::from("jump")];
app.apply_merged_settings(&prefs);
app.consider_ssh_offer(pane, Some(String::from("jump")));
assert!(
app.ssh_offer.is_none(),
"jump stayed excluded and stayed quiet"
);
}
#[test]
fn cmd_k_g_with_no_offer_open_says_so_instead_of_connecting() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.ssh_offer.is_none());
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('g'), KeyModifiers::NONE)));
assert!(
app.status.starts_with("No ssh workspace offer is open"),
"status: {}",
app.status
);
assert!(app.connect_dialog.is_none(), "nothing was launched");
assert!(app.pending_remote_launch_host.is_none());
}
#[test]
fn ssh_samples_from_the_label_thread_drive_the_offer_by_shell_pid() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.remote_offer_refused.clear();
let shell = app.terminals[0]
.shell_pid()
.expect("the pane has a shell pid");
let uid = app.terminals[0].uid();
app.apply_ssh_samples(vec![
(shell, Some(String::from("db-1"))),
(-42, Some(String::from("x"))),
]);
assert!(
app.ssh_offer
.as_ref()
.is_some_and(|o| o.pane == uid && o.host == "db-1")
);
app.apply_ssh_samples(vec![(shell, None)]);
assert!(
app.ssh_offer.is_none(),
"the session ended through the same path"
);
}
#[test]
fn a_failed_provisioning_is_remembered_and_a_later_success_forgets_it() {
let _serial = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let _restore = override_cache_dir(tmp.path().join("cache"));
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(
app.remote_offer_refused.is_empty(),
"a fresh cache dir remembers nothing"
);
let pane = app.terminals[0].uid();
app.note_provisioning_failed("DB-1", "refused");
assert!(
app.remote_offer_refused.contains_key("db-1"),
"remembered in memory, lower-cased"
);
let refused_path = crate::remote::refused_hosts_path(&tmp.path().join("cache"));
let on_disk = crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now());
assert!(on_disk.contains_key("db-1"), "and on disk: {on_disk:?}");
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(app.ssh_offer.is_none(), "a refused host is not offered");
app.note_provisioning_succeeded("db-1");
assert!(
!app.remote_offer_refused.contains_key("db-1"),
"a success forgets it in memory"
);
let on_disk = crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now());
assert!(!on_disk.contains_key("db-1"), "and on disk");
app.consider_ssh_offer(pane, None);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(app.ssh_offer.is_some(), "and the host is offered again");
}
#[test]
fn a_success_forgets_a_refusal_another_croft_recorded() {
let _serial = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let cache = tmp.path().join("cache");
let _restore = override_cache_dir(cache.clone());
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.remote_offer_refused.clear();
let refused_path = crate::remote::refused_hosts_path(&cache);
crate::remote::remember_refused_host(&refused_path, "db-1", std::time::SystemTime::now())
.unwrap();
assert!(
crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now())
.contains_key("db-1")
);
app.note_provisioning_succeeded("DB-1");
assert!(
!crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now())
.contains_key("db-1"),
"the disk refusal is gone even though this instance never held it"
);
}
#[test]
fn provisioning_outcomes_are_logged_to_the_remote_output_channel() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.note_provisioning_failed("zz364-a.example", "no space left on device");
app.note_provisioning_succeeded("zz364-b.example");
let lines = crate::output::snapshot(crate::output::CHANNEL_REMOTE)
.expect("the Remote channel exists");
let failed = lines
.iter()
.find(|l| l.text.contains("zz364-a.example"))
.expect("the failure is logged");
assert!(
failed.text.contains("no space left on device"),
"{}",
failed.text
);
assert_eq!(failed.level, crate::output::OutputLevel::Error);
assert!(
lines.iter().any(|l| l.text.contains("zz364-b.example")
&& l.level != crate::output::OutputLevel::Error),
"the success is logged"
);
});
}
#[test]
fn fleet_output_shows_each_hosts_time_and_the_lines_that_differ() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let r = |host: &str, out: &str, ms: u64| crate::fleet::HostResult {
host: String::from(host),
output: String::from(out),
exit: Some(0),
elapsed: std::time::Duration::from_millis(ms),
};
app.fleet_run = Some(crate::jobs::Job::finished(vec![
r("zz363-a", "Linux\n6.8.0-45", 120),
r("zz363-b", "Linux\n6.8.0-45", 80),
r("zz363-odd", "Linux\n6.8.0-31", 1500),
]));
assert!(app.drain_fleet_results());
let lines: Vec<String> = crate::output::snapshot(crate::output::CHANNEL_FLEET)
.unwrap()
.into_iter()
.map(|l| l.text)
.collect();
let odd = lines
.iter()
.position(|l| l.starts_with("zz363-odd"))
.expect("the odd host has a row");
assert!(
lines[odd].contains("[DIFFERS]") && lines[odd].contains("1.5s"),
"{}",
lines[odd]
);
assert_eq!(
lines[odd + 1..odd + 3],
[" - 6.8.0-45", " + 6.8.0-31"],
"the reference's line and the host's, alone"
);
let a = lines.iter().find(|l| l.starts_with("zz363-a")).unwrap();
assert!(a.contains("0.1s"), "{a}");
assert!(
!lines
.iter()
.any(|l| l.ends_with(" Linux") && l.starts_with(" ")),
"an equal line is not marked"
);
}
#[test]
fn a_fleet_run_whose_thread_crashed_lets_the_next_one_run() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.fleet_run = Some(
crate::jobs::Job::spawn("fleet-run", crate::jobs::Start::Now, || {
panic!("the run crashed (on purpose, in a test)")
})
.unwrap(),
);
crate::test_budget::await_spawned(
std::time::Duration::from_secs(1),
"the crashed run to settle",
|| {
app.drain_fleet_results();
app.fleet_run.is_none()
},
);
let lines: Vec<String> = crate::output::snapshot(crate::output::CHANNEL_FLEET)
.unwrap_or_default()
.into_iter()
.map(|l| l.text)
.collect();
assert!(
lines
.iter()
.any(|l| l == "the fleet run stopped without results"),
"{lines:?}"
);
app.run_fleet_command("localhost: echo fleet-again");
assert_eq!(app.status, "Fleet: running on 1 hosts…");
assert!(app.fleet_run.is_some(), "the next run started");
}
#[test]
fn a_fleet_run_opens_tiles_that_save_and_open_a_shell() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_fleet_command("localhost: echo fleet-ok");
crate::test_budget::await_spawned(std::time::Duration::from_secs(10), "the fleet run", || {
app.drain_fleet_results();
app.editor.fleet.is_some()
});
let view = app.editor.fleet.as_ref().unwrap();
assert_eq!(view.command, "echo fleet-ok");
assert_eq!(view.results.len(), 1);
assert_eq!(view.results[0].output, "fleet-ok");
assert_eq!(app.editor.path.as_deref(), Some(Path::new("Fleet")));
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let screen: String = (0..30)
.map(|y| {
(0..120)
.map(|x| term.backend().buffer()[(x, y)].symbol())
.collect::<String>()
+ "\n"
})
.collect();
assert!(screen.contains("localhost"), "{screen}");
app.handle_key(key(KeyCode::Char('d'), KeyModifiers::NONE))
.unwrap();
assert!(!app.editor.fleet.as_ref().unwrap().diff_mode);
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
let saved = std::fs::read_dir(tmp.path())
.unwrap()
.filter_map(|e| e.ok().map(|e| e.path()))
.find(|p| {
p.file_name()
.is_some_and(|n| n.to_string_lossy().starts_with("fleet-"))
})
.expect("a capture file");
let text = std::fs::read_to_string(saved).unwrap();
assert!(text.starts_with("$ echo fleet-ok\n"), "{text}");
assert!(text.contains("== localhost (exit 0,"), "{text}");
let panes = app.terminals.len();
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.terminals.len(),
panes + 1,
"a shell pane opened: {}",
app.status
);
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(app.editor.fleet.is_none());
}
#[test]
fn fleet_shell_commands_quote_the_target() {
assert_eq!(fleet_shell_command("localhost"), None);
assert_eq!(fleet_shell_command("db-1").as_deref(), Some("ssh 'db-1'"));
assert_eq!(
fleet_shell_command("docker:web").as_deref(),
Some("docker exec -it 'web' sh")
);
}
#[test]
fn a_forwarded_port_is_reused_and_a_pending_forward_not_repeated() {
use crate::widgets::ports::PortOrigin;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let workspace = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
let log = with_relay_home(home.path(), || {
let log = app.relay_log_path().expect("relay log path derivable");
app.request_remote_forward(3000, true);
app.request_remote_forward(3000, true);
let first = std::fs::read_to_string(&log).unwrap_or_default();
assert_eq!(first.matches("forward\t").count(), 1, "{first:?}");
app.pending_remote_pulls.clear();
app.ports
.upsert(3000, None, None, PortOrigin::Remote("box".into()));
app.ports.mark_forwarded(3000, 3001);
app.request_remote_forward(3000, true);
log
});
let all = std::fs::read_to_string(&log).unwrap();
assert_eq!(all.matches("forward\t").count(), 1, "{all:?}");
assert!(all.contains("http://127.0.0.1:3001/"), "{all:?}");
}
#[test]
fn only_a_remote_launched_croft_polls_the_build_marker() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.update_watch.is_none());
assert!(!app.poll_source_build_marker());
assert!(
app.build_marker_checked.is_none(),
"a local croft read the marker"
);
assert!(app.lsp.manager.is_some());
app.update_watch = Some(crate::update_watch::UpdateWatch::start(
tmp.path().to_path_buf(),
String::new(),
));
let just_now = std::time::Instant::now();
app.build_marker_checked = Some(just_now);
assert!(!app.poll_source_build_marker());
assert_eq!(
app.build_marker_checked,
Some(just_now),
"the marker was read again within the second"
);
}
#[test]
fn the_output_ports_and_captures_tabs_are_announced_by_name_and_row() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus = Pane::Terminal;
let channel = "a11y-1295-channel";
crate::output::push(channel, crate::output::OutputLevel::Info, "hello");
app.output.sync();
assert!(app.output.select_by_name(channel));
app.bottom_panel_tab = BottomPanelTab::Output;
assert_eq!(app.a11y_snapshot().focus, format!("Output, {channel}"));
app.bottom_panel_tab = BottomPanelTab::Ports;
let snap = app.a11y_snapshot();
assert_eq!((snap.focus.as_str(), snap.item), ("Ports, none", None));
app.ports.upsert(
3000,
Some("http://localhost:3000".into()),
Some("node".into()),
crate::widgets::ports::PortOrigin::Local,
);
let snap = app.a11y_snapshot();
assert_eq!(snap.focus, "Ports, 1 port");
assert_eq!(
snap.item.as_deref(),
Some("Port 3000, node, http://localhost:3000")
);
app.bottom_panel_tab = BottomPanelTab::Captures;
assert_eq!(app.a11y_snapshot().focus, "Captures, none");
app.captures.push(crate::widgets::captures::CapturedLine {
pane: "zsh".into(),
shell_pid: None,
message: "Build failed".into(),
line: "error: build failed".into(),
anchor: None,
});
let snap = app.a11y_snapshot();
assert_eq!(snap.focus, "Captures, 1 capture");
assert_eq!(snap.item.as_deref(), Some("Build failed, from zsh"));
}
#[test]
fn every_copy_on_a_relay_session_reaches_the_local_clipboard() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("a.txt");
std::fs::write(&p, "alpha beta\nsecond\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&p).unwrap();
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
.unwrap();
let sent = relay_copied(&mut app, |app| {
app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER))
.unwrap();
});
assert_eq!(sent.as_deref(), Some("alpha beta\nsecond"), "editor Copy");
assert!(app.status.contains("local clipboard"), "{}", app.status);
let sent = relay_copied(&mut app, |app| app.copy_path_to_clipboard(p.clone()));
assert_eq!(sent, Some(p.display().to_string()), "Copy Path");
assert!(
app.status.ends_with("sent to the local clipboard"),
"{}",
app.status
);
app.editor.clear_selection();
app.editor.cursor_row = 0;
let sent = relay_copied(&mut app, |app| app.delete_current_line());
assert_eq!(sent.as_deref(), Some("alpha beta\n"), "Delete Line");
app.ports
.upsert(3000, None, None, crate::widgets::ports::PortOrigin::Local);
let sent = relay_copied(&mut app, |app| app.ports_copy_selected());
assert_eq!(
sent.as_deref(),
Some("http://127.0.0.1:3000/"),
"Ports copy"
);
}
#[test]
fn a_cut_then_paste_on_a_relay_session_puts_back_the_cut_text() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("a.txt");
std::fs::write(&p, "alpha beta\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.clipboard_reader = || Some(String::from("stale remote text"));
app.editor.open(&p).unwrap();
app.focus_pane(Pane::Editor);
app.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: (0, 0),
head: (0, 5),
});
app.editor.cursor_col = 5;
let sent = relay_copied(&mut app, |app| {
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::SUPER))
.unwrap();
});
assert_eq!(sent.as_deref(), Some("alpha"), "the cut went home");
assert_eq!(app.editor.lines[0], " beta");
app.editor.cursor_col = app.editor.lines[0].chars().count();
app.handle_key(key(KeyCode::Char('v'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(app.editor.lines[0], " betaalpha", "{}", app.status);
}
#[test]
fn a_relay_copy_the_local_machine_could_not_take_goes_by_osc52() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.session.relay_key = Some(String::from("testrelay"));
let _ = crate::clipboard::test_clip::take_osc52_sent();
with_relay_home(home.path(), || {
let inbox = app.relay_inbox_path().expect("relay inbox derivable");
assert_eq!(app.copy_where_pasted("landed"), CopyLanding::Local);
assert_eq!(app.copy_where_pasted("refused"), CopyLanding::Local);
let ids: Vec<String> = app
.pending_relay_copies
.iter()
.map(|c| c.request_id.clone())
.collect();
assert_eq!(ids.len(), 2, "both copies wait for an answer");
assert!(!app.drain_relay_copies(), "no answer yet");
assert!(crate::clipboard::test_clip::take_osc52_sent().is_empty());
let refused = inbox.join(&ids[1]);
std::fs::create_dir_all(&refused).unwrap();
std::fs::write(refused.join(".err"), "no clipboard to write").unwrap();
assert!(app.drain_relay_copies());
assert_eq!(
crate::clipboard::test_clip::take_osc52_sent(),
vec![String::from("refused")]
);
assert!(app.status.contains("via OSC 52"), "{}", app.status);
assert!(!refused.exists(), "the answer is cleared");
assert_eq!(app.pending_relay_copies.len(), 1, "the other still waits");
app.pending_relay_copies[0].started_at -= RELAY_COPY_ANSWER_WAIT;
assert!(!app.drain_relay_copies());
assert!(
app.pending_relay_copies.is_empty(),
"silence means it landed"
);
assert!(crate::clipboard::test_clip::take_osc52_sent().is_empty());
});
}
#[test]
fn pdf_external_links_refuse_non_web_and_malformed_schemes() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for hostile in [
"file:///etc/hosts",
"vscode://file/etc/passwd",
"javascript:alert(1)",
"mailto:a@b.c",
] {
app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(hostile)));
assert!(
app.status.starts_with("Refused to open non-web link:"),
"{hostile} must be refused, got {:?}",
app.status
);
}
for malformed in [
"https://example.com\nopen\tevil",
"https://exa\u{0}mple.com",
] {
app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(malformed)));
assert!(
app.status.starts_with("Refused to open malformed link:"),
"{malformed:?} must be refused, got {:?}",
app.status
);
}
}
#[test]
fn pdf_external_links_route_through_relay_and_refuse_plain_remote() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.session.is_remote = true;
app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(
"https://example.com/spec.pdf",
)));
assert!(
app.status.contains("Running remotely"),
"plain remote session must refuse browser open, got {:?}",
app.status
);
assert!(app.pending_local_open.is_none());
with_relay_home(home.path(), || {
app.trust_local_browser = false;
app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(
"https://example.com/spec.pdf",
)));
assert_eq!(
app.pending_local_open.as_deref(),
Some("https://example.com/spec.pdf")
);
app.pending_local_open = None;
app.pending_remote_pulls.clear();
app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(
"https://localhost.run/docs",
)));
assert_eq!(
app.pending_local_open.as_deref(),
Some("https://localhost.run/docs")
);
assert!(
app.pending_remote_pulls.is_empty(),
"public lookalike host must not queue a port forward"
);
app.pending_local_open = None;
app.trust_local_browser = true;
let log = app.relay_log_path().expect("relay log path derivable");
app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(
"https://example.com/manual",
)));
let written = std::fs::read_to_string(&log).expect("relay log written");
assert!(
written.contains("open\t") && written.contains("https://example.com/manual"),
"trusted relay open should queue open request, got {written:?}"
);
app.pending_remote_pulls.clear();
app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(
"https://localhost:8443/docs/spec.pdf?download=1#page=3",
)));
let written = std::fs::read_to_string(&log).expect("relay log updated");
let fwd_req = app
.pending_remote_pulls
.iter()
.find(|p| matches!(p.kind, RemotePullKind::Forward { remote_port: 8443 }))
.expect("loopback PDF link should queue port 8443 forward")
.request_id
.clone();
assert!(
written.contains(&format!("forward\t{fwd_req}\t8443\t0\n")),
"loopback PDF link must forward without auto-opening bare http root, got {written:?}"
);
let inbox = app.relay_inbox_path().expect("relay inbox derivable");
let fwd_dir = inbox.join(&fwd_req);
std::fs::create_dir_all(&fwd_dir).unwrap();
std::fs::write(fwd_dir.join(".ok"), "51234").unwrap();
assert!(app.drain_remote_pulls());
assert_eq!(
app.ports.forwarded_local_port(8443),
Some(51234),
"completed PDF port forward must register in PORTS even without prior detection"
);
let written = std::fs::read_to_string(&log).expect("relay log updated after forward");
assert!(
written.contains("open\t")
&& written.contains("https://127.0.0.1:51234/docs/spec.pdf?download=1#page=3"),
"forwarded PDF link must preserve scheme, path, query and fragment, got {written:?}"
);
let before_len = written.len();
app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(
"https://localhost:8443/other?v=2#top",
)));
let written = std::fs::read_to_string(&log).expect("relay log updated on reuse");
let appended = &written[before_len..];
assert!(
!appended.contains("forward\t"),
"already-forwarded port must reuse existing tunnel, got {appended:?}"
);
assert!(
appended.contains("open\t")
&& appended.contains("https://127.0.0.1:51234/other?v=2#top"),
"reused tunnel must open rewritten destination URL, got {appended:?}"
);
let before_v6_len = written.len();
app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(
"http://[::1]:8443/v6docs?k=1#top",
)));
let written = std::fs::read_to_string(&log).expect("relay log updated for ipv6");
let appended_v6 = &written[before_v6_len..];
let v6_req = app
.pending_remote_pulls
.iter()
.find(|p| {
matches!(p.kind, RemotePullKind::Forward { remote_port: 8443 }) && p.remote_ipv6
})
.expect("IPv6 loopback PDF link should queue its own [::1] forward")
.request_id
.clone();
assert!(
appended_v6.contains(&format!("forward\t{v6_req}\t8443\t0\t[::1]\n")),
"IPv6 forward request must name remote [::1], got {appended_v6:?}"
);
let v6_dir = inbox.join(&v6_req);
std::fs::create_dir_all(&v6_dir).unwrap();
std::fs::write(v6_dir.join(".ok"), "51235").unwrap();
assert!(app.drain_remote_pulls());
assert_eq!(app.ports.forwarded_local_port_for(8443, false), Some(51234));
assert_eq!(app.ports.forwarded_local_port_for(8443, true), Some(51235));
let written = std::fs::read_to_string(&log).expect("relay log updated after ipv6 open");
assert!(
written.contains("open\t") && written.contains("http://127.0.0.1:51235/v6docs?k=1#top"),
"completed IPv6 forward must open rewritten URL on its local port, got {written:?}"
);
app.ports.select_index(1);
assert!(app.ports.selected().is_some_and(|e| e.remote_ipv6));
let before_stop_len = written.len();
app.ports_stop_selected();
let written = std::fs::read_to_string(&log).expect("relay log updated after ipv6 stop");
assert!(
written[before_stop_len..].contains("\t51235\t8443\t[::1]\n"),
"stopping selected IPv6 row must send [::1] unforward, got {:?}",
&written[before_stop_len..]
);
assert_eq!(
app.ports.forwarded_local_port_for(8443, false),
Some(51234),
"stopping IPv6 row must keep IPv4 tunnel intact"
);
assert_eq!(app.ports.forwarded_local_port_for(8443, true), None);
let before_restart_len = written.len();
app.pending_remote_pulls.clear();
app.ports_forward_selected();
let written = std::fs::read_to_string(&log).expect("relay log updated after ipv6 restart");
assert!(
written[before_restart_len..].contains("\t8443\t0\t[::1]\n"),
"restarting stopped IPv6 row via `f` must forward [::1], got {:?}",
&written[before_restart_len..]
);
assert!(
app.pending_remote_pulls.iter().any(|p| matches!(
p.kind,
RemotePullKind::Forward { remote_port: 8443 }
) && p.remote_ipv6),
"restarted IPv6 forward pull must carry remote_ipv6=true"
);
let before_open_len = written.len();
app.pending_remote_pulls.clear();
app.ports_open_selected();
let written = std::fs::read_to_string(&log).expect("relay log updated after ipv6 open");
assert!(
written[before_open_len..].contains("\t8443\t1\t[::1]\n"),
"restarting stopped IPv6 row via Enter must forward [::1], got {:?}",
&written[before_open_len..]
);
app.ports_stop_selected();
assert_eq!(app.ports.len(), 1);
assert_eq!(
app.ports.forwarded_local_port_for(8443, false),
Some(51234),
"dismissing IPv6 row must leave IPv4 tunnel on same port intact"
);
assert_eq!(app.ports.forwarded_local_port_for(8443, true), None);
});
}
#[test]
fn plain_remote_session_refuses_browser_open_across_all_link_paths() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.session.is_remote = true;
app.open_detected_url("https://example.com/term");
assert!(
app.status.contains("Running remotely"),
"open_detected_url must refuse on plain remote, got {:?}",
app.status
);
app.open_ssh_learn_more();
assert!(
app.status.contains("Running remotely"),
"open_ssh_learn_more must refuse on plain remote, got {:?}",
app.status
);
app.open_document_link("https://example.com/doc");
assert!(
app.status.contains("Running remotely"),
"open_document_link must refuse on plain remote, got {:?}",
app.status
);
assert!(
!app.try_open_url_for_user("https://example.com/release"),
"try_open_url_for_user must report false on plain remote"
);
assert!(
app.status.contains("Running remotely"),
"try_open_url_for_user must explain refusal, got {:?}",
app.status
);
with_relay_home(home.path(), || {
app.trust_local_browser = false;
app.pending_local_open = None;
app.open_detected_url("https://example.com/term");
assert_eq!(
app.pending_local_open.as_deref(),
Some("https://example.com/term")
);
app.pending_local_open = None;
app.open_ssh_learn_more();
assert_eq!(
app.pending_local_open.as_deref(),
Some("https://man.openbsd.org/ssh_config")
);
app.pending_local_open = None;
app.open_document_link("https://example.com/doc");
assert_eq!(
app.pending_local_open.as_deref(),
Some("https://example.com/doc")
);
app.pending_local_open = None;
assert!(app.try_open_url_for_user("https://example.com/release"));
assert_eq!(
app.pending_local_open.as_deref(),
Some("https://example.com/release")
);
let mut local_app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(local_app.try_open_url_for_user("https://example.com/local"));
assert_eq!(local_app.status, "Open https://example.com/local");
assert!(local_app.pending_local_open.is_none());
});
}
#[test]
fn terminal_paste_requests_relay_clipboard_before_remote_host_clipboard() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let workspace = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.clipboard_reader = || Some(String::from("local-one\nlocal-two"));
app.paste_clipboard_into_terminal();
let pending = app
.pending_terminal_paste
.take()
.expect("local terminal paste should read from clipboard_reader");
assert_eq!(pending, b"local-one\nlocal-two");
crate::clipboard::remember_copy("copied-a\ncopied-b");
app.clipboard_reader = || None;
app.paste_clipboard_into_terminal();
let fallback = app
.pending_terminal_paste
.take()
.expect("local terminal paste should fall back to last_copy()");
assert_eq!(fallback, b"copied-a\ncopied-b");
app.clipboard_reader = || Some(String::from("stale-remote-one\nstale-remote-two"));
with_relay_home(home.path(), || {
app.paste_clipboard_into_terminal();
assert_eq!(
app.pending_terminal_paste.take().as_deref(),
Some(b"stale-remote-one\nstale-remote-two".as_slice())
);
app.session.relay_key = Some(String::from("testrelay"));
let pane_uid = app.terminals[app.active_terminal].uid();
let log = app.relay_log_path().expect("relay log path derivable");
app.paste_clipboard_into_terminal();
assert!(
app.pending_terminal_paste.is_none(),
"relay terminal paste must not paste stale remote clipboard"
);
assert!(
app.pending_remote_pulls.iter().any(|p| matches!(
p.kind,
RemotePullKind::Clipboard { terminal_uid } if terminal_uid == Some(pane_uid)
)),
"relay terminal paste must queue a clipboard pull targeting the requesting pane"
);
let written = std::fs::read_to_string(&log).expect("relay log written");
assert!(
written.contains("clipboard\t"),
"relay log must contain clipboard request, got {written:?}"
);
});
}
#[test]
fn relay_terminal_paste_targets_requesting_pane_and_cancels_when_closed() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let workspace = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
app.focus_pane(Pane::Terminal);
app.session.relay_key = Some(String::from("testrelay"));
let stage_reply = |inbox: &std::path::Path, req_id: &str, payload: &[u8]| {
let dir = inbox.join(req_id);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("clipboard.txt"), payload).unwrap();
std::fs::write(dir.join(".ok"), b"").unwrap();
};
with_relay_home(home.path(), || {
let inbox = app.relay_inbox_path().expect("relay inbox path derivable");
app.active_terminal = 0;
let pane0_uid = app.terminals[0].uid();
app.paste_clipboard_into_terminal();
let req_id = app.pending_remote_pulls.last().unwrap().request_id.clone();
app.active_terminal = 1;
stage_reply(&inbox, &req_id, b"hello-pane-0");
assert!(app.drain_remote_pulls());
assert_eq!(app.terminals[0].written_bytes_for_test(), b"hello-pane-0");
assert!(
app.terminals[1].written_bytes_for_test().is_empty(),
"pane 1 must not receive pane 0's relay paste"
);
app.active_terminal = 0;
app.paste_clipboard_into_terminal();
let req_id = app.pending_remote_pulls.last().unwrap().request_id.clone();
app.active_terminal = 1;
stage_reply(&inbox, &req_id, b"line-one\nline-two");
assert!(app.drain_remote_pulls());
assert_eq!(
app.pending_terminal_paste.as_deref(),
Some(b"line-one\nline-two".as_slice())
);
app.confirm_pending_terminal_paste(false);
assert_eq!(
app.terminals[0].written_bytes_for_test(),
b"hello-pane-0line-one\nline-two"
);
assert!(
app.terminals[1].written_bytes_for_test().is_empty(),
"pane 1 must not receive pane 0's confirmed multiline paste"
);
app.active_terminal = 0;
app.paste_clipboard_into_terminal();
let req_id = app.pending_remote_pulls.last().unwrap().request_id.clone();
app.terminals.retain(|t| t.uid() != pane0_uid);
app.active_terminal = 0; stage_reply(&inbox, &req_id, b"must-not-paste");
assert!(app.drain_remote_pulls());
assert!(
app.terminals[0].written_bytes_for_test().is_empty(),
"remaining pane must not receive a closed pane's paste"
);
assert!(
app.status.contains("requesting terminal closed"),
"expected closed-terminal status, got {:?}",
app.status
);
});
}
#[test]
fn session_origin_env_vars_are_read_only_in_host_session() {
let app_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/app");
let mut violations = Vec::new();
fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
for entry in std::fs::read_dir(dir).unwrap().flatten() {
let p = entry.path();
if p.is_dir() {
if p.file_name().is_some_and(|n| n == "tests") {
continue;
}
walk(&p, out);
} else if p.extension().is_some_and(|e| e == "rs") {
out.push(p);
}
}
}
let mut files = Vec::new();
walk(&app_dir, &mut files);
files.sort();
assert!(!files.is_empty());
let env_keys = [
"CROFT_RELAY_KEY",
"CROFT_SESSION_PERSISTENT",
"CROFT_REMOTE_AUTOUPDATE",
"CROFT_NO_UPDATE_CHECK",
"SSH_CONNECTION",
"SSH_TTY",
"SSH_CLIENT",
];
for file in files {
if file.ends_with("src/app/remote_sessions.rs") {
continue;
}
let text = std::fs::read_to_string(&file).unwrap();
for (idx, line) in text.lines().enumerate() {
let trimmed = line.trim_start();
if trimmed.starts_with("//") {
continue;
}
let calls_env =
trimmed.contains("env::var") && env_keys.iter().any(|k| trimmed.contains(k));
let calls_remote_fn =
trimmed.contains("running_over_ssh") || trimmed.contains("is_remote_session");
if calls_env || calls_remote_fn {
violations.push(format!("{}:{}: {}", file.display(), idx + 1, trimmed));
}
}
}
assert!(
violations.is_empty(),
"session-origin env reads must live in HostSession (src/app/remote_sessions.rs):\n{}",
violations.join("\n")
);
}
#[test]
fn host_session_drives_remote_media_and_update_refusals() {
let tmp = tempfile::tempdir().unwrap();
let media = tmp.path().join("clip.md");
std::fs::write(&media, "# clip\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.session.is_remote = true;
app.editor.open_pinned(&media).unwrap();
app.toggle_markdown_preview();
app.editor.markdown_preview.as_mut().unwrap().media = true;
app.run_command(crate::widgets::command_palette::Command::MediaOpenExternal);
assert!(
app.status.contains("Running remotely: copy"),
"MediaOpenExternal should read app.session.is_remote, got {:?}",
app.status
);
app.session.remote_autoupdate = true;
app.update_croft();
assert!(
app.status.contains("updated by the croft that launched it"),
"update_croft should read app.session.remote_autoupdate, got {:?}",
app.status
);
assert!(app.manual_update_check.is_none());
app.session.remote_autoupdate = false;
app.session.no_update_check = true;
app.update_croft();
assert!(
app.status.contains("CROFT_NO_UPDATE_CHECK"),
"update_croft should read app.session.no_update_check, got {:?}",
app.status
);
assert!(app.manual_update_check.is_none());
}
#[test]
fn web_links_route_through_one_opener() {
let app_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/app");
let mut violations = Vec::new();
fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
for entry in std::fs::read_dir(dir).unwrap().flatten() {
let p = entry.path();
if p.is_dir() {
if p.file_name().is_some_and(|n| n == "tests") {
continue;
}
walk(&p, out);
} else if p.extension().is_some_and(|e| e == "rs") {
out.push(p);
}
}
}
let mut files = Vec::new();
walk(&app_dir, &mut files);
files.sort();
for file in files {
if file.ends_with("src/app/commands.rs") || file.ends_with("src/app/bottom_panel.rs") {
continue;
}
let in_remote_sessions = file.ends_with("src/app/remote_sessions.rs");
let text = std::fs::read_to_string(&file).unwrap();
let mut current_fn = String::new();
for (idx, line) in text.lines().enumerate() {
let trimmed = line.trim_start();
if let Some(rest) = trimmed
.find("fn ")
.map(|pos| &trimmed[pos + 3..])
.filter(|_| !trimmed.starts_with("//"))
{
let name: String = rest
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
.collect();
if !name.is_empty() {
current_fn = name;
}
}
if trimmed.starts_with("//") || trimmed.starts_with("fn open_url(") {
continue;
}
if trimmed.contains("open_url(") && !trimmed.contains(".open_url(") {
if in_remote_sessions
&& matches!(
current_fn.as_str(),
"open_web_url" | "handle_port_toast_click"
)
{
continue;
}
violations.push(format!(
"{}:{} (in fn {}): {}",
file.display(),
idx + 1,
current_fn,
trimmed
));
}
}
}
assert!(
violations.is_empty(),
"web URL opens must go through App::open_web_url in src/app/remote_sessions.rs:\n{}",
violations.join("\n")
);
}
#[test]
fn open_web_url_validates_and_routes_consistently_across_callers() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(!app.try_open_url_for_user("javascript:alert(1)"));
assert_eq!(
app.status,
"Refused to open non-web link: javascript:alert(1)"
);
assert!(!app.try_open_url_for_user("https://example.com/\nboom"));
assert!(
app.status.starts_with("Refused to open malformed link:"),
"got {:?}",
app.status
);
assert!(app.try_open_url_for_user(" https://example.com/docs "));
assert_eq!(app.status, "Open https://example.com/docs");
with_relay_home(home.path(), || {
let mut local_app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(local_app.try_open_url_for_user("https://example.com/local"));
assert_eq!(local_app.status, "Open https://example.com/local");
assert!(local_app.pending_local_open.is_none());
app.session.is_remote = true;
app.session.relay_key = Some(String::from("web-opener-test"));
app.trust_local_browser = true;
let log_path = app.relay_log_path().unwrap();
assert!(!app.try_open_url_for_user("file:///etc/passwd"));
assert_eq!(
app.status,
"Refused to open non-web link: file:///etc/passwd"
);
app.pending_remote_pulls.clear();
app.open_ssh_learn_more();
assert_eq!(app.status, "Opening ssh_config(5) on your local Mac");
assert!(
app.pending_remote_pulls.iter().any(|p| {
p.kind == RemotePullKind::Open
&& p.src_display == "https://man.openbsd.org/ssh_config"
}),
"ssh_config docs should queue one relay open"
);
let relay_log = std::fs::read_to_string(&log_path).unwrap();
assert!(
relay_log.contains("open\t")
&& relay_log.contains("https://man.openbsd.org/ssh_config"),
"relay log should record the open request, got {relay_log:?}"
);
app.pending_remote_pulls.clear();
assert!(app.try_open_url_for_user("http://127.0.0.1:4321/app"));
assert!(
app.pending_remote_pulls
.iter()
.any(|p| matches!(p.kind, RemotePullKind::Forward { remote_port: 4321 })),
"loopback URL should forward port 4321 via relay"
);
});
}
#[test]
fn local_and_remote_render_byte_identical_frames_across_core_views() {
struct PlainHostGuard;
impl PlainHostGuard {
fn enter() -> Self {
crate::iterm2_inline::PLAIN_HOST_FRAMES.with(|f| f.set(true));
Self
}
}
impl Drop for PlainHostGuard {
fn drop(&mut self) {
crate::iterm2_inline::PLAIN_HOST_FRAMES.with(|f| f.set(false));
}
}
fn make_app(root: &std::path::Path, session: HostSession) -> App {
let mut app = App::new(root.to_path_buf()).unwrap();
app.color_depth = crate::color_depth::ColorDepth::TrueColor;
app.underline_colors = true;
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::None;
app.sixel_supported = false;
app.cell_pixel = None;
app.osk_auto = false;
app.status = String::from("Ready");
app.bottom_panel_tab = BottomPanelTab::Problems;
app.persistence_warning = remote_persistence_status(session.is_remote, session.persistent);
app.terminal_restore_respawns = session.is_remote;
app.session = session;
app.welcome
.set_test_notes(vec![crate::release_notes::ReleaseNote {
kind: crate::release_notes::NoteKind::Feature,
summary: "Local and remote share one renderer",
}]);
app
}
fn draw_buf(app: &mut App, width: u16, height: u16) -> ratatui::buffer::Buffer {
for _ in 0..8 {
let started = std::time::Instant::now();
let backend = ratatui::backend::TestBackend::new(width, height);
let mut terminal = ratatui::Terminal::new(backend).unwrap();
app.cursor_blink.poke();
terminal.draw(|f| app.render_for_terminal(f)).unwrap();
if started.elapsed() < super::cursor_blink::HALF && app.cursor_visible_phase() {
return terminal.backend().buffer().clone();
}
}
panic!("frame did not draw inside the visible blink half-period");
}
fn remote_persistent() -> HostSession {
HostSession {
is_remote: true,
relay_key: Some(String::from("parity-relay")),
persistent: true,
remote_autoupdate: true,
no_update_check: false,
}
}
fn pair(root: &std::path::Path) -> (App, App) {
(
make_app(root, HostSession::default()),
make_app(root, remote_persistent()),
)
}
let _plain = PlainHostGuard::enter();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("parity");
std::fs::create_dir_all(root.join("src")).unwrap();
let main_rs = root.join("src/main.rs");
std::fs::write(&main_rs, "fn main() {\n println!(\"hello\");\n}\n").unwrap();
std::fs::write(root.join("README.md"), "# parity\n").unwrap();
{
let (mut local, mut remote) = pair(&root);
assert_eq!(
draw_buf(&mut local, 120, 40),
draw_buf(&mut remote, 120, 40),
"welcome frame must match between local and persistent remote"
);
}
{
let (mut local, mut remote) = pair(&root);
assert!(local.open_file_at_launch(&main_rs));
assert!(remote.open_file_at_launch(&main_rs));
assert_eq!(
draw_buf(&mut local, 120, 40),
draw_buf(&mut remote, 120, 40),
"workbench frame must match between local and persistent remote"
);
}
{
let (mut local, mut remote) = pair(&root);
assert!(local.open_file_at_launch(&main_rs));
assert!(remote.open_file_at_launch(&main_rs));
for app in [&mut local, &mut remote] {
app.open_command_palette();
for ch in "toggle side".chars() {
app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
.unwrap();
}
}
assert_eq!(
draw_buf(&mut local, 120, 40),
draw_buf(&mut remote, 120, 40),
"command palette frame must match between local and persistent remote"
);
}
{
let (mut local, mut remote) = pair(&root);
for app in [&mut local, &mut remote] {
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the Go to File index to be built",
|| {
app.poll_file_finder_index();
app.file_finder_index.is_some()
},
);
app.run_command(crate::widgets::command_palette::Command::QuickOpen);
for ch in "main".chars() {
app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
.unwrap();
}
}
assert_eq!(
draw_buf(&mut local, 120, 40),
draw_buf(&mut remote, 120, 40),
"quick-open frame must match between local and persistent remote"
);
}
{
let (mut local, mut remote) = pair(&root);
local.run_command(crate::widgets::command_palette::Command::OpenSettingsEditor);
remote.run_command(crate::widgets::command_palette::Command::OpenSettingsEditor);
assert_eq!(
draw_buf(&mut local, 120, 40),
draw_buf(&mut remote, 120, 40),
"settings editor frame must match between local and persistent remote"
);
}
{
let (mut local, mut remote) = pair(&root);
assert!(local.open_file_at_launch(&main_rs));
assert!(remote.open_file_at_launch(&main_rs));
remote.session.persistent = false;
remote.persistence_warning =
remote_persistence_status(remote.session.is_remote, remote.session.persistent);
let local_buf = draw_buf(&mut local, 120, 40);
let remote_buf = draw_buf(&mut remote, 120, 40);
assert_ne!(
remote_buf, local_buf,
"non-persistent remote session must visibly differ from local workbench"
);
let status_row: String = (0..120).map(|x| remote_buf[(x, 39)].symbol()).collect();
assert!(
status_row.contains("Persistence off: install dtach"),
"status bar should show persistence warning, got {status_row:?}"
);
}
}
#[test]
fn intentional_remote_session_differences_follow_one_contract() {
use crate::widgets::ports::PortOrigin;
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("note.txt");
std::fs::write(&file, "hello\n").unwrap();
assert_eq!(remote_persistence_status(false, false), None);
assert_eq!(remote_persistence_status(false, true), None);
assert_eq!(remote_persistence_status(true, true), None);
assert_eq!(
remote_persistence_status(true, false),
Some("Persistence off: install dtach")
);
let mut local = App::new(tmp.path().to_path_buf()).unwrap();
local.session = HostSession::default();
local.drop_to_local_if_remote();
assert!(!local.drop_to_local);
assert!(!local.quit);
assert_eq!(
local.status,
"Drop to Local: this croft is not a remote session"
);
let mut remote = App::new(tmp.path().to_path_buf()).unwrap();
remote.session = HostSession {
is_remote: true,
relay_key: Some(String::from("contract-relay")),
persistent: true,
remote_autoupdate: true,
no_update_check: false,
};
remote.drop_to_local_if_remote();
assert!(remote.drop_to_local);
assert!(remote.quit);
remote.drop_to_local = false;
remote.quit = false;
assert!(remote.open_file_at_launch(&file));
assert!(!remote.open_tab_in_new_window(0));
assert_eq!(remote.status, "New Window: not available over SSH");
assert_eq!(local.port_origin(), PortOrigin::Local);
assert!(matches!(remote.port_origin(), PortOrigin::Remote(_)));
#[cfg(target_os = "macos")]
{
assert!(local.open_file_at_launch(&file));
let local_items = build_tab_context_menu_items(
0,
local.editor.tab_count(),
false,
Some(&file),
!local.session.is_remote && cfg!(target_os = "macos"),
false,
true,
);
let remote_items = build_tab_context_menu_items(
0,
remote.editor.tab_count(),
false,
Some(&file),
!remote.session.is_remote && cfg!(target_os = "macos"),
false,
true,
);
let has_finder = |items: &[MenuEntry]| {
items.iter().any(
|entry| matches!(entry, MenuEntry::Item { label, .. } if label.contains("Finder")),
)
};
assert!(has_finder(&local_items), "local macOS menu includes Finder");
assert!(!has_finder(&remote_items), "remote macOS menu omits Finder");
}
}