use super::*;
#[test]
fn terminal_warning_renders_inside_a_narrow_frame_without_panicking() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.pending_terminal_warning = true;
let backend = ratatui::backend::TestBackend::new(46, 12);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let backend = ratatui::backend::TestBackend::new(8, 3);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
}
#[test]
fn overlays_render_on_a_tiny_terminal_without_panicking() {
let tmp = tempfile::tempdir().unwrap();
let draw = |app: &mut App, w: u16, h: u16| {
let backend = ratatui::backend::TestBackend::new(w, h);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
};
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_command_palette();
draw(&mut app, 36, 20);
draw(&mut app, 80, 9);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_file_finder();
draw(&mut app, 36, 20);
draw(&mut app, 80, 9);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.pending_discard = Some(PendingDiscard {
root: std::path::PathBuf::new(),
rel_path: String::from("a.txt"),
untracked: false,
staged: false,
});
draw(&mut app, 45, 12);
draw(&mut app, 45, 5);
draw(&mut app, 8, 3);
}
#[test]
fn a_one_row_terminal_renders_without_panicking() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("data.csv"), "a,b\n1,2\n").unwrap();
let draw = |app: &mut App, w: u16, h: u16| {
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(w, h)).unwrap();
term.draw(|f| app.render(f)).unwrap();
};
let mut welcome = App::new(tmp.path().to_path_buf()).unwrap();
let mut csv = App::new(tmp.path().to_path_buf()).unwrap();
csv.editor.open(&tmp.path().join("data.csv")).unwrap();
for app in [&mut welcome, &mut csv] {
for w in [140, 100, 80, 40, 20] {
draw(app, w, 1);
}
}
}
#[test]
fn terminal_warning_swallows_a_key_and_dismisses_for_the_session() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.pending_terminal_warning = true;
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert!(
!app.pending_terminal_warning,
"any key should dismiss the nudge for this session"
);
}
#[test]
fn a_url_that_wraps_the_pane_edge_resolves_whole_from_any_of_its_rows() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let backend = ratatui::backend::TestBackend::new(80, 24);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let inner = app.terminals[0].last_inner;
let w = inner.width as usize;
let url = format!("https://example.com/oauth?state={}END", "y".repeat(w));
let chunk = format!("\r\nsee{} {url}\r\nnext line\r\n", "x".repeat(w - 10));
app.terminals[0].feed_bytes_for_test(chunk.as_bytes());
term.draw(|f| app.render(f)).unwrap();
let pane = &app.terminals[0];
let (_, head_row) = cell_carrying(pane, "https:").expect("the URL's first row");
let clicks = [
(inner.x + inner.width - 3, head_row),
(inner.x + 5, head_row + 1),
(inner.x + 1, head_row + 2),
];
for (col, row) in clicks {
let (text, idx) = pane.line_text_at(col, row).expect("inside the pane");
assert_eq!(
crate::port_detect::url_at(&text, idx).as_deref(),
Some(url.as_str()),
"click at ({col}, {row}) on {text:?}"
);
}
let (text, idx) = pane.line_text_at(inner.x + 1, head_row + 3).unwrap();
assert!(text.starts_with("next line"), "{text:?}");
assert_eq!(idx, 1);
assert!(crate::port_detect::url_at(&text, idx).is_none());
}
#[test]
fn cell_carrying_lands_inside_the_needle_not_at_the_start_of_its_row() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let area = app.terminals[0].last_area;
assert!(
area.width > 4 && area.height > 2,
"the terminal must be laid out, or the search finds nothing and the \
failure below blames a missing token rather than a missing pane"
);
app.terminals[0].feed_bytes_for_test(b"a prompt got here first\r\nbash-5.2$ tok_here\r\n");
term.draw(|f| app.render(f)).unwrap();
let (col, row) =
cell_carrying(&app.terminals[0], "tok_here").expect("the pane must show this test's token");
let (text, idx) = app.terminals[0]
.line_text_at(col, row)
.expect("the returned cell must map to a row and a char index");
let start = text
.find("tok_here")
.map(|b| text[..b].chars().count())
.expect("the row the search returned must carry the needle");
assert!(
(start..start + "tok_here".chars().count()).contains(&idx),
"the cell must fall inside the needle: row {text:?} put the cell at \
char {idx} and the needle spans {start}..{}",
start + "tok_here".chars().count()
);
assert!(
idx > 0,
"and this fixture must keep the needle off column 0, or a row \
predicate and a span predicate pick the same cell and the assertion \
above cannot fail"
);
}
#[test]
fn a_terminal_miss_does_not_blame_a_view_it_never_searched() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let bin = tmp.path().join("a.bin");
std::fs::write(&bin, [0u8, 1, 2, 3, 4, 5, 6, 7]).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.keymap = crate::keymap::Keymap::from_json(
r#"[{"key": "ctrl+click", "command": "mouse_open_link_at_click", "when": "terminal"}]"#,
);
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
app.editor.hex = Some(crate::hex::HexView::open(&bin).unwrap());
assert!(
app.editor.has_non_text_view(),
"precondition: a non-text view must be up, or the arm-wide status and \
the scoped one agree and this test cannot tell them apart"
);
app.terminals[0].feed_bytes_for_test(b"just some words\r\n");
term.draw(|f| app.render(f)).unwrap();
let area = app.terminals[0].last_area;
let (col, row) = (area.x + 2, area.y + 1);
assert!(
app.terminals[0].hyperlink_at_screen(col, row).is_none(),
"precondition: the cell must hold NO link, or this tests the hit path"
);
assert_eq!(
app.terminal_at_pos(col, row),
Some(0),
"precondition: and must be inside a terminal pane, or the editor \
lookup is legitimately the one that missed"
);
app.focus_pane(Pane::Terminal);
let mut ev = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ev.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ev);
assert_eq!(
app.status, "No link there",
"a miss in a TERMINAL pane must not name the editor's view: that \
lookup was short-circuited and never searched"
);
}
#[test]
fn a_terminal_link_binding_is_not_refused_for_an_editor_side_reason() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let bin = tmp.path().join("a.bin");
std::fs::write(&bin, [0u8, 1, 2, 3, 4, 5, 6, 7]).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.keymap = crate::keymap::Keymap::from_json(
r#"[{"key": "ctrl+click", "command": "mouse_open_link_at_click", "when": "terminal"}]"#,
);
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
app.editor.hex = Some(crate::hex::HexView::open(&bin).unwrap());
assert!(
app.editor.has_non_text_view(),
"precondition: the editor must be on a non-text view, or the guard \
never fires and this test is about the ordinary path"
);
app.terminals[0].feed_bytes_for_test(b"a prompt got here first\r\n");
app.terminals[0]
.feed_bytes_for_test(b"\x1b]8;;mailto:decoy@example.com\x1b\\decoy\x1b]8;;\x1b\\\r\n");
app.terminals[0]
.feed_bytes_for_test(b"\x1b]8;;mailto:t@example.com\x1b\\link\x1b]8;;\x1b\\\r\n");
term.draw(|f| app.render(f)).unwrap();
let (col, row) = cell_with_link(&app.terminals[0], "mailto:t@example.com").expect(
"precondition: the click must land on the terminal link, or a refusal \
proves nothing about which branch refused it",
);
app.focus_pane(Pane::Terminal);
let mut ev = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ev.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ev);
assert_eq!(
app.status, "Refused to open non-web link: mailto:t@example.com",
"a TERMINAL-region link binding must reach the terminal helpers even \
while the EDITOR shows a hex preview of an unrelated file: the guard's \
reason does not apply to a pane it does not read"
);
}
#[test]
fn a_mouse_tracking_child_keeps_the_pointer_from_a_bound_wheel() {
use crossterm::event::MouseEventKind;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.keymap = crate::keymap::Keymap::from_json(
r#"[{"key": "ctrl+wheel_up", "command": "quick_open", "when": "terminal"}]"#,
);
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h");
term.draw(|f| app.render(f)).unwrap();
assert!(
app.terminals[0].mouse_reporting(),
"the child is tracking the mouse"
);
let area = app.terminals[0].last_area;
let (col, row) = (area.x + 2, area.y + 1);
assert!(
app.terminals[0].cell_at(col, row).is_some(),
"the wheel must land on a real grid cell"
);
let mut ev = mouse(MouseEventKind::ScrollUp, col, row);
ev.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ev);
assert!(
app.file_finder.is_none(),
"croft FORWARDS the wheel to a tracking child (all three `report_mouse` \
call sites construct WheelUp/WheelDown), so the child really does own \
this gesture and the binding must not fire"
);
}
#[test]
fn holding_shift_takes_the_pointer_back_from_a_tracking_child() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.keymap = crate::keymap::Keymap::from_json(
r#"[{"key": "ctrl+shift+click", "command": "quick_open", "when": "terminal"}]"#,
);
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h");
term.draw(|f| app.render(f)).unwrap();
assert!(app.terminals[0].mouse_reporting(), "the child is tracking");
let area = app.terminals[0].last_area;
let mut shifted = mouse(
MouseEventKind::Down(MouseButton::Left),
area.x + 2,
area.y + 1,
);
shifted.modifiers = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
app.handle_mouse(shifted);
assert!(
app.file_finder.is_some(),
"Shift takes the pointer back and the ctrl+shift+click row fires"
);
}
#[test]
fn the_swallow_guard_reads_the_clicked_terminal_not_the_active_one() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.keymap = crate::keymap::Keymap::from_json(
r#"[{"key": "ctrl+double_click", "command": "toggle_word_wrap", "when": "terminal"}]"#,
);
app.split_terminal().unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert_eq!(app.terminals.len(), 2, "two panes are visible");
app.terminals[0]
.feed_bytes_for_test(b"\x1b]8;;mailto:decoy@example.com\x1b\\decoy\x1b]8;;\x1b\\\r\n");
app.terminals[0]
.feed_bytes_for_test(b"\x1b]8;;mailto:split@example.com\x1b\\split-link\x1b]8;;\x1b\\\r\n");
app.active_terminal = 1;
term.draw(|f| app.render(f)).unwrap();
let (col, row) = cell_with_link(&app.terminals[0], "mailto:split@example.com")
.expect("pane 0 must carry the link somewhere, or the built-in has nothing to act on");
assert_eq!(
app.active_terminal, 1,
"pane 1 must be ACTIVE while the click lands in pane 0, or the \
clicked-vs-active distinction this test exists for does not arise"
);
let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ctrl.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ctrl);
assert_eq!(
app.status, "Refused to open non-web link: mailto:split@example.com",
"the prefix click must defer to the built-in, which opens the link in \
the CLICKED pane. Reading the ACTIVE pane finds nothing there, \
swallows the click, and the link never opens"
);
}
#[test]
fn a_double_click_prefix_over_a_mouse_tracking_child_leaves_the_builtin_alone() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.keymap = crate::keymap::Keymap::from_json(
r#"[{"key": "ctrl+double_click", "command": "toggle_word_wrap", "when": "terminal"}]"#,
);
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let area = app.terminals[0].last_area;
assert!(
area.width > 4 && area.height > 2,
"terminal must be laid out"
);
app.terminals[0].feed_bytes_for_test(b"a prompt got here first\r\n");
app.terminals[0].feed_bytes_for_test(
b"\x1b]8;;mailto:decoy@example.com\x1b\\decoy\x1b]8;;\x1b\\\r\n\x1b]8;;mailto:x@example.com\x1b\\link\x1b]8;;\x1b\\\r\n",
);
let (col, row) = cell_with_link(&app.terminals[0], "mailto:x@example.com").expect(
"the cell must carry THIS test's OSC 8 link, or the built-in has nothing \
to act on and this test cannot distinguish the two branches",
);
app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h");
assert!(
app.terminals[0].mouse_reporting(),
"the child must be tracking, or `child_owns_pointer` is false and this \
test proves nothing about the guard"
);
let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ctrl.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ctrl);
assert_eq!(
app.status, "Refused to open non-web link: mailto:x@example.com",
"a double-click PREFIX over a mouse-tracking child must fall through to \
the built-in: the Cmd/Ctrl link-open runs BEFORE the press is \
forwarded, so swallowing the click would cost the user the link. \
Expected the refusal from the built-in link handler"
);
}
#[test]
fn terminal_decoration_dot_click_is_not_hijacked_by_the_sidebar_splitter() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let script = "printf '\\033]133;A\\007$ \\033]133;B\\007cmd\\n\\033]133;C\\007out\\n\\033]133;D;0\\007'; sleep 30";
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), script.into()],
tmp.path(),
)
.unwrap();
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the shell to emit a decoration mark",
|| !app.terminals[0].command_decorations().is_empty(),
);
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let deco = app.terminals[0].command_decorations()[0];
let pane = app.terminals[0].last_area;
let inner_y = app.terminals[0].last_inner.y;
let (col, row) = (pane.x, inner_y + u16::try_from(deco.line).unwrap());
assert_eq!(
app.terminals[0].decoration_at_screen(col, row),
Some(deco),
"the dot cell must hit-test to the decoration"
);
let x = app
.sidebar_splitter_x
.expect("sidebar shown, so the splitter seam exists");
assert!(
col == x || col == x.saturating_sub(1),
"the dot column ({col}) must lie in the splitter grab zone ({x})"
);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert!(
!matches!(app.gesture, Some(Gesture::Splitter(_))),
"pressing a decoration dot must not start a sidebar resize"
);
assert!(
app.context_menu.is_some(),
"pressing a decoration dot must open the command's action menu"
);
}
#[test]
fn paste_while_terminal_focused_does_not_leak_into_search_box() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Search);
app.search.query = String::from("hello");
app.search.clear_selection();
app.focus_pane(Pane::Terminal);
app.handle_paste("machi");
assert_eq!(
app.search.query, "hello",
"a bracketed paste must NOT append to the search box when the terminal is focused, even though the Search panel is visible"
);
assert!(
matches!(app.focus, Pane::Terminal),
"focus must stay on the terminal"
);
}
#[test]
fn cmd_f_opens_terminal_find_and_captures_typing() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
assert!(app.terminal_find.is_none(), "find starts closed");
app.handle_terminal_key(key(KeyCode::Char('f'), KeyModifiers::SUPER));
assert!(app.terminal_find.is_some(), "Cmd+F must open the find bar");
app.handle_terminal_key(key(KeyCode::Char('l'), KeyModifiers::NONE));
app.handle_terminal_key(key(KeyCode::Char('s'), KeyModifiers::NONE));
assert_eq!(
app.terminal_find.as_ref().unwrap().query,
"ls",
"printable keys must append to the find query"
);
app.handle_terminal_key(key(KeyCode::Backspace, KeyModifiers::NONE));
assert_eq!(app.terminal_find.as_ref().unwrap().query, "l");
app.handle_terminal_key(key(KeyCode::Esc, KeyModifiers::NONE));
assert!(app.terminal_find.is_none(), "Esc must close the find bar");
}
#[cfg(target_os = "macos")]
#[test]
fn ctrl_f_reaches_the_terminal_child_on_macos() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.handle_terminal_key(key(KeyCode::Char('f'), KeyModifiers::CONTROL));
assert!(
app.terminal_find.is_none(),
"Ctrl+F must not open find on macOS"
);
let written = app.terminals[0].written_bytes_for_test();
assert!(
written.ends_with(&[0x06]),
"Ctrl+F must be encoded to the child, wrote {written:?}"
);
}
fn run_selected_text(app: &mut App) -> String {
let cmd = crate::widgets::command_palette::Command::from_id("run_selected_text")
.expect("there is a Run Selected Text command");
let before = app.terminals[app.active_terminal]
.written_bytes_for_test()
.len();
app.run_command(cmd);
let written = app.terminals[app.active_terminal].written_bytes_for_test();
String::from_utf8_lossy(&written[before..]).into_owned()
}
fn unbracketed(sent: &str) -> String {
sent.replace("\x1b[200~", "").replace("\x1b[201~", "")
}
#[test]
fn run_selected_text_sends_the_selection_and_enter_to_the_terminal() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(
tmp.path(),
"explore.py",
"import csv\nrows = [1, 2]\ntotal = sum(rows)\nprint(total)\n",
);
app.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: (2, 0),
head: (3, 12),
});
assert_eq!(
unbracketed(&run_selected_text(&mut app)),
"total = sum(rows)\nprint(total)\r"
);
assert!(app.focus == Pane::Editor, "focus stays in the editor");
assert!(app.show_terminal, "the terminal is shown");
}
#[test]
fn run_selected_text_skips_the_multiline_paste_confirm() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "explore.py", "a = 1\nb = 2\n");
app.multiline_paste_warning = crate::prefs::MultilinePasteWarning::Always;
app.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: (0, 0),
head: (1, 5),
});
assert_eq!(unbracketed(&run_selected_text(&mut app)), "a = 1\nb = 2\r");
assert!(app.pending_terminal_paste.is_none(), "nothing held");
}
#[test]
fn run_selected_text_brackets_the_block_when_the_pane_asked_for_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.py", "a = 1\nb = 2\n");
app.terminals[app.active_terminal].feed_bytes_for_test(b"\x1b[?2004h");
app.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: (0, 0),
head: (1, 5),
});
assert_eq!(
run_selected_text(&mut app),
"\x1b[200~a = 1\nb = 2\x1b[201~\r"
);
}
#[test]
fn run_selected_text_without_a_selection_sends_the_line_and_steps_on() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.py", "a = 1\n\n\nb = 2\n");
assert_eq!(unbracketed(&run_selected_text(&mut app)), "a = 1\r");
assert_eq!(app.editor.cursor_row, 3, "blank lines are stepped over");
assert_eq!(unbracketed(&run_selected_text(&mut app)), "b = 2\r");
}
#[test]
fn run_selected_text_sends_nothing_for_a_blank_line() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.py", "a = 1\n");
app.editor.cursor_row = 1;
assert_eq!(unbracketed(&run_selected_text(&mut app)), "");
}
#[test]
fn cmd_opt_up_parks_the_previous_prompt_mark_at_the_viewport_top() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let script = "printf '\\033]133;A\\007PROMPT\\n'; i=0; while [ $i -lt 40 ]; do echo filler-$i; i=$((i+1)); done";
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), script.into()],
tmp.path(),
)
.unwrap();
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the prompt mark, the filler output and the exit footer",
|| {
let (lines, _) = app.terminals[0].grid_lines();
!app.terminals[0].prompt_lines().is_empty()
&& lines.iter().any(|l| l.contains("filler-39"))
&& lines.iter().any(|l| l.contains("[Process exited]"))
},
);
app.focus_pane(Pane::Terminal);
assert_eq!(
app.terminal().viewport_top_line(),
0,
"starts at the live bottom"
);
app.handle_terminal_key(key(KeyCode::Up, KeyModifiers::SUPER | KeyModifiers::ALT));
let mark = app.terminal().prompt_lines()[0];
assert!(mark < 0, "the mark scrolled into history");
assert_eq!(
app.terminal().viewport_top_line(),
mark,
"Cmd+Opt+Up must park the previous prompt mark at the viewport top"
);
app.handle_terminal_key(key(KeyCode::Down, KeyModifiers::SUPER | KeyModifiers::ALT));
assert!(
app.status.contains("No next command"),
"status was: {}",
app.status
);
}
#[test]
fn cmd_opt_down_at_the_last_mark_stays_put_while_output_streams() {
use alacritty_terminal::vte::ansi::{Processor, StdSyncHandler};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
const STREAMED_MAX: usize = 2000;
const PRESSES: usize = 50;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sleep",
&[String::from("60")],
tmp.path(),
)
.unwrap();
let grid = app.terminals[0].grid_lock_for_test();
let paint = |bytes: &[u8]| Processor::<StdSyncHandler>::new().advance(&mut *grid.lock(), bytes);
app.terminals[0].push_mark_for_test(crate::shell_integration::OscEvent::PromptStart, 0);
paint(b"PROMPT\r\n");
for i in 0..40 {
paint(format!("filler-{i}\r\n").as_bytes());
}
app.focus_pane(Pane::Terminal);
app.handle_terminal_key(key(KeyCode::Up, KeyModifiers::SUPER | KeyModifiers::ALT));
let mark = app.terminal().prompt_lines()[0];
assert!(mark < 0, "the mark scrolled into history");
assert_eq!(app.terminal().viewport_top_line(), mark);
let armed = Arc::new(AtomicBool::new(false));
let idle = Arc::new(AtomicBool::new(true));
let stop = Arc::new(AtomicBool::new(false));
let writer = {
let (grid, armed, idle, stop) = (grid.clone(), armed.clone(), idle.clone(), stop.clone());
std::thread::spawn(move || {
let mut p = Processor::<StdSyncHandler>::new();
let mut n = 0;
while !stop.load(SeqCst) {
if armed.load(SeqCst) && n < STREAMED_MAX {
p.advance(&mut *grid.lock(), format!("streamed-{n}\r\n").as_bytes());
n += 1;
} else {
idle.store(true, SeqCst);
std::thread::yield_now();
}
}
})
};
let mut failure = None;
for press in 0..PRESSES {
app.status.clear();
armed.store(true, SeqCst);
app.handle_terminal_key(key(KeyCode::Down, KeyModifiers::SUPER | KeyModifiers::ALT));
armed.store(false, SeqCst);
idle.store(false, SeqCst);
while !idle.load(SeqCst) {
std::thread::yield_now();
}
let mark = app.terminal().prompt_lines()[0];
let top = app.terminal().viewport_top_line();
if !app.status.contains("No next command") || top != mark {
failure = Some(format!(
"press {press}: status {:?}, view top {top}, mark {mark}",
app.status
));
break;
}
}
stop.store(true, SeqCst);
writer.join().unwrap();
if let Some(failure) = failure {
panic!("Cmd+Opt+Down at the last mark must say so and stay put: {failure}");
}
}
#[test]
fn ctrl_shift_space_quick_select_labels_matches_and_a_label_commits() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let script = "echo see-https://example.com/quick; echo sha de40bdf12ab34; sleep 60";
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from(script)],
tmp.path(),
)
.unwrap();
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the hash on its own echoed row as well as in the run-label header",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.filter(|l| l.contains("de40bdf12ab34"))
.count()
>= 2
},
);
app.focus_pane(Pane::Terminal);
assert!(app.terminal_quick_select.is_none(), "starts off");
app.handle_terminal_key(key(
KeyCode::Char(' '),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
));
let state = app
.terminal_quick_select
.as_ref()
.expect("Ctrl+Shift+Space must enter quick-select");
assert!(
state
.hints
.iter()
.any(|h| h.text == "https://example.com/quick"),
"the URL must be labelled"
);
let sha = state.hints.last().expect("hints must not be empty");
assert_eq!(
(sha.text.as_str(), sha.label.as_str()),
("de40bdf12ab34", "a"),
"the bottom-most match gets the cheapest label; hints were: {:?}",
state
.hints
.iter()
.map(|h| (h.line, h.text.as_str(), h.label.as_str()))
.collect::<Vec<_>>()
);
app.handle_terminal_key(key(KeyCode::Esc, KeyModifiers::NONE));
assert!(app.terminal_quick_select.is_none(), "Esc must cancel");
app.handle_terminal_key(key(
KeyCode::Char(' '),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
));
let label = app
.terminal_quick_select
.as_ref()
.unwrap()
.hints
.iter()
.find(|h| h.text == "de40bdf12ab34")
.unwrap()
.label
.clone();
for c in label.chars() {
app.handle_terminal_key(key(KeyCode::Char(c), KeyModifiers::NONE));
}
assert!(
app.terminal_quick_select.is_none(),
"committing a label must close quick-select"
);
assert!(
app.status.contains("Copied"),
"commit must report the copy, status was: {}",
app.status
);
}
#[test]
fn shift_pageup_pages_the_scrollback_and_shift_end_snaps_back() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let script = "i=0; while [ $i -lt 80 ]; do echo page-$i; i=$((i+1)); done; sleep 60";
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from(script)],
tmp.path(),
)
.unwrap();
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the filler output",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("page-79"))
},
);
app.focus_pane(Pane::Terminal);
let at_bottom = app.terminal().viewport_top_line();
app.handle_terminal_key(key(KeyCode::PageUp, KeyModifiers::SHIFT));
let paged = app.terminal().viewport_top_line();
assert!(
paged < at_bottom,
"Shift+PageUp must scroll into history: {paged} vs {at_bottom}"
);
app.handle_terminal_key(key(KeyCode::Home, KeyModifiers::SHIFT));
let top = app.terminal().viewport_top_line();
assert!(
top < paged,
"Shift+Home must jump to the oldest line: {top} vs {paged}"
);
app.handle_terminal_key(key(KeyCode::End, KeyModifiers::SHIFT));
assert_eq!(
app.terminal().viewport_top_line(),
at_bottom,
"Shift+End must snap back to the live bottom"
);
}
#[test]
fn copy_on_select_puts_a_finished_terminal_selection_on_the_clipboard() {
let tmp = 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.copy_on_select = true;
app.focus_pane(Pane::Terminal);
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let inner = app.terminal().last_inner;
app.terminal_mut().start_selection_at(inner.x, inner.y);
app.terminal_mut().extend_selection_to(inner.x + 8, inner.y);
let expected = app.terminal().selection_text();
assert!(!expected.is_empty(), "selection must cover some pane text");
app.handle_mouse(mouse(
MouseEventKind::Up(MouseButton::Left),
inner.x + 8,
inner.y,
));
let clip = crate::clipboard::read_string().unwrap_or_default();
assert_eq!(
clip, expected,
"finishing the drag must copy the selection when copy_on_select is on"
);
}
#[test]
fn pane_inline_image_overlay_anchors_hides_when_scrolled_off_and_returns() {
use base64::Engine;
let mut png_buf = Vec::new();
image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]))
.write_to(
&mut std::io::Cursor::new(&mut png_buf),
image::ImageFormat::Png,
)
.expect("encode test png");
let png: &[u8] = &png_buf;
let b64 = base64::engine::general_purpose::STANDARD.encode(png);
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::ITerm2;
app.cell_pixel = Some((10, 20));
let script = format!(
"printf '\\033]1337;File=inline=1:{b64}\\007\\n'; i=0; while [ $i -lt 80 ]; do echo fill-$i; i=$((i+1)); done; sleep 60"
);
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), script],
tmp.path(),
)
.unwrap();
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the image and its filler",
|| {
!app.terminals[0].pane_images().is_empty()
&& app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("fill-79"))
},
);
app.focus_pane(Pane::Terminal);
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert!(
app.terminal_image_payload().is_none(),
"an off-screen anchor must hide the picture"
);
app.terminal_mut().scroll_to_top();
term.draw(|f| app.render(f)).unwrap();
let (osc, layout) = app
.terminal_image_payload()
.expect("a visible anchor must produce an overlay payload");
assert!(
osc.contains("1337;File=inline=1"),
"the payload must be a re-baked OSC 1337 image"
);
let inner = app.terminal().last_inner;
assert_eq!(layout.pane, 0);
assert!(
layout.cell_y >= inner.y && layout.cell_y < inner.y + inner.height,
"the picture must anchor inside the pane: {layout:?} vs {inner:?}"
);
assert!(layout.cell_w >= 1 && layout.cell_h >= 1);
app.mark_terminal_image_displayed();
app.terminal_mut().reset_scrollback();
term.draw(|f| app.render(f)).unwrap();
assert!(app.terminal_image_payload().is_none());
assert!(
app.consume_terminal_image_clear(),
"hiding a displayed picture must arm the clear latch"
);
}
#[test]
fn quick_select_paints_gold_labels_and_broadcast_paints_modal_and_pills() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let script = "echo grab https://example.com/paint; sleep 60";
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from(script)],
tmp.path(),
)
.unwrap();
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the URL on its own echoed row as well as in the run-label header",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.filter(|l| l.contains("example.com/paint"))
.count()
>= 2
},
);
app.focus_pane(Pane::Terminal);
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
app.handle_terminal_key(key(
KeyCode::Char(' '),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
));
assert!(app.terminal_quick_select.is_some());
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let gold = Color::Rgb(0xff, 0xd7, 0x4a);
let label_cell = (0..buf.area.height)
.flat_map(|y| (0..buf.area.width).map(move |x| (x, y)))
.find(|&(x, y)| buf[(x, y)].bg == gold && buf[(x, y)].fg == Color::Black);
assert!(
label_cell.is_some(),
"a quick-select label must paint black-on-gold somewhere in the pane"
);
app.handle_terminal_key(key(KeyCode::Esc, KeyModifiers::NONE));
app.terminals.push(
crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from("sleep 60")],
tmp.path(),
)
.unwrap(),
);
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('i'), KeyModifiers::NONE)));
term.draw(|f| app.render(f)).unwrap();
assert!(
screen_char_rows(&term)
.iter()
.any(|r| r.contains("BROADCAST INPUT TO ALL PANES?")),
"the confirm modal must be painted while pending"
);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
term.draw(|f| app.render(f)).unwrap();
let marks = screen_char_rows(&term)
.iter()
.map(|r| r.matches('\u{21f6}').count())
.sum::<usize>();
assert_eq!(
marks, 2,
"both receiving panes must wear the ⇶ broadcast pill"
);
}
#[test]
fn cmd_k_i_broadcasts_input_to_every_pane_with_confirm_and_auto_off() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mk = || {
crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from("read x; echo got-$x; sleep 30"),
],
tmp.path(),
)
.unwrap()
};
app.terminals[0] = mk();
app.terminals.push(mk());
app.active_terminal = 0;
app.focus_pane(Pane::Terminal);
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('i'), KeyModifiers::NONE)));
assert!(
app.pending_broadcast_enable,
"enabling broadcast must be gated on a confirm popup"
);
assert!(!app.broadcast_input);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(app.broadcast_input, "Enter must confirm");
assert!(!app.pending_broadcast_enable);
for c in ['h', 'i'] {
app.handle_terminal_key(key(KeyCode::Char(c), KeyModifiers::NONE));
}
app.handle_terminal_key(key(KeyCode::Enter, KeyModifiers::NONE));
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the broadcast input to reach every pane",
|| {
app.terminals
.iter()
.all(|t| t.grid_lines().0.iter().any(|l| l.contains("got-hi")))
},
);
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('I'), KeyModifiers::SHIFT)));
assert!(app.terminals[0].broadcast_excluded);
assert!(app.close_active_terminal());
assert!(
!app.broadcast_input,
"broadcast must switch off when only one pane remains"
);
}
#[test]
fn trigger_hits_surface_in_the_status_bar_via_the_drain_tick() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.triggers = std::sync::Arc::new(crate::triggers::TriggerSet::from_json(
r#"[ { "regex": "BUILD (\\w+)", "action": "notify", "message": "build: \\1" } ]"#,
));
let script = "read x; echo BUILD OK; sleep 30";
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from(script)],
tmp.path(),
)
.unwrap();
app.drain_terminal_bells();
app.terminals[0].write_input(b"\n");
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the trigger to surface in the status line",
|| {
app.drain_terminal_bells();
app.status.starts_with("Trigger in")
},
);
assert!(
app.status.contains("build: OK"),
"interpolated message expected, status: {}",
app.status
);
}
#[test]
fn leaving_the_terminal_closes_its_find_bar() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.handle_terminal_key(key(KeyCode::Char('f'), KeyModifiers::SUPER));
assert!(app.terminal_find.is_some());
app.focus_pane(Pane::Editor);
assert!(
app.terminal_find.is_none(),
"moving focus off the terminal must close the find bar so no stale highlight lingers"
);
}
#[test]
fn paste_into_input_prompt_fills_it_not_the_focused_pane() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.input_prompt = Some(crate::widgets::input_prompt::InputPrompt::new(
crate::widgets::input_prompt::InputPurpose::McpArg {
command_id: String::from("fetch.url"),
},
"Web: Fetch URL as Markdown",
"URL to fetch",
));
app.handle_paste("https://example.com/x");
assert_eq!(
app.input_prompt.as_ref().unwrap().value,
"https://example.com/x",
"a paste while the input prompt is open must fill the prompt, not leak to the focused pane"
);
}
#[test]
fn paste_while_terminal_focused_does_not_leak_into_editor_find_bar() {
let mut app = editor_app_with_lines(&["alpha beta", "alpha gamma"]);
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
assert!(
app.editor_find.is_some(),
"precondition: Cmd+F opens the inline editor Find bar"
);
let query_before = app
.editor_find
.as_ref()
.map(|s| s.query.clone())
.unwrap_or_default();
app.focus_pane(Pane::Terminal);
app.handle_paste("ls -la");
assert_eq!(
app.editor_find.as_ref().map(|s| s.query.clone()),
Some(query_before),
"a paste must NOT append to the editor Find query when the terminal is focused, even though the find bar is still open"
);
assert!(
matches!(app.focus, Pane::Terminal),
"focus must stay on the terminal"
);
}
#[test]
fn a_cell_pixel_size_needs_the_terminal_to_report_pixels() {
assert_eq!(cell_pixel_of(100, 40, 800, 640), Some((8, 16)));
assert_eq!(cell_pixel_of(100, 40, 0, 0), None);
assert_eq!(cell_pixel_of(0, 40, 800, 640), None);
}
#[test]
fn modified_terminal_keys_keep_their_modifiers() {
let k = |c, m| key_to_bytes(key(c, m), false);
assert_eq!(k(KeyCode::Backspace, KeyModifiers::ALT), b"\x1b\x7f");
assert_eq!(k(KeyCode::Char(' '), KeyModifiers::CONTROL), vec![0x00]);
assert_eq!(k(KeyCode::Char('/'), KeyModifiers::CONTROL), vec![0x1f]);
assert_eq!(
k(
KeyCode::Char('a'),
KeyModifiers::CONTROL | KeyModifiers::ALT
),
b"\x1b\x01"
);
assert_eq!(k(KeyCode::Left, KeyModifiers::CONTROL), b"\x1b[1;5D");
assert_eq!(k(KeyCode::Right, KeyModifiers::SHIFT), b"\x1b[1;2C");
assert_eq!(k(KeyCode::Home, KeyModifiers::CONTROL), b"\x1b[1;5H");
assert_eq!(k(KeyCode::Delete, KeyModifiers::CONTROL), b"\x1b[3;5~");
assert_eq!(k(KeyCode::Left, KeyModifiers::ALT), b"\x1bb");
}
#[test]
fn key_to_bytes_arrows() {
assert_eq!(
key_to_bytes(key(KeyCode::Up, KeyModifiers::NONE), false),
b"\x1b[A"
);
assert_eq!(
key_to_bytes(key(KeyCode::Down, KeyModifiers::NONE), false),
b"\x1b[B"
);
assert_eq!(
key_to_bytes(key(KeyCode::Right, KeyModifiers::NONE), false),
b"\x1b[C"
);
assert_eq!(
key_to_bytes(key(KeyCode::Left, KeyModifiers::NONE), false),
b"\x1b[D"
);
}
#[test]
fn key_to_bytes_arrows_in_app_cursor_mode_use_ss3() {
for (code, seq) in [
(KeyCode::Up, b"\x1bOA"),
(KeyCode::Down, b"\x1bOB"),
(KeyCode::Right, b"\x1bOC"),
(KeyCode::Left, b"\x1bOD"),
(KeyCode::Home, b"\x1bOH"),
(KeyCode::End, b"\x1bOF"),
] {
assert_eq!(key_to_bytes(key(code, KeyModifiers::NONE), true), seq);
}
assert_eq!(
key_to_bytes(key(KeyCode::PageUp, KeyModifiers::NONE), true),
b"\x1b[5~"
);
assert_eq!(
key_to_bytes(key(KeyCode::Enter, KeyModifiers::NONE), true),
b"\r"
);
}
#[test]
fn key_to_bytes_enter_tab_backspace() {
assert_eq!(
key_to_bytes(key(KeyCode::Enter, KeyModifiers::NONE), false),
b"\r"
);
assert_eq!(
key_to_bytes(key(KeyCode::Tab, KeyModifiers::NONE), false),
b"\t"
);
assert_eq!(
key_to_bytes(key(KeyCode::Backspace, KeyModifiers::NONE), false),
&[0x7f]
);
}
#[test]
fn key_to_bytes_ctrl_letter_maps_to_control_byte() {
let bytes = key_to_bytes(key(KeyCode::Char('c'), KeyModifiers::CONTROL), false);
assert_eq!(bytes, vec![0x03]);
let bytes = key_to_bytes(key(KeyCode::Char('a'), KeyModifiers::CONTROL), false);
assert_eq!(bytes, vec![0x01]);
let bytes = key_to_bytes(key(KeyCode::Char('z'), KeyModifiers::CONTROL), false);
assert_eq!(bytes, vec![0x1a]);
}
#[test]
fn key_to_bytes_alt_letter_prefixes_esc() {
let bytes = key_to_bytes(key(KeyCode::Char('x'), KeyModifiers::ALT), false);
assert_eq!(bytes, vec![0x1b, b'x']);
}
#[test]
fn key_to_bytes_alt_left_emits_esc_b_for_readline_backward_word() {
let bytes = key_to_bytes(key(KeyCode::Left, KeyModifiers::ALT), false);
assert_eq!(
bytes, b"\x1bb",
"Option+Left in the terminal must send ESC b so zsh/bash readline runs backward-word"
);
}
#[test]
fn key_to_bytes_alt_right_emits_esc_f_for_readline_forward_word() {
let bytes = key_to_bytes(key(KeyCode::Right, KeyModifiers::ALT), false);
assert_eq!(
bytes, b"\x1bf",
"Option+Right in the terminal must send ESC f so zsh/bash readline runs forward-word"
);
}
#[test]
fn key_to_bytes_plain_arrows_unchanged_when_alt_not_held() {
assert_eq!(
key_to_bytes(key(KeyCode::Left, KeyModifiers::NONE), false),
b"\x1b[D"
);
assert_eq!(
key_to_bytes(key(KeyCode::Right, KeyModifiers::NONE), false),
b"\x1b[C"
);
}
#[test]
fn key_to_bytes_plain_char_utf8() {
assert_eq!(
key_to_bytes(key(KeyCode::Char('a'), KeyModifiers::NONE), false),
b"a"
);
assert_eq!(
key_to_bytes(key(KeyCode::Char('é'), KeyModifiers::NONE), false),
"é".as_bytes()
);
}
#[test]
fn key_to_bytes_function_keys() {
assert_eq!(
key_to_bytes(key(KeyCode::F(1), KeyModifiers::NONE), false),
b"\x1bOP"
);
assert_eq!(
key_to_bytes(key(KeyCode::F(5), KeyModifiers::NONE), false),
b"\x1b[15~"
);
assert_eq!(
key_to_bytes(key(KeyCode::F(12), KeyModifiers::NONE), false),
b"\x1b[24~"
);
}
#[test]
fn key_to_bytes_unknown_returns_empty() {
assert!(key_to_bytes(key(KeyCode::CapsLock, KeyModifiers::NONE), false).is_empty());
}
#[test]
fn cmd_w_and_ctrl_shift_w_close_terminal_but_plain_ctrl_w_does_not() {
assert!(is_terminal_close_key(key(
KeyCode::Char('w'),
KeyModifiers::SUPER
)));
assert!(is_terminal_close_key(key(
KeyCode::Char('w'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT
)));
assert!(!is_terminal_close_key(key(
KeyCode::Char('w'),
KeyModifiers::CONTROL
)));
}
#[test]
fn ctrl_shift_c_is_recognized_as_terminal_copy() {
let mods = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
assert!(is_terminal_copy_key(key(KeyCode::Char('C'), mods)));
}
#[test]
fn cmd_c_is_recognized_as_terminal_copy() {
assert!(is_terminal_copy_key(key(
KeyCode::Char('c'),
KeyModifiers::SUPER
)));
}
#[test]
fn plain_ctrl_c_is_not_terminal_copy() {
assert!(!is_terminal_copy_key(key(
KeyCode::Char('c'),
KeyModifiers::CONTROL
)));
}
#[cfg(target_os = "macos")]
#[test]
fn cmd_c_on_terminal_selection_lands_text_on_macos_clipboard() {
let _g = crate::clipboard::lock_clipboard_for_test();
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
app.terminal_mut().focused = true;
term.draw(|f| app.render(f)).unwrap();
let probe = format!("croft-terminal-cmdc-{}", std::process::id());
await_terminal_probe(&mut app, &probe);
term.draw(|f| app.render(f)).unwrap();
let snapshot = app.terminal().visible_text();
assert!(
snapshot.contains(&probe),
"shell must echo the probe within 3s; got:\n{snapshot}"
);
let row_idx = snapshot
.lines()
.position(|l| l.contains(&probe))
.expect("probe row must exist");
let line = snapshot.lines().nth(row_idx).unwrap();
let col_start = line.find(&probe).unwrap();
let col_end = col_start + probe.len() - 1;
let inner = app.terminal().last_inner;
let screen_y = inner.y + row_idx as u16;
let screen_x_a = inner.x + col_start as u16;
let screen_x_b = inner.x + col_end as u16;
app.terminal_mut().start_selection_at(screen_x_a, screen_y);
app.terminal_mut().extend_selection_to(screen_x_b, screen_y);
assert_eq!(
app.terminal().selection_text(),
probe,
"selection_text must reproduce the probe exactly so a Cmd+C copy is byte-faithful"
);
app.copy_terminal_selection();
let got = crate::clipboard::read_string()
.expect("read_string must surface what copy_terminal_selection just wrote");
assert_eq!(
got, probe,
"after a Cmd+C on a terminal selection, the system clipboard must contain the exact selection text - this is the non-negotiable round-trip the user relies on for every copy out of croft"
);
}
#[test]
fn ctrl_j_is_recognized_as_terminal_toggle() {
assert!(is_terminal_toggle_key(key(
KeyCode::Char('j'),
KeyModifiers::CONTROL
)));
}
#[test]
fn ctrl_shift_j_is_not_terminal_toggle_anymore() {
let mods = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
assert!(!is_terminal_toggle_key(key(KeyCode::Char('J'), mods)));
assert!(!is_terminal_toggle_key(key(KeyCode::Char('j'), mods)));
}
#[test]
fn plain_j_is_not_terminal_toggle() {
assert!(!is_terminal_toggle_key(key(
KeyCode::Char('j'),
KeyModifiers::NONE
)));
}
#[test]
fn ctrl_shift_j_is_terminal_maximize_key() {
let mods = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
assert!(is_terminal_maximize_key(key(KeyCode::Char('J'), mods)));
assert!(is_terminal_maximize_key(key(KeyCode::Char('j'), mods)));
}
#[test]
fn plain_ctrl_j_is_not_terminal_maximize_key() {
assert!(!is_terminal_maximize_key(key(
KeyCode::Char('j'),
KeyModifiers::CONTROL
)));
}
#[test]
fn plain_shift_j_is_not_terminal_maximize_key() {
assert!(!is_terminal_maximize_key(key(
KeyCode::Char('J'),
KeyModifiers::SHIFT
)));
}
#[test]
fn alt_or_super_blocks_terminal_maximize_key() {
let with_alt = KeyModifiers::CONTROL | KeyModifiers::SHIFT | KeyModifiers::ALT;
let with_super = KeyModifiers::CONTROL | KeyModifiers::SHIFT | KeyModifiers::SUPER;
assert!(!is_terminal_maximize_key(key(KeyCode::Char('J'), with_alt)));
assert!(!is_terminal_maximize_key(key(
KeyCode::Char('J'),
with_super
)));
}
#[test]
fn ctrl_shift_j_toggles_terminal_maximize_state_via_handle_key() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(!app.terminal_maximized, "fresh app starts un-maximized");
let chord = key(
KeyCode::Char('J'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
);
app.handle_key(chord).unwrap();
assert!(app.terminal_maximized, "first chord maximizes");
assert!(app.show_terminal, "maximize forces terminal visible");
assert!(
matches!(app.focus, Pane::Terminal),
"maximize focuses the terminal"
);
app.handle_key(chord).unwrap();
assert!(!app.terminal_maximized, "second chord restores split");
}
#[test]
fn multiline_terminal_drag_above_the_pane_does_not_bleed_into_the_editor() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("probe.txt");
std::fs::write(&f, "alpha\nbeta\ngamma\ndelta\nepsilon\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let term_inner = app.terminal().last_inner;
let editor_area = app.editor.last_area;
assert!(
term_inner.width > 4 && term_inner.height > 2,
"precondition: the split terminal must own a real rect"
);
assert!(
editor_area.height > 0 && editor_area.y < term_inner.y,
"precondition: the editor pane must sit above the terminal so the upward drag crosses into it"
);
app.focus_pane(Pane::Editor);
app.editor.start_selection_at_cursor();
app.editor.move_right();
app.editor.move_right();
app.editor.extend_selection_to_cursor();
assert!(
app.editor.selection.is_some_and(|s| s.has_area()),
"precondition: the editor must hold an active selection before the terminal gesture"
);
let click_col = term_inner.x + 3;
let click_row = term_inner.y + 2;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: click_col,
row: click_row,
modifiers: KeyModifiers::NONE,
});
let drag_col = term_inner.x + 1;
let drag_row = editor_area.y + 1; assert!(
drag_row < term_inner.y,
"precondition: the drag end-point must land above the terminal pane"
);
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
column: drag_col,
row: drag_row,
modifiers: KeyModifiers::NONE,
});
assert!(
app.editor.selection.is_none_or(|s| !s.has_area()),
"a terminal drag that overflowed upward must not seed an editor selection - that is the cross-pane bleed reported in issue #23"
);
let sel = app
.terminal()
.selection()
.expect("the terminal Down must have seeded a selection");
let (head_line, head_col) = sel.head;
assert!(
head_line >= 0 && (head_line as u16) < term_inner.height,
"terminal selection head line {head_line} must clamp inside the terminal viewport (0..{})",
term_inner.height
);
assert!(
head_col < term_inner.width,
"terminal selection head col {head_col} must clamp inside the terminal inner width {}",
term_inner.width
);
}
#[test]
fn cross_pane_paste_via_bracketed_paste_works_in_every_destination_and_terminal_layout() {
fn seed_app() -> (tempfile::TempDir, App) {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("probe.txt");
std::fs::write(&f, "alpha\nbeta\ngamma\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
(tmp, app)
}
let payload_editor_split = "clip-into-editor-split";
let payload_editor_max = "clip-into-editor-maximised";
let payload_find_split = "clip-into-find-split";
let payload_find_max = "clip-into-find-maximised";
let payload_search_split = "clip-into-search-split";
let payload_search_max = "clip-into-search-maximised";
let payload_finder = "clip-into-file-finder";
let payload_sc = "clip-into-source-control";
{
let (_tmp, mut app) = seed_app();
let _draw = draw_terminal(&mut app, 140, 50);
app.focus_pane(Pane::Editor);
app.handle_paste(payload_editor_split);
assert!(
app.editor
.lines
.iter()
.any(|l| l.contains(payload_editor_split)),
"bracketed paste with editor focus + terminal split must insert into the editor buffer; lines={:?}",
app.editor.lines
);
}
{
let (_tmp, mut app) = seed_app();
let _draw = draw_terminal(&mut app, 140, 50);
app.toggle_terminal_maximize();
let _draw = draw_terminal(&mut app, 140, 50);
app.focus_pane(Pane::Editor);
app.handle_paste(payload_editor_max);
assert!(
app.editor
.lines
.iter()
.any(|l| l.contains(payload_editor_max)),
"bracketed paste with editor focus + terminal maximised must still insert into the editor; lines={:?}",
app.editor.lines
);
}
{
let (_tmp, mut app) = seed_app();
let _draw = draw_terminal(&mut app, 140, 50);
app.focus_pane(Pane::Editor);
app.open_editor_find();
app.handle_paste(payload_find_split);
let q = app
.editor_find
.as_ref()
.map(|s| s.query.clone())
.unwrap_or_default();
assert!(
q.contains(payload_find_split),
"bracketed paste with editor-find open + terminal split must append to the query; query={q:?}"
);
}
{
let (_tmp, mut app) = seed_app();
let _draw = draw_terminal(&mut app, 140, 50);
app.toggle_terminal_maximize();
let _draw = draw_terminal(&mut app, 140, 50);
app.focus_pane(Pane::Editor);
app.open_editor_find();
app.handle_paste(payload_find_max);
let q = app
.editor_find
.as_ref()
.map(|s| s.query.clone())
.unwrap_or_default();
assert!(
q.contains(payload_find_max),
"bracketed paste with editor-find open + terminal maximised must append to the query - this is the path the user named explicitly; query={q:?}"
);
}
{
let (_tmp, mut app) = seed_app();
let _draw = draw_terminal(&mut app, 140, 50);
app.set_sidebar_view(SidebarView::Search);
let _draw = draw_terminal(&mut app, 140, 50);
app.handle_paste(payload_search_split);
assert!(
app.search.query.contains(payload_search_split),
"bracketed paste in Search sidebar + terminal split must append to the search query; query={:?}",
app.search.query
);
}
{
let (_tmp, mut app) = seed_app();
let _draw = draw_terminal(&mut app, 140, 50);
app.toggle_terminal_maximize();
let _draw = draw_terminal(&mut app, 140, 50);
app.set_sidebar_view(SidebarView::Search);
let _draw = draw_terminal(&mut app, 140, 50);
app.handle_paste(payload_search_max);
assert!(
app.search.query.contains(payload_search_max),
"bracketed paste in Search sidebar + terminal maximised must also append; query={:?}",
app.search.query
);
}
{
let (_tmp, mut app) = seed_app();
let _draw = draw_terminal(&mut app, 140, 50);
app.focus_pane(Pane::Terminal);
app.handle_paste("clip-into-terminal-split");
}
{
let (_tmp, mut app) = seed_app();
let _draw = draw_terminal(&mut app, 140, 50);
app.toggle_terminal_maximize();
let _draw = draw_terminal(&mut app, 140, 50);
app.focus_pane(Pane::Terminal);
app.handle_paste("clip-into-terminal-maximised");
}
{
let (_tmp, mut app) = seed_app();
let _draw = draw_terminal(&mut app, 140, 50);
app.set_sidebar_view(SidebarView::SourceControl);
let _draw = draw_terminal(&mut app, 140, 50);
app.handle_paste(payload_sc);
assert!(
app.source_control.message.contains(payload_sc),
"bracketed paste in the Source Control commit box must append the clipboard; got: {:?}",
app.source_control.message
);
}
{
let (_tmp, mut app) = seed_app();
let _draw = draw_terminal(&mut app, 140, 50);
app.open_file_finder();
app.handle_paste(payload_finder);
let q = app
.file_finder
.as_ref()
.map(|f| f.query.clone())
.unwrap_or_default();
assert!(
q.contains(payload_finder),
"bracketed paste in the file finder (Cmd+P) must append to the query; query={q:?}"
);
}
}
#[test]
fn double_click_in_terminal_word_selects_in_split_and_maximised_layout() {
for maximise in [false, true] {
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();
if maximise {
app.toggle_terminal_maximize();
term.draw(|f| app.render(f)).unwrap();
}
app.focus_pane(Pane::Terminal);
let probe = format!("croft-dclick-{}", std::process::id());
await_terminal_probe(&mut app, &probe);
term.draw(|f| app.render(f)).unwrap();
let snap = app.terminal().visible_text();
let row_idx = snap
.lines()
.position(|l| l.contains(&probe))
.expect("probe must render");
let line = snap.lines().nth(row_idx).unwrap();
let mid_col = line.find(&probe).unwrap() + probe.len() / 2;
let inner = app.terminal().last_inner;
let screen_y = inner.y + row_idx as u16;
let screen_x = inner.x + mid_col as u16;
for _ in 0..2 {
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: screen_x,
row: screen_y,
modifiers: KeyModifiers::NONE,
});
}
let sel_text = app.terminal().selection_text();
assert!(
sel_text.contains(&probe) || probe.contains(&sel_text),
"double-click on the middle of the probe word must word-select the run that contains it in {} layout; got selection={sel_text:?}",
if maximise { "maximised" } else { "split" }
);
}
}
#[test]
fn terminal_copy_paste_into_other_panes_works_in_split_and_maximised_layout() {
fn copy_terminal_word(app: &mut App) -> String {
let probe = format!("croft-e2e-{}", std::process::id());
await_terminal_probe(app, &probe);
let snap = app.terminal().visible_text();
let row_idx = snap.lines().position(|l| l.contains(&probe)).unwrap();
let line = snap.lines().nth(row_idx).unwrap();
let col_start = line.find(&probe).unwrap();
let col_end = col_start + probe.len() - 1;
let inner = app.terminal().last_inner;
let screen_y = inner.y + row_idx as u16;
let screen_x_a = inner.x + col_start as u16;
let screen_x_b = inner.x + col_end as u16;
app.terminal_mut().start_selection_at(screen_x_a, screen_y);
app.terminal_mut().extend_selection_to(screen_x_b, screen_y);
assert_eq!(
app.terminal().selection_text(),
probe,
"terminal selection_text must reproduce the probe before we copy"
);
app.copy_terminal_selection();
probe
}
let layouts: &[bool] = &[false, true]; for &maximise in layouts {
{
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();
if maximise {
app.toggle_terminal_maximize();
term.draw(|f| app.render(f)).unwrap();
}
app.focus_pane(Pane::Terminal);
let probe = copy_terminal_word(&mut app);
let cmd_shift_f = key(
KeyCode::Char('F'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
);
app.handle_key(cmd_shift_f).unwrap();
term.draw(|f| app.render(f)).unwrap();
let clip = crate::clipboard::read_string()
.expect("clipboard must hold what copy_terminal_selection just wrote");
assert_eq!(clip, probe);
app.handle_paste(&clip);
assert!(
app.search.query.contains(&probe),
"terminal copy -> Search paste must work in {} layout; got query={:?}",
if maximise { "maximised" } else { "split" },
app.search.query
);
}
{
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("probe.txt");
std::fs::write(&f, "alpha\nbeta\ngamma\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
if maximise {
app.toggle_terminal_maximize();
term.draw(|f| app.render(f)).unwrap();
}
app.focus_pane(Pane::Terminal);
let probe = copy_terminal_word(&mut app);
app.focus_pane(Pane::Editor);
app.open_editor_find();
term.draw(|f| app.render(f)).unwrap();
let clip = crate::clipboard::read_string().unwrap();
assert_eq!(clip, probe);
app.handle_paste(&clip);
let q = app
.editor_find
.as_ref()
.map(|s| s.query.clone())
.unwrap_or_default();
assert!(
q.contains(&probe),
"terminal copy -> editor-find paste must work in {} layout; got query={q:?}",
if maximise { "maximised" } else { "split" }
);
}
{
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("probe.txt");
std::fs::write(&f, "alpha\nbeta\ngamma\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
if maximise {
app.toggle_terminal_maximize();
term.draw(|f| app.render(f)).unwrap();
}
app.focus_pane(Pane::Terminal);
let probe = copy_terminal_word(&mut app);
app.focus_pane(Pane::Editor);
term.draw(|f| app.render(f)).unwrap();
let clip = crate::clipboard::read_string().unwrap();
assert_eq!(clip, probe);
app.handle_paste(&clip);
assert!(
app.editor.lines.iter().any(|l| l.contains(&probe)),
"terminal copy -> editor body paste must work in {} layout; lines={:?}",
if maximise { "maximised" } else { "split" },
app.editor.lines
);
}
{
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();
if maximise {
app.toggle_terminal_maximize();
term.draw(|f| app.render(f)).unwrap();
}
app.focus_pane(Pane::Terminal);
let probe = copy_terminal_word(&mut app);
app.set_sidebar_view(SidebarView::SourceControl);
term.draw(|f| app.render(f)).unwrap();
let clip = crate::clipboard::read_string().unwrap();
assert_eq!(clip, probe);
app.handle_paste(&clip);
assert!(
app.source_control.message.contains(&probe),
"terminal copy -> Source Control paste must work in {} layout; msg={:?}",
if maximise { "maximised" } else { "split" },
app.source_control.message
);
}
}
}
#[test]
fn the_terminal_probe_command_prints_the_probe_without_echoing_it() {
let probe = format!("croft-probe-echo-{}", std::process::id());
let cmd = probe_command(&probe);
assert!(
!cmd.contains(&probe),
"the typed command line must not contain the probe verbatim, or the shell echo matches the grid search alongside the output; got {cmd:?}"
);
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
app.terminal_mut().focused = true;
term.draw(|f| app.render(f)).unwrap();
await_terminal_probe(&mut app, &probe);
let snap = app.terminal().visible_text();
let rows: Vec<&str> = snap.lines().filter(|l| l.contains(&probe)).collect();
assert_eq!(
rows.len(),
1,
"exactly one row may carry the probe (the command's output); got {rows:?}"
);
assert_eq!(
rows[0].trim(),
probe,
"the matching row must be the printed probe alone, not a command line quoting it"
);
}
#[test]
fn terminal_cmd_c_copies_even_when_search_sidebar_is_open() {
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();
app.set_sidebar_view(SidebarView::Search);
term.draw(|f| app.render(f)).unwrap();
let probe = format!("croft-search-open-{}", std::process::id());
await_terminal_probe(&mut app, &probe);
term.draw(|f| app.render(f)).unwrap();
let snap = app.terminal().visible_text();
let row_idx = snap.lines().position(|l| l.contains(&probe)).unwrap();
let line = snap.lines().nth(row_idx).unwrap();
let col_start = line.find(&probe).unwrap();
let col_end = col_start + probe.len() - 1;
let inner = app.terminal().last_inner;
let screen_y = inner.y + row_idx as u16;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
column: inner.x + col_start as u16,
row: screen_y,
modifiers: KeyModifiers::NONE,
});
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Drag(MouseButton::Left),
column: inner.x + col_end as u16,
row: screen_y,
modifiers: KeyModifiers::NONE,
});
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Up(MouseButton::Left),
column: inner.x + col_end as u16,
row: screen_y,
modifiers: KeyModifiers::NONE,
});
assert!(
app.focus == Pane::Terminal,
"terminal click must focus terminal"
);
app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(
crate::clipboard::read_string().as_deref(),
Some(probe.as_str()),
"Cmd+C in the terminal must copy the terminal selection even when the Search sidebar is the active view"
);
assert!(
app.search.query.is_empty(),
"Cmd+C in the terminal must NOT leak into the search query; query={:?}",
app.search.query
);
}
#[test]
fn maximizing_terminal_requests_welcome_image_clear_when_image_was_displayed() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.welcome.set_displayed(true);
let chord = key(
KeyCode::Char('J'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
);
app.handle_key(chord).unwrap();
assert!(app.terminal_maximized, "first chord maximizes");
assert!(
app.consume_welcome_image_clear(),
"maximize must arm a one-shot welcome image clear"
);
}
#[test]
fn maximizing_terminal_is_noop_for_welcome_clear_when_image_was_not_displayed() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.welcome.set_displayed(false);
let chord = key(
KeyCode::Char('J'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
);
app.handle_key(chord).unwrap();
assert!(app.terminal_maximized);
assert!(
!app.consume_welcome_image_clear(),
"maximize must NOT arm a clear when no image was ever emitted"
);
}
#[test]
fn restoring_terminal_from_maximize_rearms_welcome_overlay_dirty() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let chord = key(
KeyCode::Char('J'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
);
app.handle_key(chord).unwrap();
assert!(app.terminal_maximized);
app.overlays.welcome.set_dirty(false);
app.handle_key(chord).unwrap();
assert!(!app.terminal_maximized);
assert!(
app.overlays.welcome.is_dirty(),
"exiting maximize must re-arm welcome_overlay_dirty so the wordmark re-paints"
);
}
#[test]
fn dtach_reattach_mode_reassert_reenables_mouse_tracking() {
let s = String::from_utf8(mode_reassert_seq()).unwrap();
for m in ["\x1b[?1049h", "\x1b[?1000h", "\x1b[?1006h", "\x1b[?2004h"] {
assert!(s.contains(m), "reattach re-assert missing {m:?}");
}
let takeover = String::from_utf8(takeover_mode_seq()).unwrap();
assert!(
s.starts_with(&takeover),
"mode_reassert_seq must embed takeover_mode_seq verbatim"
);
let set_kbd = format!("\x1b[={};1u", keyboard_enhancement_flags().bits());
assert!(s.contains(&set_kbd), "kitty keyboard flags must be re-SET");
assert!(
!s.contains("\x1b[>"),
"a push (CSI > flags u) per WINCH would leak stack entries"
);
}
#[test]
fn change_workspace_root_writes_cd_into_active_terminal_pty() {
let tmp = tempfile::tempdir().unwrap();
let target_dir = tmp.path().join("seeded");
std::fs::create_dir(&target_dir).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let _ = app.terminal_mut().take_dirty();
app.change_workspace_root(target_dir.clone());
assert!(
app.terminal_mut().take_dirty(),
"change_workspace_root must seed the active terminal's PTY with a cd command so the shell follows the Explorer; nothing was written"
);
assert_eq!(
app.workspace_root(),
target_dir,
"workspace_root must still flip to the new path"
);
}
#[test]
fn change_workspace_root_skips_cd_when_terminal_runs_a_foreground_app() {
let tmp = tempfile::tempdir().unwrap();
let target_dir = tmp.path().join("seeded");
std::fs::create_dir(&target_dir).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminal_mut()
.write_input(b"echo GO''-MARKER; sleep 60\n");
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the shell's main loop to print the marker",
|| {
let (lines, _) = app.terminal().grid_lines();
lines
.iter()
.any(|l| l.contains("GO-MARKER") && !l.contains("echo"))
},
);
let mut foreground = None;
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the kernel to report a foreign foreground group (the sleep)",
|| {
foreground = app.terminal().foreground_resolved_for_test();
foreground == Some(false)
},
);
assert_eq!(
foreground,
Some(false),
"await_spawned returns only once the kernel reports the foreign group"
);
app.change_workspace_root(target_dir.clone());
assert!(
app.status.contains("terminal busy"),
"a busy terminal must take the suppress-cd branch and say so; injecting a cd would type the path into the running app. status was: {}",
app.status
);
assert_eq!(
app.workspace_root(),
target_dir,
"the Explorer root must still flip even when the shell cannot be synced"
);
}
#[test]
fn change_workspace_root_seeds_cd_while_shell_startup_owns_the_tty() {
let tmp = tempfile::tempdir().unwrap();
let target_dir = tmp.path().join("seeded");
std::fs::create_dir(&target_dir).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let script = tmp.path().join("slow-startup.sh");
std::fs::write(&script, "#!/bin/bash\nset -m\nsleep 30\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
}
app.terminals[app.active_terminal] = crate::widgets::terminal::PtyTerminal::new_running(
script.to_str().unwrap(),
&[],
tmp.path(),
)
.unwrap();
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the startup child to take the foreground group from the shell",
|| !app.terminal().foreground_is_shell(),
);
assert!(
!app.terminal().foreground_is_shell(),
"precondition: the startup child must own the foreground group"
);
let _ = app.terminal_mut().take_dirty();
app.change_workspace_root(target_dir.clone());
assert!(
app.terminal_mut().take_dirty(),
"a Make Root during shell startup must still seed the cd: nothing has ever been \
written into the pane, so a non-shell foreground group can only be shell startup \
and the seed is type-ahead for the first prompt"
);
assert!(
!app.status.contains("terminal busy"),
"the startup window must not be reported as a busy terminal; status was: {}",
app.status
);
}
#[test]
fn ctrl_k_leads_off_macos_except_in_the_shell_or_the_vim_editor() {
assert!(ctrl_k_leads(false, false, false));
assert!(
!ctrl_k_leads(false, true, false),
"a focused shell keeps Ctrl+K"
);
assert!(
!ctrl_k_leads(false, false, true),
"the vim editor keeps kill-line"
);
assert!(
!ctrl_k_leads(true, false, false),
"macOS: Ctrl+K kills, Cmd leads"
);
let ctrl_k = key(KeyCode::Char('k'), KeyModifiers::CONTROL);
assert!(is_cmd_k_leader_key(ctrl_k, true));
assert!(!is_cmd_k_leader_key(ctrl_k, false));
for ctrl_leads in [false, true] {
let super_k = key(KeyCode::Char('k'), KeyModifiers::SUPER);
assert!(
is_cmd_k_leader_key(super_k, ctrl_leads),
"Cmd+K always leads"
);
let ctrl_shift_k = key(
KeyCode::Char('K'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
);
assert!(
!is_cmd_k_leader_key(ctrl_shift_k, ctrl_leads),
"Ctrl+Shift+K stays Delete Line"
);
}
}
#[test]
fn terminal_clear_from_the_palette_empties_the_active_pane() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
app.active_terminal = 1;
await_terminal_probe(&mut app, "cleared-1562");
app.focus_pane(Pane::Editor);
assert!(run_palette_row_titled(&mut app, "Terminal: Clear"));
assert!(
!app.terminals[1].visible_text().contains("cleared-1562"),
"{}",
app.terminals[1].visible_text()
);
assert_eq!(app.status, "Cleared terminal");
}
#[test]
fn terminal_modes_from_the_palette_focus_the_terminal() {
use crate::widgets::command_palette::Command;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
draw(&mut app, 100, 30);
app.focus_pane(Pane::Editor);
app.run_command(Command::TerminalCopyMode);
assert!(app.terminal_copy_mode.is_some());
assert!(app.focus == Pane::Terminal);
app.terminal_copy_mode = None;
app.focus_pane(Pane::Editor);
app.run_command(Command::TerminalCommandHistory);
assert!(app.command_history_popup.is_some());
assert!(app.focus == Pane::Terminal);
}
#[test]
fn terminal_modes_from_the_palette_bring_the_terminal_tab_forward() {
use crate::widgets::command_palette::Command;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
draw(&mut app, 100, 30);
for cmd in [
Command::TerminalCopyMode,
Command::TerminalQuickSelect,
Command::TerminalCommandHistory,
] {
app.terminal_copy_mode = None;
app.command_history_popup = None;
app.set_bottom_panel_tab(BottomPanelTab::Output);
app.focus_pane(Pane::Editor);
app.run_command(cmd);
assert!(app.bottom_panel_tab == BottomPanelTab::Terminal, "{cmd:?}");
assert!(app.focus == Pane::Terminal, "{cmd:?}");
}
}
#[test]
fn terminal_menu_rows_show_the_user_s_chord() {
let (clear, rename) = if cfg!(target_os = "macos") {
("⌘K K", "⌘K R")
} else {
("Ctrl+K K", "Ctrl+K R")
};
let none = crate::keymap::Keymap::from_json("[]");
assert_eq!(
menu_hint(&MenuAction::ClearTerminal(0), &none).as_deref(),
Some(clear)
);
let bound = crate::keymap::Keymap::from_json(
r#"[{ "key": "ctrl+alt+k", "command": "terminal_clear" }]"#,
);
assert_eq!(
menu_hint(&MenuAction::ClearTerminal(0), &bound).as_deref(),
Some("ctrl+alt+k")
);
assert_eq!(
menu_hint(&MenuAction::RenameTerminal(0), &bound).as_deref(),
Some(rename),
"only the rebound row changes"
);
}
#[test]
fn cmd_shift_t_focuses_the_terminal_pane_from_the_editor() {
let mut app = editor_app_with_lines(&["x"]);
app.focus_pane(Pane::Editor);
app.handle_key(key(
KeyCode::Char('t'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert!(
matches!(app.focus, Pane::Terminal),
"Cmd+Shift+T must move focus to the Terminal pane from the editor so the user can start typing in the shell without reaching for the mouse"
);
}
#[test]
fn cmd_shift_t_focuses_the_terminal_pane_from_the_tree() {
let mut app = editor_app_with_lines(&["x"]);
app.focus_pane(Pane::Tree);
app.handle_key(key(
KeyCode::Char('t'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert!(
matches!(app.focus, Pane::Terminal),
"Cmd+Shift+T must move focus to the Terminal pane even when the Explorer is focused"
);
}
#[test]
fn terminal_focus_key_predicate_accepts_cmd_shift_t_and_rejects_neighbours() {
let cmd_shift = KeyModifiers::SUPER | KeyModifiers::SHIFT;
assert!(is_terminal_focus_key(key(KeyCode::Char('t'), cmd_shift)));
assert!(is_terminal_focus_key(key(KeyCode::Char('T'), cmd_shift)));
assert!(
!is_terminal_focus_key(key(KeyCode::Char('t'), KeyModifiers::SUPER)),
"Cmd+T (no Shift) is the split/new-terminal chord, not focus; the focus chord requires Shift"
);
assert!(
!is_terminal_focus_key(key(
KeyCode::Char('t'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT
)),
"Ctrl+Shift+T must stay routed to is_terminal_split_key, not focus"
);
assert!(
!is_terminal_focus_key(key(
KeyCode::Char('t'),
KeyModifiers::SUPER | KeyModifiers::SHIFT | KeyModifiers::ALT
)),
"Cmd+Opt+Shift+T must not focus — that chord is reserved (we relocate iTerm2's Restore Closed Session onto it)"
);
}
#[test]
fn cmd_c_inside_a_mouse_tracking_program_says_why_nothing_was_copied() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.show_terminal = true;
app.focus_pane(Pane::Terminal);
app.terminals[0].feed_bytes_for_test(b"\x1b[?1002h\x1b[?1006h");
assert!(
app.terminals[0].mouse_reporting(),
"precondition: the child is tracking the mouse"
);
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.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
inner.x + 2,
inner.y + 1,
));
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
inner.x + 12,
inner.y + 1,
));
app.handle_mouse(mouse(
MouseEventKind::Up(MouseButton::Left),
inner.x + 12,
inner.y + 1,
));
assert!(
!app.terminals[0].selection().is_some_and(|s| s.has_area()),
"precondition: the drag belonged to the child, so croft holds no selection"
);
app.status.clear();
app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER))
.unwrap();
assert!(
!app.status.is_empty(),
"Cmd+C that copies nothing must say so rather than fail silently"
);
assert!(
app.status.contains("Shift"),
"and must name the gesture that DOES select inside a tracking program, got {:?}",
app.status
);
}
fn app_with_one_finished_command(
tmp: &std::path::Path,
) -> (App, crate::widgets::terminal::CommandDecoration) {
let mut app = App::new(tmp.to_path_buf()).unwrap();
let script = "x=out; printf '\\033]133;A\\007$ \\033]133;B\\007cmd\\n\\033]133;C\\007'\"$x\"'-1667\\n\\033]133;D;0\\007'; sleep 30";
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), script.into()],
tmp,
)
.unwrap();
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the shell to finish its command",
|| !app.terminals[0].command_decorations().is_empty(),
);
let deco = app.terminals[0].command_decorations()[0];
(app, deco)
}
#[test]
fn copy_output_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 (mut app, deco) = app_with_one_finished_command(tmp.path());
let sent = relay_copied(&mut app, |app| app.copy_command_output(0, deco));
assert_eq!(sent.as_deref().map(str::trim_end), Some("out-1667"));
assert_eq!(
app.status,
"Sent command output (1 line) to the local clipboard"
);
}
#[test]
fn every_terminal_copy_on_a_relay_session_reaches_the_local_clipboard() {
use crossterm::event::{MouseButton, MouseEventKind};
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();
let script = "x=de40; printf \"sha ${x}bdf12ab34\\n\"; sleep 60";
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from(script)],
tmp.path(),
)
.unwrap();
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the pane output \"de40bdf12ab34\"",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.starts_with("sha de40bdf12ab34"))
},
);
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 sent = relay_copied(&mut app, |app| {
app.handle_terminal_key(key(
KeyCode::Char(' '),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
));
let label = app
.terminal_quick_select
.as_ref()
.expect("Ctrl+Shift+Space enters quick select")
.hints
.iter()
.find(|h| h.text == "de40bdf12ab34")
.expect("the hash is labelled")
.label
.clone();
for c in label.chars() {
app.handle_terminal_key(key(KeyCode::Char(c), KeyModifiers::NONE));
}
});
assert_eq!(sent.as_deref(), Some("de40bdf12ab34"), "quick select");
assert!(
app.status.ends_with("to the local clipboard"),
"{}",
app.status
);
let (lines, _) = app.terminals[0].grid_lines();
let row = lines
.iter()
.position(|l| l.starts_with("sha de40bdf12ab34"))
.unwrap();
let sent = relay_copied(&mut app, |app| {
app.handle_terminal_key(key(
KeyCode::Char('y'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
));
assert!(
app.terminal_copy_mode.is_some(),
"Ctrl+Shift+Y enters copy mode"
);
app.handle_terminal_key(key(KeyCode::Char('g'), KeyModifiers::NONE));
for _ in 0..row {
app.handle_terminal_key(key(KeyCode::Char('j'), KeyModifiers::NONE));
}
app.handle_terminal_key(key(KeyCode::Char('V'), KeyModifiers::NONE));
app.handle_terminal_key(key(KeyCode::Char('y'), KeyModifiers::NONE));
});
assert_eq!(
sent.as_deref().map(str::trim_end),
Some("sha de40bdf12ab34"),
"copy mode"
);
assert!(
app.status.ends_with("to the local clipboard"),
"{}",
app.status
);
app.copy_on_select = true;
let inner = app.terminals[0].last_inner;
let (lines, top) = app.terminals[0].grid_lines();
let vrow = (top
+ lines
.iter()
.position(|l| l.starts_with("sha de40bdf12ab34"))
.unwrap() as i32) as u16;
app.terminals[0].start_selection_at(inner.x, inner.y + vrow);
app.terminals[0].extend_selection_to(inner.x + 2, inner.y + vrow);
let expected = app.terminals[0].selection_text();
assert!(expected.starts_with("sh"), "precondition: {expected:?}");
let sent = relay_copied(&mut app, |app| {
app.handle_mouse(mouse(
MouseEventKind::Up(MouseButton::Left),
inner.x + 2,
inner.y + vrow,
));
});
assert_eq!(sent, Some(expected), "copy on select");
}
#[test]
fn copy_output_off_a_relay_session_writes_this_machines_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, deco) = app_with_one_finished_command(tmp.path());
assert!(!app.session.is_relay_session());
let log = with_relay_home(home.path(), || {
app.copy_command_output(0, deco);
app.relay_log_path().expect("relay log path derivable")
});
assert!(!log.exists(), "nothing goes over a relay");
let clip = crate::clipboard::read_string().unwrap_or_default();
assert_eq!(clip.trim_end(), "out-1667");
assert!(
app.status.starts_with("Copied command output (1 line)"),
"{}",
app.status
);
}
#[test]
fn dragging_terminal_splitter_resizes_terminal() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminal_splitter_y = Some(15);
app.last_content_height = 20;
app.last_content_width = 60;
app.terminal_height = Some(5); app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 50,
row: 15,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.gesture, Some(Gesture::Splitter(SplitterDrag::Terminal)));
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
column: 50,
row: 10,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.terminal_height, Some(10));
}
#[test]
fn terminal_drag_grabs_one_row_above_seam() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminal_splitter_y = Some(15);
app.last_content_height = 20;
app.last_content_width = 60;
app.terminal_height = Some(5);
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 50,
row: 14,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.gesture, Some(Gesture::Splitter(SplitterDrag::Terminal)));
}
#[test]
fn fresh_app_has_one_active_terminal() {
let tmp = tempfile::tempdir().unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
assert_eq!(app.terminals.len(), 1);
assert_eq!(app.active_terminal, 0);
}
#[test]
fn ctrl_shift_w_in_terminal_pane_closes_active() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
app.focus_pane(Pane::Terminal);
app.handle_key(key(
KeyCode::Char('W'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(app.terminals.len(), 1);
}
#[test]
fn each_terminal_paints_its_own_add_close_buttons_when_multiple_open() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
app.split_terminal().unwrap();
assert_eq!(app.terminals.len(), 3);
let backend = ratatui::backend::TestBackend::new(180, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert_eq!(
app.panel_hits.add_buttons.len(),
3,
"each terminal pane must record its own [+] hit rect"
);
assert_eq!(
app.panel_hits.close_buttons.len(),
3,
"each terminal pane must record its own [-] hit rect when more than one is open"
);
let xs: std::collections::HashSet<u16> =
app.panel_hits.add_buttons.iter().map(|r| r.x).collect();
assert_eq!(
xs.len(),
3,
"add-button rects must be on three distinct columns"
);
}
#[test]
fn a_frame_without_the_terminal_panes_or_the_panel_leaves_none_of_their_buttons_clickable() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
app.split_terminal().unwrap();
app.terminal_pane_maximized = true;
let backend = ratatui::backend::TestBackend::new(180, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let hits = &app.panel_hits;
assert!(!hits.terminal_tab.is_empty() && !hits.maximize_button.is_empty());
assert!(
!hits.focus_button.is_empty(),
"three panes have the focus-mode button"
);
assert!(
!hits.rail.is_empty() && hits.rail_rows.len() == 3,
"the rail lists all three"
);
assert_eq!(hits.add_buttons.len(), 3, "one [+] slot per pane");
app.bottom_panel_tab = BottomPanelTab::Problems;
term.draw(|f| app.render(f)).unwrap();
let hits = &app.panel_hits;
assert!(!hits.problems_tab.is_empty(), "the tab row is still drawn");
assert!(
hits.focus_button.is_empty(),
"focus mode is a TERMINAL-tab button"
);
assert!(
hits.rail.is_empty() && hits.rail_rows.is_empty(),
"no rail behind PROBLEMS"
);
for (name, list) in [
("add", &hits.add_buttons),
("profile", &hits.profile_buttons),
("close", &hits.close_buttons),
("label", &hits.pane_labels),
("collapse", &hits.collapse_buttons),
("strip", &hits.collapsed_strips),
] {
assert!(
list.is_empty(),
"no {name} button behind PROBLEMS: {list:?}"
);
}
app.show_terminal = false;
term.draw(|f| app.render(f)).unwrap();
assert_eq!(
app.panel_hits,
PanelHitAreas::default(),
"nothing of a hidden panel"
);
}
#[test]
fn a_frame_without_the_status_bar_leaves_none_of_its_items_clickable() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.status = "Saved".into();
let backend = ratatui::backend::TestBackend::new(120, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert!(!app.status_hits.message.is_empty(), "the message is drawn");
assert!(
!app.status_hits.diagnostics.is_empty(),
"the counts are drawn"
);
app.status_bar_visible = false;
term.draw(|f| app.render(f)).unwrap();
assert_eq!(app.status_hits, StatusHitAreas::default());
}
#[test]
fn clicking_restore_button_returns_to_split_layout() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
app.terminal_pane_maximized = true;
let backend = ratatui::backend::TestBackend::new(180, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let r = app.panel_hits.focus_button;
assert!(r.width > 0, "the panel row paints a restore button");
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: r.x + 1,
row: r.y,
modifiers: KeyModifiers::NONE,
});
assert!(
!app.terminal_pane_maximized,
"clicking the restore button leaves maximize mode"
);
term.draw(|f| app.render(f)).unwrap();
assert!(
app.terminals.iter().all(|t| t.last_area.width > 0),
"all panes are visible again after restore"
);
assert!(
app.panel_hits.rail_rows.is_empty(),
"the rail disappears with the split restored"
);
}
#[test]
fn peek_terminals_dirty_does_not_clear_flags() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.peek_terminals_dirty(), "fresh app should be dirty");
assert!(
app.peek_terminals_dirty(),
"peek must not consume the dirty flag"
);
let drained = app.drain_terminals_dirty();
assert!(drained, "drain after peek should still report dirty once");
assert!(
!app.peek_terminals_dirty(),
"after drain, peek must be clean"
);
}
#[test]
fn focus_flag_only_set_on_active_terminal() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
app.focus_pane(Pane::Terminal);
let active = app.active_terminal;
for (i, t) in app.terminals.iter().enumerate() {
assert_eq!(t.focused, i == active);
}
app.focus_pane(Pane::Editor);
for t in &app.terminals {
assert!(!t.focused);
}
}
#[test]
fn bare_f9_in_a_focused_terminal_is_the_shells_even_with_an_update_ready() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.update_status = UpdateStatus::Ready;
let _ = app.handle_key(key(KeyCode::F(9), KeyModifiers::NONE));
assert!(!app.pending_reexec && !app.quit, "croft did not relaunch");
assert!(
app.editor.breakpoints.is_empty(),
"nor toggled a breakpoint"
);
}
#[test]
fn a_python_block_still_imports_from_the_pane_s_directory() {
if !(crate::markdown::runnable_interpreter("python") == Some("python3")) {
return;
}
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("helper_1630.py"), "X = 'local'\n").unwrap();
let scripts = tempfile::tempdir().unwrap();
let cmd = super::fence_command(
"python3",
"import helper_1630\nprint(helper_1630.X)\n",
scripts.path(),
"/bin/sh",
);
assert_eq!(run_typed_line(&cmd, tmp.path()), "local\n");
}
#[test]
fn quick_select_skips_hints_inside_masked_spans() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.triggers = std::sync::Arc::new(crate::triggers::TriggerSet::from_json(
r#"[{ "regex": "token \\S+", "action": "redact" }]"#,
));
let term = crate::widgets::terminal::PtyTerminal::new_with_transcript(
tmp.path(),
&[
String::from("token deadbeefcafe0123 end"),
String::from("commit cafebabe0123456 fixed it"),
],
)
.unwrap();
app.insert_terminal(term);
app.focus_pane(Pane::Terminal);
app.open_terminal_quick_select();
let state = app
.terminal_quick_select
.as_ref()
.expect("quick select opened");
let texts: Vec<&str> = state.hints.iter().map(|h| h.text.as_str()).collect();
assert!(
texts.iter().any(|t| t.contains("cafebabe0123456")),
"the ordinary hash is still a hint: {texts:?}"
);
assert!(
!texts.iter().any(|t| t.contains("deadbeefcafe0123")),
"the hex run inside the masked token is not a hint: {texts:?}"
);
}
#[test]
fn undo_close_restores_a_closed_terminal_pane_with_its_process_alive() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mk = || {
crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from("read x; echo revived-$x; sleep 30"),
],
tmp.path(),
)
.unwrap()
};
app.terminals[0] = mk();
app.terminals.push(mk());
app.terminals[1].set_manual_name(Some(String::from("keepme")));
app.active_terminal = 1;
app.focus_pane(Pane::Terminal);
assert!(app.close_active_terminal());
assert_eq!(app.terminals.len(), 1);
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('T'), KeyModifiers::SHIFT)));
assert_eq!(app.terminals.len(), 2, "undo close must restore the pane");
assert_eq!(app.terminals[1].label(), "keepme");
assert_eq!(app.active_terminal, 1, "the restored pane takes focus");
app.terminals[1].write_input(b"back\n");
crate::test_budget::await_spawned(
crate::test_budget::tests::RESTORED_SHELL_BASE,
"the reopened pane's shell to answer",
|| {
app.terminals[1]
.grid_lines()
.0
.iter()
.any(|l| l.contains("revived-back"))
},
);
assert!(app.close_active_terminal());
for parked in &mut app.closed_terminals {
parked.closed_at =
std::time::Instant::now() - UNDO_CLOSE_GRACE - std::time::Duration::from_secs(1);
}
app.drain_terminal_bells();
assert!(
app.closed_terminals.is_empty(),
"expired parked panes must be reaped by the tick"
);
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('T'), KeyModifiers::SHIFT)));
assert_eq!(app.terminals.len(), 1, "nothing to restore after expiry");
}
#[test]
fn copy_mode_navigates_scrollback_with_vi_keys_and_copies_char_line_and_block() {
let tmp = 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("x=a; y=b; z=c; printf \"${x}aaa1\\n${y}bbb2\\n${z}cc3\\n\"; sleep 30"),
],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the pane output \"ccc3\"",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("ccc3"))
},
);
let enter_copy_mode = key(
KeyCode::Char('y'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
);
let press = |app: &mut App, code: KeyCode| {
app.handle_terminal_key(key(code, KeyModifiers::NONE));
};
let (lines, top) = app.terminals[0].grid_lines();
let hops = lines
.iter()
.position(|l| l.starts_with("aaaa1"))
.expect("printf output must be on the grid");
assert!(top <= 0, "no scrollback expected in this tiny session");
let down = |app: &mut App, n: usize| {
for _ in 0..n {
app.handle_terminal_key(key(KeyCode::Char('j'), KeyModifiers::NONE));
}
};
app.handle_terminal_key(enter_copy_mode);
assert!(
app.terminal_copy_mode.is_some(),
"Ctrl+Shift+Y must enter copy mode"
);
press(&mut app, KeyCode::Char('g'));
down(&mut app, hops);
press(&mut app, KeyCode::Char('0'));
press(&mut app, KeyCode::Char('v'));
press(&mut app, KeyCode::Char('$'));
press(&mut app, KeyCode::Char('y'));
assert_eq!(
crate::clipboard::read_string().unwrap_or_default(),
"aaaa1",
"v + $ + y must copy the whole first output line"
);
assert!(app.terminal_copy_mode.is_none(), "y exits copy mode");
app.handle_terminal_key(enter_copy_mode);
press(&mut app, KeyCode::Char('g'));
down(&mut app, hops);
press(&mut app, KeyCode::Char('l'));
press(&mut app, KeyCode::Char('l'));
press(&mut app, KeyCode::Char('V'));
press(&mut app, KeyCode::Char('j'));
press(&mut app, KeyCode::Char('y'));
assert_eq!(
crate::clipboard::read_string().unwrap_or_default(),
"aaaa1\nbbbb2",
"V + j + y must copy both full lines"
);
app.handle_terminal_key(enter_copy_mode);
press(&mut app, KeyCode::Char('g'));
down(&mut app, hops);
press(&mut app, KeyCode::Char('0'));
app.handle_terminal_key(key(KeyCode::Char('v'), KeyModifiers::CONTROL));
press(&mut app, KeyCode::Char('j'));
press(&mut app, KeyCode::Char('j'));
press(&mut app, KeyCode::Char('l'));
press(&mut app, KeyCode::Char('y'));
assert_eq!(
crate::clipboard::read_string().unwrap_or_default(),
"aa\nbb\ncc",
"Ctrl+V must cut a rectangular column slice"
);
app.handle_terminal_key(enter_copy_mode);
press(&mut app, KeyCode::Char('v'));
press(&mut app, KeyCode::Esc);
assert!(app.terminal_copy_mode.is_none(), "Esc exits copy mode");
assert!(
app.terminals[0].selection().is_none(),
"leaving copy mode must clear the selection highlight"
);
}
#[test]
fn capture_triggers_collect_into_the_captures_panel_and_jump_to_the_line() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.triggers = std::sync::Arc::new(crate::triggers::TriggerSet::from_json(
r#"[ { "regex": "err-(\\d+)", "action": "capture", "message": "boom \\1" } ]"#,
));
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from("read x; e=err; echo ${e}-7 broke; sleep 30"),
],
tmp.path(),
)
.unwrap();
app.drain_terminal_bells();
app.terminals[0].write_input(b"\n");
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the error line to be captured",
|| {
app.drain_terminal_bells();
!app.captures.is_empty()
},
);
let entry = app.captures.selected_entry().expect("one capture");
assert_eq!(entry.message, "boom 7");
assert!(
entry.line.contains("err-7 broke"),
"the whole line is kept: {:?}",
entry.line
);
app.captures_open_selected();
assert_eq!(app.bottom_panel_tab, BottomPanelTab::Terminal);
let sel = app.terminals[0].selection_text();
assert!(
sel.contains("err-7 broke"),
"jump must land the selection on the captured line, got {sel:?}"
);
app.ask_navigator_about_capture();
assert!(
app.status.to_lowercase().contains("not active"),
"{}",
app.status
);
assert!(
crate::widgets::command_palette::ALL_COMMANDS
.contains(&crate::widgets::command_palette::Command::AskNavigatorAboutCapture)
);
assert_eq!(
crate::widgets::command_palette::Command::AskNavigatorAboutCapture.id(),
"captures_ask_navigator"
);
}
fn app_with_captures(script: &str, want: usize) -> (tempfile::TempDir, App) {
app_with_triggers(ERR_CAPTURE, script, want)
}
const ERR_CAPTURE: &str =
r#"[ { "regex": "err-(\\d+)", "action": "capture", "message": "boom \\1" } ]"#;
fn app_with_triggers(triggers: &str, script: &str, want: usize) -> (tempfile::TempDir, App) {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.triggers = std::sync::Arc::new(crate::triggers::TriggerSet::from_json(triggers));
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
format!("read x; e=err; {script}; sleep 30"),
],
tmp.path(),
)
.unwrap();
app.drain_terminal_bells();
app.terminals[0].write_input(b"\n");
await_captures(&mut app, want);
(tmp, app)
}
fn await_captures(app: &mut App, want: usize) {
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the error lines to be captured",
|| {
app.drain_terminal_bells();
app.captures.len() >= want
},
);
}
#[test]
fn each_capture_of_a_repeated_line_jumps_to_its_own_copy() {
let (_tmp, mut app) =
app_with_captures("echo ${e}-7 broke; echo between; echo ${e}-7 broke", 2);
let mut rows = Vec::new();
for i in 0..2 {
app.captures.select_index(i);
app.captures_open_selected();
let sel = app.terminals[0]
.selection()
.expect("the jump selects the line");
assert!(
app.terminals[0].selection_text().contains("err-7 broke"),
"{}",
app.status
);
rows.push(sel.anchor.0);
}
assert_eq!(
rows[1] - rows[0],
2,
"the first entry selects the upper copy, the second the lower: {rows:?}"
);
}
#[test]
fn a_capture_that_left_the_scrollback_is_not_stood_in_for_by_its_repeat() {
let (_tmp, mut app) = app_with_captures(
"echo ${e}-7 broke; yes 'filler line' | head -n 6000; echo ${e}-7 broke",
2,
);
let (lines, _) = app.terminals[0].grid_lines();
assert_eq!(
lines
.iter()
.filter(|l| l.starts_with("err-7 broke"))
.count(),
1,
"precondition: the first copy rotated off the scrollback"
);
app.captures.select_index(0);
app.captures_open_selected();
assert_eq!(app.status, "Captured line is no longer in the scrollback");
assert!(
app.terminals[0].selection().is_none(),
"the first run's entry must not select the second run's line"
);
app.captures.select_index(1);
app.captures_open_selected();
assert!(
app.terminals[0].selection_text().contains("err-7 broke"),
"the copy still on screen is found: {}",
app.status
);
}
#[test]
fn a_resize_that_rewraps_the_output_keeps_each_capture_on_its_own_copy() {
let long = "printf '%0200d\\n' 0";
let (_tmp, mut app) = app_with_captures(
&format!(
"echo ${{e}}-7 broke; echo first; {long}; echo ${{e}}-7 broke; echo second; \
{long}; {long}; {long}"
),
2,
);
for (cols, when) in [(80, "as printed"), (40, "narrower"), (120, "wider")] {
app.terminals[0].resize(cols, 24);
for (i, next) in ["first", "second"].into_iter().enumerate() {
app.captures.select_index(i);
app.captures_open_selected();
let line = app.terminals[0]
.selection()
.unwrap_or_else(|| panic!("{when}: entry {i}: {}", app.status))
.anchor
.0;
let (lines, top) = app.terminals[0].grid_lines();
assert_eq!(
lines[(line - top) as usize + 1].trim_end(),
next,
"{when}: entry {i} selects its own copy"
);
}
}
}
fn app_resized_under_a_full_screen_program(
before: &str,
want: usize,
after: &str,
) -> (tempfile::TempDir, App) {
app_resized_under_a_full_screen_program_with(ERR_CAPTURE, before, want, after)
}
fn app_resized_under_a_full_screen_program_with(
triggers: &str,
before: &str,
want: usize,
after: &str,
) -> (tempfile::TempDir, App) {
let (tmp, mut app) = app_with_triggers(
triggers,
&format!(
"{before}; printf '\\033[?1049h'; read y; printf '\\033[?1049l'; {after}; echo back"
),
want,
);
let wait = |app: &mut App, what: &str, done: &dyn Fn(&App) -> bool| {
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
what,
|| {
app.drain_terminal_bells();
done(app)
},
);
};
wait(&mut app, "the full-screen program", &|app| {
app.terminals[0].alt_screen()
});
app.terminals[0].resize(40, 24);
app.terminals[0].write_input(b"\n");
wait(&mut app, "the shell back on the primary screen", &|app| {
!app.terminals[0].alt_screen()
&& app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.trim_end() == "back")
});
(tmp, app)
}
#[test]
fn a_resize_under_a_full_screen_program_keeps_each_capture_on_its_own_copy() {
let long = "printf '%0200d\\n' 0";
let (_tmp, mut app) = app_resized_under_a_full_screen_program(
&format!(
"echo ${{e}}-7 broke; echo first; {long}; echo ${{e}}-7 broke; echo second; \
{long}; {long}; {long}"
),
2,
"true",
);
for (i, next) in ["first", "second"].into_iter().enumerate() {
app.captures.select_index(i);
app.captures_open_selected();
let line = app.terminals[0]
.selection()
.unwrap_or_else(|| panic!("entry {i}: {}", app.status))
.anchor
.0;
let (lines, top) = app.terminals[0].grid_lines();
assert_eq!(
lines[(line - top) as usize + 1].trim_end(),
next,
"entry {i} selects its own copy"
);
}
}
#[test]
fn two_triggers_on_one_line_still_find_it_after_a_full_screen_resize() {
let both = r#"[
{ "regex": "err-(\\d+)", "action": "capture", "message": "boom \\1" },
{ "regex": "broke", "action": "capture", "message": "broke" }
]"#;
let (_tmp, mut app) = app_resized_under_a_full_screen_program_with(
both,
"echo ${e}-7 broke; echo first; echo ${e}-7 broke; echo second",
4,
"true",
);
for (i, next) in ["first", "first", "second", "second"]
.into_iter()
.enumerate()
{
app.captures.select_index(i);
app.captures_open_selected();
let line = app.terminals[0]
.selection()
.unwrap_or_else(|| panic!("entry {i}: {}", app.status))
.anchor
.0;
let (lines, top) = app.terminals[0].grid_lines();
assert_eq!(
lines[(line - top) as usize + 1].trim_end(),
next,
"entry {i} selects its own copy"
);
}
}
#[test]
fn a_reset_after_a_full_screen_resize_drops_the_capture() {
let exact =
r#"[ { "regex": "^err-(\\d+) broke$", "action": "capture", "message": "boom \\1" } ]"#;
let (_tmp, mut app) = app_resized_under_a_full_screen_program_with(
exact,
"echo ${e}-7 broke",
1,
"printf '\\033c'; echo ${e}-7 broke again",
);
assert_eq!(app.captures.len(), 1, "the later line is not captured");
app.captures.select_index(0);
app.captures_open_selected();
assert_eq!(app.status, "Captured line is no longer in the scrollback");
assert!(app.terminals[0].selection().is_none());
}
#[test]
fn a_copy_gone_after_a_full_screen_resize_is_not_stood_in_for_by_its_repeat() {
let (_tmp, mut app) = app_resized_under_a_full_screen_program(
"echo ${e}-7 broke; yes 'filler line' | head -n 4995; echo ${e}-7 broke; echo second",
2,
"yes 'filler line' | head -n 100",
);
let (lines, _) = app.terminals[0].grid_lines();
assert_eq!(
lines
.iter()
.filter(|l| l.starts_with("err-7 broke"))
.count(),
1,
"precondition: the first copy rotated off the scrollback"
);
app.captures.select_index(0);
app.captures_open_selected();
assert_eq!(app.status, "Captured line is no longer in the scrollback");
assert!(app.terminals[0].selection().is_none());
app.captures.select_index(1);
app.captures_open_selected();
assert!(
app.terminals[0].selection_text().contains("err-7 broke"),
"the copy still on screen is found: {}",
app.status
);
}
#[test]
fn a_capture_erased_by_a_clear_is_not_stood_in_for_by_a_later_copy() {
let (_tmp, mut app) = app_with_captures(
"echo ${e}-7 broke; read y; printf '\\033[H\\033[2J\\033[3J'; echo ${e}-7 broke; \
read z; echo ${e}-7 broke",
1,
);
app.terminals[0].write_input(b"\n");
await_captures(&mut app, 2);
app.terminals[0].clear_screen_and_scrollback();
app.terminals[0].write_input(b"\n");
await_captures(&mut app, 3);
for i in 0..2 {
app.captures.select_index(i);
app.captures_open_selected();
assert_eq!(
app.status, "Captured line is no longer in the scrollback",
"entry {i}"
);
assert!(app.terminals[0].selection().is_none(), "entry {i}");
}
app.captures.select_index(2);
app.captures_open_selected();
assert!(
app.terminals[0].selection_text().contains("err-7 broke"),
"the copy printed after the Clear is found: {}",
app.status
);
}
#[test]
fn a_capture_whose_pane_closed_takes_the_newest_match_in_the_active_pane() {
let tmp = 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 30")],
tmp.path(),
)
.unwrap();
app.terminals[0].feed_bytes_for_test(b"a line from a closed pane\r\n");
app.captures.push(crate::widgets::captures::CapturedLine {
pane: String::from("gone"),
shell_pid: None,
message: String::from("captured"),
line: String::from("a line from a closed pane"),
anchor: Some(u64::MAX),
});
app.captures_open_selected();
assert!(
app.terminals[0]
.selection_text()
.contains("a line from a closed pane"),
"{}",
app.status
);
}
#[test]
fn change_workspace_root_restores_the_incoming_workspaces_layout_when_the_panel_is_untouched() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a");
let b = tmp.path().join("b");
let b_sub = b.join("sub");
std::fs::create_dir(&a).unwrap();
std::fs::create_dir(&b).unwrap();
std::fs::create_dir(&b_sub).unwrap();
let session_path = tmp.path().join("sessions.json");
crate::terminal_session::save_for_root(
&session_path,
&b.display().to_string(),
crate::terminal_session::SessionRecord {
panes: vec![
crate::terminal_session::PaneRecord {
host: None,
cwd: b.display().to_string(),
name: None,
transcript: Vec::new(),
lane: None,
},
crate::terminal_session::PaneRecord {
host: None,
cwd: b_sub.display().to_string(),
name: Some(String::from("srv")),
transcript: Vec::new(),
lane: None,
},
],
active: 1,
},
)
.unwrap();
let mut app = App::new(a.clone()).unwrap();
app.terminal_session_path = session_path;
app.terminal_restore_respawns = true;
app.change_workspace_root(b.clone());
assert_eq!(
app.terminals.len(),
2,
"re-rooting an untouched panel must bring back the incoming workspace's saved layout"
);
assert_eq!(app.terminals[1].label(), "srv", "names come back with it");
assert_eq!(app.active_terminal, 1, "focus lands on the recorded pane");
}
#[test]
fn restoring_a_workspaces_layout_drops_pane_bound_state_from_the_outgoing_panel() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a");
let b = tmp.path().join("b");
std::fs::create_dir(&a).unwrap();
std::fs::create_dir(&b).unwrap();
let session_path = tmp.path().join("sessions.json");
crate::terminal_session::save_for_root(
&session_path,
&b.display().to_string(),
crate::terminal_session::SessionRecord {
panes: vec![
crate::terminal_session::PaneRecord {
host: None,
cwd: b.display().to_string(),
name: None,
transcript: Vec::new(),
lane: None,
},
crate::terminal_session::PaneRecord {
host: None,
cwd: b.display().to_string(),
name: Some(String::from("srv")),
transcript: Vec::new(),
lane: None,
},
],
active: 0,
},
)
.unwrap();
let mut app = App::new(a.clone()).unwrap();
app.terminal_session_path = session_path;
app.terminal_restore_respawns = true;
app.split_terminal().unwrap();
assert!(app.close_terminal_at(1));
assert!(!app.closed_terminals.is_empty());
app.open_terminal_copy_mode();
assert!(app.terminal_copy_mode.is_some());
app.change_workspace_root(b.clone());
assert_eq!(app.terminals.len(), 2, "precondition: the restore ran");
assert!(
app.terminal_copy_mode.is_none(),
"copy mode was bound to a replaced pane; its coordinates mean nothing on the restored grid"
);
assert!(
app.closed_terminals.is_empty(),
"undo-close must not resurrect a PTY from the outgoing workspace into the restored panel"
);
}
#[test]
fn osc_9_4_progress_paints_a_border_gauge_and_pill_percent() {
let tmp = 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(
"printf '\\033]9;4;1;46\\007'; read x; printf '\\033]9;4;0\\007'; sleep 30",
),
],
tmp.path(),
)
.unwrap();
app.terminals[0].set_manual_name(Some(String::from("bld")));
app.terminals.push(
crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from("sleep 30")],
tmp.path(),
)
.unwrap(),
);
app.terminals[1].set_manual_name(Some(String::from("idle")));
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the 1-of-46 progress report",
|| app.terminals[0].progress() == Some((1, 46)),
);
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let area = app.terminals[0].last_area;
let inner = app.terminals[0].last_inner;
let rows = screen_char_rows(&term);
let border_row = &rows[(area.y + area.height - 1) as usize];
let fill_glyph = if app.theme.surfaces().is_some() {
'\u{2582}'
} else if app.terminals[0].focused {
'═'
} else {
'━'
};
let fill: usize = border_row
.chars()
.skip(inner.x as usize)
.take(inner.width as usize)
.filter(|c| *c == fill_glyph)
.count();
let expected = (inner.width as u32 * 46 / 100) as usize;
assert!(
expected > 0,
"pane too narrow for the test to mean anything"
);
assert_eq!(
fill, expected,
"the bottom border must fill to 46% with heavy strokes: {border_row:?}"
);
let top_row = &rows[area.y as usize];
assert!(
top_row.contains("bld \u{b7} 46%"),
"the name pill carries the percent: {top_row:?}"
);
if let Some(t) = crate::theme::tones(app.theme) {
let buf = term.backend().buffer();
let quiet = crate::gradient::rgb_color(crate::gradient::lerp_rgb(t.accent, t.canvas, 0.25));
assert_eq!(buf[(inner.x, area.y + area.height - 1)].fg, quiet);
let b = (area.x..area.right())
.find(|&x| buf[(x, area.y)].symbol() == "b")
.unwrap();
assert!(app.terminals[0].focused);
assert_eq!(buf[(b, area.y)].fg, t.strong(), "the focused pane's name");
let other = app.terminals[1].last_area;
let i = (other.x..other.right())
.find(|&x| buf[(x, other.y)].symbol() == "i")
.expect("the other pane's name");
assert_eq!(buf[(i, other.y)].fg, t.muted(), "an unfocused pane's name");
}
app.terminals[0].write_input(b"\n");
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"state 0 to clear the progress",
|| app.terminals[0].progress().is_none(),
);
term.draw(|f| app.render(f)).unwrap();
let rows = screen_char_rows(&term);
let border_row = &rows[(area.y + area.height - 1) as usize];
assert!(
!border_row.contains(fill_glyph),
"a cleared gauge restores the plain border: {border_row:?}"
);
assert!(
!rows[area.y as usize].contains("46%"),
"the pill percent must clear too"
);
}
#[test]
fn cmd_k_d_dumps_the_pane_scrollback_into_a_rendered_log_tab() {
let tmp = 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("s=scroll; echo ${s}back-payload-7; sleep 30"),
],
tmp.path(),
)
.unwrap();
app.terminals[0].set_manual_name(Some(String::from("bldlog")));
app.scrollback_dir = tmp.path().join("dumps");
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the pane output \"scrollback-payload-7\"",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("scrollback-payload-7"))
},
);
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('d'), KeyModifiers::NONE)));
assert!(
matches!(app.focus, Pane::Editor),
"the dump lands in the editor, so focus follows"
);
let label = app
.editor
.path
.as_ref()
.map(|p| p.display().to_string())
.unwrap_or_default();
assert!(
label.contains("bldlog") && label.contains("scrollback"),
"the scratch tab is named after the pane: {label:?}"
);
let text: Vec<String> = {
let log = app
.editor
.log
.as_mut()
.expect("the dump opens as a rendered log");
log.finish_index();
let n = log.len();
log.ensure(0, n).unwrap();
(0..n)
.map(|i| log.visible_text(i).unwrap_or("").to_string())
.collect()
};
assert!(
text.iter().any(|l| l.contains("scrollback-payload-7")),
"the pane's output is in the buffer: {text:?}"
);
let blank_tail = text
.iter()
.rev()
.take_while(|l| l.trim().is_empty())
.count();
assert!(
blank_tail <= 1,
"the unused live-screen rows must not pad the buffer: {blank_tail} blank tail lines"
);
}
#[test]
fn cmd_k_d_opens_the_scrollback_as_a_rendered_log_with_its_colours() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.scrollback_dir = tmp.path().join("dumps");
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from("s=QQ; printf \"\\033[32m${s}GREEN\\033[0m rest\\n\"; sleep 30"),
],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the pane to print the coloured row",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("QQGREEN rest"))
},
);
app.open_scrollback_in_editor();
{
let log = app
.editor
.log
.as_mut()
.expect("the scrollback opens in the rendered log view");
log.finish_index();
let n = log.len();
log.ensure(0, n).unwrap();
}
let log = app.editor.log.as_ref().unwrap();
let row = (0..log.len())
.find(|&i| {
log.visible_text(i)
.is_some_and(|t| t.contains("QQGREEN rest"))
})
.expect("the coloured row is in the view, escapes stripped");
let line = log.line(row).expect("the row is parsed");
let green = line
.spans
.iter()
.find(|s| line.text[s.start..s.end].contains("QQGREEN"))
.unwrap_or_else(|| panic!("a span colours the green run: {:?}", line.spans));
assert_eq!(
green.style.fg,
Some(crate::ansi_text::AnsiColor::Indexed(2)),
"the pane's green reaches the tab as the symbolic green slot"
);
let path = app.editor.path.clone().expect("the tab has a path");
assert!(
path.starts_with(&app.scrollback_dir) && path.extension().is_some_and(|e| e == "log"),
"the dump is a .log under the scrollback dir: {path:?}"
);
assert!(
path.is_file(),
"the dump exists on disk for the view to index"
);
}
#[test]
fn a_second_dump_of_the_same_pane_shows_its_new_output() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.scrollback_dir = tmp.path().join("dumps");
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from(
"s=QQ; printf \"\\033[32m${s}ONE\\033[0m\\n\"; read line; \
printf \"\\033[32m${s}TWO\\033[0m\\n\"; sleep 30",
),
],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the first coloured row",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("QQONE"))
},
);
app.open_scrollback_in_editor();
assert!(app.editor.log.is_some(), "the first dump is a rendered log");
app.terminals[0].write_input(b"\n");
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the second coloured row",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("QQTWO"))
},
);
app.open_scrollback_in_editor();
let text: Vec<String> = {
let log = app
.editor
.log
.as_mut()
.expect("the second dump is a rendered log too");
log.finish_index();
let n = log.len();
log.ensure(0, n).unwrap();
(0..n)
.map(|i| log.visible_text(i).unwrap_or("").to_string())
.collect()
};
assert!(
text.iter().any(|l| l.contains("QQTWO")),
"the second dump shows the new row, not the stale first dump: {text:?}"
);
}
#[test]
fn colour_beyond_the_sniff_prefix_keeps_the_dump_plain() {
let plain: Vec<String> = (0..400)
.map(|i| format!("plain row {i:04} with padding text"))
.collect();
let mut late = plain.clone();
late.push(String::from("\x1b[32mlate colour\x1b[0m"));
assert!(
late.iter().map(|r| r.len() + 1).take(400).sum::<usize>() > 8192,
"fixture: the colour sits past the 8 KiB sniff prefix"
);
assert!(
!scrollback_opens_as_log(&late),
"colour past the prefix is not a log to the sniff"
);
let mut early = vec![String::from("\x1b[32mearly colour\x1b[0m")];
early.extend(plain.iter().cloned());
assert!(
scrollback_opens_as_log(&early),
"colour inside the prefix is"
);
assert!(!scrollback_opens_as_log(&plain), "no colour at all is not");
}
#[test]
fn a_scrollback_dump_is_a_pinned_tab() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.scrollback_dir = tmp.path().join("dumps");
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from("s=QQ; printf \"\\033[32m${s}PIN\\033[0m\\n\"; sleep 30"),
],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the coloured row",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("QQPIN"))
},
);
app.open_scrollback_in_editor();
let path = app.editor.path.clone().expect("the dump tab has a path");
let idx = app
.editor
.find_tab_with_path(&path)
.expect("the dump tab is findable by its path");
assert!(
!app.editor.is_preview(idx),
"the dump is pinned, not a replaceable preview"
);
}
#[test]
fn two_panes_with_one_label_dump_to_separate_files() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.scrollback_dir = tmp.path().join("dumps");
let spawn = |tag: &str| {
crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
format!("s=QQ; printf \"\\033[32m${{s}}{tag}\\033[0m\\n\"; sleep 30"),
],
tmp.path(),
)
.unwrap()
};
app.terminals = vec![spawn("ONE"), spawn("TWO")];
for (i, tag) in ["QQONE", "QQTWO"].iter().enumerate() {
app.terminals[i].set_manual_name(Some(String::from("same")));
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the pane to print its row",
|| {
app.terminals[i]
.grid_lines()
.0
.iter()
.any(|l| l.contains(tag))
},
);
}
app.active_terminal = 0;
app.focus_pane(Pane::Terminal);
app.open_scrollback_in_editor();
let first = app.editor.path.clone().expect("first dump has a path");
app.active_terminal = 1;
app.focus_pane(Pane::Terminal);
app.open_scrollback_in_editor();
let second = app.editor.path.clone().expect("second dump has a path");
assert_ne!(first, second, "one file per pane, not per label");
assert!(
first.is_file() && second.is_file(),
"both dumps are still on disk"
);
assert!(
app.editor.find_tab_with_path(&first).is_some(),
"the first pane's tab survives the second pane's dump"
);
}
#[cfg(unix)]
#[test]
fn a_scrollback_dump_is_owner_only_on_disk() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.scrollback_dir = tmp.path().join("dumps");
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from("s=QQ; printf \"\\033[32m${s}SEC\\033[0m\\n\"; sleep 30"),
],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the coloured row",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("QQSEC"))
},
);
app.open_scrollback_in_editor();
let path = app.editor.path.clone().expect("the dump has a path");
let file_mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
let dir_mode = std::fs::metadata(&app.scrollback_dir)
.unwrap()
.permissions()
.mode()
& 0o777;
assert_eq!(file_mode, 0o600, "the dump is readable by its owner alone");
assert_eq!(dir_mode, 0o700, "and so is the dir that holds it");
}
#[test]
fn a_scrollback_dump_file_is_scoped_to_this_process() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.scrollback_dir = tmp.path().join("dumps");
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from("s=QQ; printf \"\\033[32m${s}PID\\033[0m\\n\"; sleep 30"),
],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the coloured row",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("QQPID"))
},
);
app.open_scrollback_in_editor();
let name = app
.editor
.path
.clone()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
.expect("the dump has a file name");
assert!(
name.contains(&format!("-{}-", std::process::id())),
"the file name carries this process's pid: {name}"
);
}
#[test]
fn a_scrollback_dump_leaves_a_blank_group_it_did_not_empty_alone() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.scrollback_dir = tmp.path().join("dumps");
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from("s=QQ; printf \"\\033[32m${s}KEEP\\033[0m\\n\"; read line; sleep 30"),
],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the coloured row",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("QQKEEP"))
},
);
app.open_scrollback_in_editor();
app.split_editor();
assert!(app.editor_layout.is_split(), "fixture: the editor is split");
app.editor.close_tab(0);
assert!(
app.editor.is_blank_initial(),
"fixture: the focused group is blank"
);
app.focus_editor_group(true);
assert!(
app.editor.path.is_some(),
"fixture: the dump's group is focused"
);
assert!(
app.editor_layout
.inactive_groups()
.any(|g| g.is_blank_initial()),
"fixture: the blank group is inactive"
);
app.focus_pane(Pane::Terminal);
app.open_scrollback_in_editor();
assert!(
app.editor_layout.is_split(),
"a blank group this dump did not empty survives it"
);
}
#[test]
fn a_scrollback_dump_prunes_only_the_group_it_emptied() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.scrollback_dir = tmp.path().join("dumps");
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from("s=QQ; printf \"\\033[32m${s}THREE\\033[0m\\n\"; read line; sleep 30"),
],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the coloured row",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("QQTHREE"))
},
);
app.open_scrollback_in_editor();
app.split_editor();
app.editor.close_tab(0);
app.focus_editor_group(true);
assert!(
app.editor.path.is_some(),
"fixture: the dump's group is focused"
);
app.split_editor();
let inactive = app.editor_layout.inactive_groups().collect::<Vec<_>>();
assert_eq!(inactive.len(), 2, "fixture: two inactive groups");
assert!(
inactive.iter().any(|g| g.is_blank_initial())
&& inactive.iter().any(|g| g
.find_tab_with_path(app.editor.path.as_ref().unwrap())
.is_some()),
"fixture: one blank, one holding the dump"
);
app.focus_pane(Pane::Terminal);
app.open_scrollback_in_editor();
let inactive = app.editor_layout.inactive_groups().collect::<Vec<_>>();
assert!(
app.editor_layout.is_split(),
"the user's blank group keeps its split"
);
assert_eq!(
inactive.len(),
1,
"exactly the emptied group is gone: {} left",
inactive.len()
);
assert!(
inactive[0].is_blank_initial(),
"and the survivor is the user's blank group"
);
}
#[test]
fn a_scrollback_dump_that_cannot_be_written_falls_back_to_the_plain_buffer() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let blocker = tmp.path().join("blocker");
std::fs::write(&blocker, "not a dir").unwrap();
app.scrollback_dir = blocker.join("dumps");
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from("s=QQ; printf \"\\033[32m${s}FALL\\033[0m\\n\"; sleep 30"),
],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the coloured row",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("QQFALL"))
},
);
app.open_scrollback_in_editor();
assert!(app.editor.log.is_none(), "no rendered log view opened");
assert!(
app.editor.lines.iter().any(|l| l.contains("QQFALL")),
"the plain text is in the buffer: {:?}",
app.editor.lines
);
assert!(
app.status.starts_with("Rendered scrollback unavailable"),
"the status says why: {:?}",
app.status
);
}
#[cfg(unix)]
#[test]
fn a_scrollback_dump_reaps_the_dumps_of_dead_processes() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.scrollback_dir = tmp.path().join("dumps");
std::fs::create_dir_all(&app.scrollback_dir).unwrap();
let mut child = std::process::Command::new("true").spawn().unwrap();
child.wait().unwrap();
let dead = app
.scrollback_dir
.join(format!("shell-{}-1-scrollback.log", child.id()));
std::fs::write(&dead, "gone").unwrap();
let live = app
.scrollback_dir
.join(format!("shell-{}-99-scrollback.log", std::process::id()));
std::fs::write(&live, "mine").unwrap();
let other = app.scrollback_dir.join("notes.txt");
std::fs::write(&other, "not a dump").unwrap();
let huge = app.scrollback_dir.join("shell-4294967295-1-scrollback.log");
std::fs::write(&huge, "?").unwrap();
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from("s=QQ; printf \"\\033[32m${s}REAP\\033[0m\\n\"; sleep 30"),
],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the coloured row",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("QQREAP"))
},
);
app.open_scrollback_in_editor();
assert!(app.editor.path.is_some(), "the dump itself landed");
assert!(!dead.exists(), "a dead process's dump is reaped");
assert!(live.exists(), "this process's other dump stays");
assert!(other.exists(), "a file that is not a dump is not touched");
assert!(huge.exists(), "a pid outside pid_t is left alone");
}
#[test]
fn a_scrollback_dump_is_redacted_on_disk_and_only_the_masked_row_loses_colour() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.scrollback_dir = tmp.path().join("dumps");
app.triggers = std::sync::Arc::new(crate::triggers::TriggerSet::from_json(
r#"[{ "regex": "token \\S+", "action": "redact" }]"#,
));
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from(
"s=QQ; printf \"\\033[32m${s}SAFE\\033[0m\\n\"; \
printf \"\\033[31mtoken ${s}SECRET99\\033[0m\\n\"; sleep 30",
),
],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(std::time::Duration::from_millis(500), "both rows", || {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("QQSECRET99"))
});
app.open_scrollback_in_editor();
let path = app.editor.path.clone().expect("the dump has a path");
let on_disk = std::fs::read_to_string(&path).unwrap();
assert!(
!on_disk.contains("QQSECRET99"),
"the secret never reaches the disk: {on_disk:?}"
);
let masked_row = on_disk
.lines()
.find(|l| l.contains(crate::triggers::MASK))
.expect("the matching row is written masked");
assert!(
!masked_row.contains('\x1b'),
"the masked row gives up its colour: {masked_row:?}"
);
let safe_row = on_disk
.lines()
.find(|l| l.contains("QQSAFE"))
.expect("the neighbouring row is there");
assert!(
safe_row.contains("\x1b[32m"),
"and keeps its colour: {safe_row:?}"
);
}
#[test]
fn copy_mode_keys_follow_content_that_streamed_between_presses() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
let mut last = app.terminals[0].grid_lines().0;
let mut quiet_since = std::time::Instant::now();
while std::time::Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(50));
let now = app.terminals[0].grid_lines().0;
if now != last {
last = now;
quiet_since = std::time::Instant::now();
} else if last.iter().any(|l| !l.trim().is_empty())
&& quiet_since.elapsed() > std::time::Duration::from_millis(300)
{
break;
}
}
let mut fill = String::new();
for i in 0..40 {
fill.push_str(&format!("row-{i}\r\n"));
}
fill.push_str("row-40");
app.terminals[0].feed_bytes_for_test(fill.as_bytes());
app.open_terminal_copy_mode();
app.handle_terminal_copy_mode_key(key(KeyCode::Char('v'), KeyModifiers::NONE));
let mut more = String::new();
for i in 0..5 {
more.push_str(&format!("\r\nx-{i}"));
}
app.terminals[0].feed_bytes_for_test(more.as_bytes());
app.handle_terminal_copy_mode_key(key(KeyCode::Char('k'), KeyModifiers::NONE));
let text = app.terminals[0].selection_text();
assert!(
text.contains("row-40"),
"the selection must stay on the content the user was on, got: {text:?}"
);
}
#[test]
fn a_plain_click_on_the_prompt_row_moves_the_shell_cursor() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let sink = tmp.path().join("clicks.bin");
let script = format!(
"h=hello; printf '\\033]133;A\\007$ \\033]133;B\\007'; printf \"${{h}}-world\"; stty raw -echo 2>/dev/null; dd bs=1 count=33 of={} 2>/dev/null; sleep 30",
sink.display()
);
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), script],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the prompt text",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("hello-world"))
},
);
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let inner = app.terminals[0].last_inner;
let (lines, top) = app.terminals[0].grid_lines();
let vrow = (lines
.iter()
.position(|l| l.contains("hello-world"))
.unwrap() as i32
+ top) as u16;
let (x, y) = (inner.x + 2, inner.y + vrow);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), x, y));
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), x, y));
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the click's arrow keys to reach the shell (33 bytes)",
|| std::fs::read(&sink).unwrap_or_default().len() == 33,
);
assert_eq!(
std::fs::read(&sink).unwrap(),
b"\x1b[D".repeat(11),
"eleven left-arrows bring the cursor from after 'd' to 'h'"
);
}
#[test]
fn arrow_keys_reach_an_app_cursor_mode_child_as_ss3() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let sink = tmp.path().join("keys.bin");
let script = format!(
"s=REA; printf '\\033[?1h'; printf \"${{s}}DY_MARK\"; stty raw -echo 2>/dev/null; dd bs=1 count=18 of={} 2>/dev/null; sleep 30",
sink.display()
);
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), script],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the child to turn on app cursor mode",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("READY_MARK"))
},
);
for code in [
KeyCode::Up,
KeyCode::Down,
KeyCode::Right,
KeyCode::Left,
KeyCode::Home,
KeyCode::End,
] {
app.handle_terminal_key(key(code, KeyModifiers::NONE));
}
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the key presses to reach the child (18 bytes)",
|| std::fs::read(&sink).unwrap_or_default().len() == 18,
);
assert_eq!(
std::fs::read(&sink).unwrap(),
b"\x1bOA\x1bOB\x1bOC\x1bOD\x1bOH\x1bOF",
"DECCKM is on: keys must arrive in the SS3 application form"
);
}
#[test]
fn broadcast_arrows_encode_per_pane_cursor_mode() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let sink_a = tmp.path().join("a.bin");
let sink_b = tmp.path().join("b.bin");
let script_a = format!(
"s=REA; printf \"${{s}}DY_MARK\"; stty raw -echo 2>/dev/null; dd bs=1 count=3 of={} 2>/dev/null; sleep 30",
sink_a.display()
);
let script_b = format!(
"s=REA; printf '\\033[?1h'; printf \"${{s}}DY_MARK\"; stty raw -echo 2>/dev/null; dd bs=1 count=3 of={} 2>/dev/null; sleep 30",
sink_b.display()
);
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), script_a],
tmp.path(),
)
.unwrap();
app.terminals.push(
crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), script_b],
tmp.path(),
)
.unwrap(),
);
app.active_terminal = 0;
app.broadcast_input = true;
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the children to reach their prompts",
|| {
app.terminals
.iter()
.all(|t| t.grid_lines().0.iter().any(|l| l.contains("READY_MARK")))
},
);
app.handle_terminal_key(key(KeyCode::Up, KeyModifiers::NONE));
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the broadcast to reach both panes (3 bytes each)",
|| {
std::fs::read(&sink_a).unwrap_or_default().len() == 3
&& std::fs::read(&sink_b).unwrap_or_default().len() == 3
},
);
assert_eq!(
std::fs::read(&sink_a).unwrap(),
b"\x1b[A",
"normal-mode pane must get the CSI form"
);
assert_eq!(
std::fs::read(&sink_b).unwrap(),
b"\x1bOA",
"DECCKM pane must get the SS3 form"
);
}
#[test]
fn host_accent_rules_dress_matching_panes() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_host_accents(&[crate::prefs::HostAccentRule {
pattern: String::from("prod-*"),
accent: None, badge: Some(String::from("PROD")),
}]);
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from("printf '\\033]7;file://prod-db-1/tmp\\007'; sleep 30"),
],
tmp.path(),
)
.unwrap();
app.terminals[0].set_manual_name(Some(String::from("db")));
app.terminals.push(
crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from("sleep 30")],
tmp.path(),
)
.unwrap(),
);
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the OSC 7 host",
|| app.terminals[0].shell_host().as_deref() == Some("prod-db-1"),
);
let backend = ratatui::backend::TestBackend::new(140, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let area = app.terminals[0].last_area;
let red = Some(ratatui::style::Color::Rgb(0xf1, 0x4c, 0x4c));
let border = term.backend().buffer()[(area.x, area.y + 1)].style();
assert_eq!(
border.fg, red,
"a matching pane's border wears the accent color"
);
let inner = app.terminals[0].last_inner;
let top_row: String = (inner.x..inner.x + inner.width)
.map(|x| {
term.backend().buffer()[(x, inner.y)]
.symbol()
.chars()
.next()
.unwrap_or(' ')
})
.collect();
assert!(
top_row.contains("PROD"),
"the badge watermark sits on the pane's top row: {top_row:?}"
);
let pill_row: String = (area.x..area.x + area.width)
.map(|x| {
term.backend().buffer()[(x, area.y)]
.symbol()
.chars()
.next()
.unwrap_or(' ')
})
.collect();
assert!(
pill_row.contains("\u{26a0} db"),
"the name pill carries the warning mark: {pill_row:?}"
);
let other = app.terminals[1].last_area;
let other_border = term.backend().buffer()[(other.x, other.y + 1)].style();
assert_ne!(
other_border.fg, red,
"a non-matching pane must not wear the accent"
);
}
#[test]
fn alt_screen_upward_drag_through_the_real_mouse_pipeline_selects_upward() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let mut screen = String::from("\x1b[?1049h\x1b[?1000h\x1b[?1006h\x1b[H\x1b[2J");
for i in 0..6 {
screen.push_str(&format!("transcript line number {i:02}\r\n"));
}
screen.push_str("tokens 100");
app.terminal().feed_bytes_for_test(screen.as_bytes());
let area = app.terminal().last_area;
assert!(area.height > 9, "terminal pane must be real: {area:?}");
let (ix, iy) = (area.x + 1, area.y + 1);
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: ix,
row: iy + 4,
modifiers: KeyModifiers::NONE,
});
term.draw(|f| app.render(f)).unwrap();
for (step, drag_row) in [iy + 3, iy + 2].into_iter().enumerate() {
app.terminal()
.feed_bytes_for_test(format!("\x1b[7;1Htokens 10{step}\x1b[K").as_bytes());
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
column: ix,
row: drag_row,
modifiers: KeyModifiers::NONE,
});
term.draw(|f| app.render(f)).unwrap();
}
let sel = app.terminal().selection().expect("drag built a selection");
let (sr, _, er, _) = sel.normalised();
assert_eq!(
(sr, er),
(2, 4),
"dragging up two rows from row 4 must select rows 2..=4, never run downward: {sel:?}"
);
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
column: ix,
row: iy + 2,
modifiers: KeyModifiers::NONE,
});
let sel = app
.terminal()
.selection()
.expect("selection survives release");
let (sr, _, er, _) = sel.normalised();
assert_eq!(
(sr, er),
(2, 4),
"release must not move the selection: {sel:?}"
);
assert_eq!(
app.terminal().selection_text(),
"transcript line number 02\ntranscript line number 03\nt",
"the extracted text names the rows the pointer actually crossed"
);
}
#[test]
fn typing_into_an_unattached_pane_of_a_live_file_is_gated_not_wiped() {
use std::time::{Duration, Instant};
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("f.txt");
std::fs::write(&file, "hello world").unwrap();
let socket = tmp.path().join("collab.sock");
{
let s = socket.clone();
std::thread::spawn(move || {
let _ = crate::collab::relay_serve(&s);
});
}
let deadline = Instant::now() + Duration::from_secs(5);
while !crate::session::is_alive(&socket) {
assert!(Instant::now() < deadline, "relay never came up");
std::thread::sleep(Duration::from_millis(10));
}
let mut owner = App::new(tmp.path().to_path_buf()).unwrap();
owner.collab.config = Some((socket.clone(), crate::collab::CollabRole::Owner));
let mut guest = App::new(tmp.path().to_path_buf()).unwrap();
guest.collab.config = Some((socket.clone(), crate::collab::CollabRole::Guest));
owner.open_file_at_launch(&file);
guest.open_file_at_launch(&file);
let pump_until =
|owner: &mut App, guest: &mut App, what: &str, done: &dyn Fn(&App, &App) -> bool| {
let deadline = Instant::now() + Duration::from_secs(5);
while !done(owner, guest) {
assert!(Instant::now() < deadline, "never settled: {what}");
owner.poll_collab();
guest.poll_collab();
std::thread::sleep(Duration::from_millis(5));
}
};
pump_until(&mut owner, &mut guest, "bootstrap", &|_, g| {
g.collab
.session
.as_ref()
.is_some_and(|s| s.is_live("f.txt"))
});
guest.editor.insert_str("SESSION ");
pump_until(&mut owner, &mut guest, "session edit converges", &|o, g| {
o.editor.lines == g.editor.lines && o.editor.lines[0].contains("SESSION")
});
guest.split_editor_dir(crate::app::editor_layout::SplitDir::Horizontal, true);
guest
.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert!(
!guest.editor.lines.join("\n").contains('x'),
"the keystroke went into a stale unattached pane and will be wiped"
);
pump_until(&mut owner, &mut guest, "the split pane seeds", &|o, g| {
g.editor.lines == o.editor.lines && g.editor.lines[0].contains("SESSION")
});
assert!(
!owner.editor.lines.join("\n").contains('x'),
"the gated keystroke must not reach the session"
);
}
#[test]
fn cycling_focus_into_the_editor_also_restores_a_maximized_terminal() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminal_maximized = true;
for _ in 0..3 {
app.cycle_focus();
if matches!(app.focus, Pane::Editor) {
break;
}
}
assert!(
matches!(app.focus, Pane::Editor),
"F6 must reach the editor"
);
assert!(
!app.terminal_maximized,
"cycling into the editor must restore it, same as any other route"
);
}
#[test]
fn copy_mode_e_wraps_to_the_next_rows_word_end() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.terminals[0].feed_bytes_for_test(b"\r\nalpha beta\r\nnext word");
app.open_terminal_copy_mode();
app.handle_terminal_copy_mode_key(key(KeyCode::Char('k'), KeyModifiers::NONE));
app.handle_terminal_copy_mode_key(key(KeyCode::Char('0'), KeyModifiers::NONE));
app.handle_terminal_copy_mode_key(key(KeyCode::Char('e'), KeyModifiers::NONE));
let st = app.terminal_copy_mode.as_ref().unwrap();
let first_row = st.line;
assert_eq!(st.col, 4, "first e lands on the end of 'alpha'");
app.handle_terminal_copy_mode_key(key(KeyCode::Char('e'), KeyModifiers::NONE));
assert_eq!(
app.terminal_copy_mode.as_ref().unwrap().col,
9,
"second e lands on the end of 'beta'"
);
app.handle_terminal_copy_mode_key(key(KeyCode::Char('e'), KeyModifiers::NONE));
let st = app.terminal_copy_mode.as_ref().unwrap();
assert_eq!(
st.line,
first_row + 1,
"e at the row's last word must wrap to the next row"
);
assert_eq!(st.col, 3, "and land on the end of 'next'");
}
#[test]
fn copy_mode_e_skips_blank_rows_to_the_next_word_end() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.terminals[0].feed_bytes_for_test(b"\r\nalpha\r\n\r\n\r\nnext word");
app.open_terminal_copy_mode();
for _ in 0..3 {
app.handle_terminal_copy_mode_key(key(KeyCode::Char('k'), KeyModifiers::NONE));
}
app.handle_terminal_copy_mode_key(key(KeyCode::Char('0'), KeyModifiers::NONE));
app.handle_terminal_copy_mode_key(key(KeyCode::Char('e'), KeyModifiers::NONE));
let st = app.terminal_copy_mode.as_ref().unwrap();
let alpha_row = st.line;
assert_eq!(st.col, 4, "first e lands on the end of 'alpha'");
app.handle_terminal_copy_mode_key(key(KeyCode::Char('e'), KeyModifiers::NONE));
let st = app.terminal_copy_mode.as_ref().unwrap();
assert_eq!(
st.line,
alpha_row + 3,
"e skips the two blank rows to the row with the next word"
);
assert_eq!(st.col, 3, "and lands on the end of 'next'");
}
#[test]
fn the_terminal_image_yields_to_an_open_context_menu() {
let (_tmp, mut app) =
app_with_baked_terminal_image(crate::iterm2_inline::InlineImageProtocol::ITerm2);
assert!(app.terminal_image_payload().is_some());
let l = app.overlays.terminal_image.layout().unwrap().clone();
app.context_menu = Some(ContextMenu {
crumb: None,
scroll: Default::default(),
submenu_scroll: Default::default(),
look: MenuLook::Panel,
keyed: true,
origin: (l.cell_x, l.cell_y),
items: vec![
MenuEntry::Item {
label: String::from("Rename Terminal"),
action: MenuAction::RenameTerminal(0),
},
MenuEntry::Item {
label: String::from("Clear"),
action: MenuAction::ClearTerminal(0),
},
],
selected: 0,
open_submenu: None,
submenu_selected: 0,
target_dir: PathBuf::new(),
});
app.update_terminal_image_overlay();
assert!(
app.terminal_image_payload().is_none(),
"the menu must win over the picture while it is open"
);
}
#[test]
fn a_wheel_on_the_pane_border_scrolls_even_when_the_child_tracks_the_mouse() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let mut feed = Vec::new();
for i in 0..80 {
feed.extend_from_slice(format!("row-{i}\r\n").as_bytes());
}
feed.extend_from_slice(b"\x1b[?1000h");
app.terminals[0].feed_bytes_for_test(&feed);
term.draw(|f| app.render(f)).unwrap();
let area = app.terminals[0].last_area;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::ScrollUp,
column: area.x,
row: area.y,
modifiers: KeyModifiers::NONE,
});
assert!(
app.terminals[0].scroll_display_offset() > 0,
"the border notch must scroll the scrollback, not vanish"
);
}
#[test]
fn shift_end_reaches_an_alt_screen_program() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.terminals[0].feed_bytes_for_test(b"\x1b[?1049h");
app.handle_terminal_key(key(KeyCode::End, KeyModifiers::SHIFT));
let expected = key_to_bytes(
key(KeyCode::End, KeyModifiers::SHIFT),
app.terminals[0].app_cursor_keys(),
);
assert!(!expected.is_empty());
let written = app.terminals[0].written_bytes_for_test();
assert!(
written.ends_with(&expected),
"Shift+End must be encoded to the program in the alt screen, wrote {written:?}"
);
}
#[test]
fn a_wrapped_prompt_does_not_push_the_url_off_a_maximized_pane() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"sleep",
&[String::from("30")],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, 24)).unwrap();
app.toggle_terminal_maximize();
term.draw(|f| app.render(f)).unwrap();
let inner = app.terminals[0].last_inner;
let h = inner.height as usize;
assert!(
h >= 16,
"the maximized panel must leave slack for the wrapped prompt; got {h} rows"
);
app.terminals[0].feed_bytes_for_test("\r\n".repeat(h * 2).as_bytes());
app.terminals[0].feed_bytes_for_test(b"\r\nhttp://drift.io");
app.open_terminal_quick_select();
app.terminals[0]
.feed_bytes_for_test(format!("\r\n{}", "p".repeat(inner.width as usize * 4)).as_bytes());
app.terminals[0].feed_bytes_for_test(b"\r\nx1\r\nx2\r\nx3");
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer().clone();
let joined: String = (inner.y..inner.y + inner.height)
.flat_map(|y| {
(inner.x..inner.x + inner.width)
.map(move |x| (x, y))
.map(|(x, y)| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
})
.collect();
assert!(
joined.contains("ttp://drift.io") && !joined.contains("http://drift.io"),
"a four-row prompt must not cost the URL its place on screen, and a \
label must still cover its first cell: {joined:?}"
);
}
#[test]
fn quick_select_labels_follow_content_that_streams_below_them() {
let tmp = 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 30")],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
let backend = ratatui::backend::TestBackend::new(80, 24);
let mut term = ratatui::Terminal::new(backend).unwrap();
app.toggle_terminal_maximize();
term.draw(|f| app.render(f)).unwrap();
let h = app.terminals[0].last_inner.height as usize;
assert!(
h >= 16,
"the maximized panel must leave rows for the scroll this test drives; got {h} rows"
);
app.terminals[0].feed_bytes_for_test("\r\n".repeat(h * 2).as_bytes());
app.terminals[0].feed_bytes_for_test(b"\r\nhttp://drift.io");
app.open_terminal_quick_select();
assert!(
app.terminal_quick_select
.as_ref()
.is_some_and(|s| s.hints.iter().any(|h| h.text.contains("drift.io"))),
"staging: the URL is hinted"
);
app.terminals[0].feed_bytes_for_test(b"\r\nx1\r\nx2\r\nx3");
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer().clone();
let inner = app.terminals[0].last_inner;
let joined: String = (inner.y..inner.y + inner.height)
.flat_map(|y| {
(inner.x..inner.x + inner.width)
.map(move |x| (x, y))
.map(|(x, y)| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
})
.collect();
assert!(
joined.contains("ttp://drift.io") && !joined.contains("http://drift.io"),
"a label must still overlay the URL's first cell after the content\n\
scrolled (the 'h' covered, the tail intact); pane text: {joined:?}"
);
}
#[test]
fn quick_select_sees_a_match_that_wraps_the_pane_edge_whole() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
let backend = ratatui::backend::TestBackend::new(80, 24);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let w = app.terminals[0].last_inner.width as usize;
let mut chunk = String::from("\r\n");
chunk.push_str(&"x".repeat(w - 6));
chunk.push_str("http://drift.io");
app.terminals[0].feed_bytes_for_test(chunk.as_bytes());
app.open_terminal_quick_select();
let state = app
.terminal_quick_select
.as_ref()
.expect("staging: the pane holds at least the wrapped URL");
let url = state
.hints
.iter()
.find(|h| h.text.starts_with("http://drift.io"))
.unwrap_or_else(|| {
panic!(
"the wrapped URL must be staged whole; hints were: {:?}",
state
.hints
.iter()
.map(|h| (h.line, h.start, h.text.as_str()))
.collect::<Vec<_>>()
)
});
assert_eq!(
url.start,
w - 6,
"the label anchors on the URL's first cell, not the wrap row"
);
assert!(
!url.tail.is_empty(),
"the continuation row rides along as a tail segment"
);
assert!(
!state.hints.iter().any(|h| h.text == "/drift.io"),
"the wrapped tail must not be labelled as a path fragment; hints: {:?}",
state
.hints
.iter()
.map(|h| h.text.as_str())
.collect::<Vec<_>>()
);
let label = url.label.clone();
for c in label.chars() {
app.handle_terminal_key(key(KeyCode::Char(c), KeyModifiers::NONE));
}
assert!(
app.terminal_quick_select.is_none(),
"committing a label must close quick-select"
);
assert!(
app.status.contains("Copied"),
"commit must report the copy, status was: {}",
app.status
);
}
#[test]
fn quick_select_closes_instead_of_hijacking_another_pane() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
let mut feed = Vec::new();
for i in 0..10 {
feed.extend_from_slice(
format!("\r\nhttp://a{i}.io http://b{i}.io http://c{i}.io").as_bytes(),
);
}
feed.extend_from_slice(b"\r\n");
app.terminals[0].feed_bytes_for_test(&feed);
app.open_terminal_quick_select();
let st = app.terminal_quick_select.as_ref().expect("staging: hints");
assert!(st.hints.len() > 26, "staging: two-char labels required");
let prefix = st
.hints
.iter()
.find(|h| h.label.len() == 2)
.expect("staging: a two-char label")
.label
.chars()
.next()
.unwrap();
app.terminals.push(
crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sleep",
&[String::from("30")],
tmp.path(),
)
.unwrap(),
);
app.active_terminal = 1;
app.handle_terminal_quick_select_key(key(KeyCode::Char(prefix), KeyModifiers::NONE));
assert!(
app.terminal_quick_select.is_none(),
"a pane switch closes quick select instead of hijacking the new pane"
);
assert!(
!app.terminals[1].has_hints_for_test(),
"the sibling pane must not inherit the old pane's hint labels"
);
}
#[test]
fn terminal_find_navigation_survives_streaming_output() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
let mut feed = Vec::new();
for i in 0..40 {
feed.extend_from_slice(format!("pad-{i}\r\n").as_bytes());
}
feed.extend_from_slice(b"match-one\r\nmatch-two\r\nmatch-three\r\n");
app.terminals[0].feed_bytes_for_test(&feed);
app.handle_terminal_key(key(KeyCode::Char('f'), KeyModifiers::SUPER));
for c in "match".chars() {
app.handle_terminal_key(key(KeyCode::Char(c), KeyModifiers::NONE));
}
let anchored_line = |app: &App| -> String {
let (lines, now) = app.terminals[0].find_lines_and_clock();
let (clock, abs, _c, _l) = app.terminal_find_match.expect("an anchored match");
let abs = abs - (now - clock) as i32;
let row = lines.iter().rposition(|l| l.start <= abs).unwrap_or(0);
lines[row].text.clone()
};
assert!(
anchored_line(&app).contains("match-three"),
"staging: the first anchor is the bottom-most occurrence"
);
app.terminals[0].feed_bytes_for_test(b"filler\r\nfiller\r\nfiller\r\nfiller\r\nfiller\r\n");
app.handle_terminal_key(key(KeyCode::Enter, KeyModifiers::SHIFT));
assert!(
anchored_line(&app).contains("match-two"),
"prev from the drifted anchor must land on the occurrence above it, got {:?}",
anchored_line(&app)
);
}
#[test]
fn clearing_a_pane_resets_its_find_anchor_and_count() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.terminals[0].feed_bytes_for_test(b"\r\nmatch-a\r\nmatch-b\r\n");
app.handle_terminal_key(key(KeyCode::Char('f'), KeyModifiers::SUPER));
for c in "match".chars() {
app.handle_terminal_key(key(KeyCode::Char(c), KeyModifiers::NONE));
}
assert!(
app.terminal_find_match.is_some(),
"staging: an anchored match exists"
);
assert!(
app.terminal_find.as_ref().unwrap().match_count > 0,
"staging: matches counted"
);
app.clear_terminal_at(0);
assert!(
app.terminal_find_match.is_none(),
"the cleared grid must drop the stale anchor"
);
assert_eq!(
app.terminal_find.as_ref().unwrap().match_count,
0,
"the match count must reflect the emptied grid"
);
}
#[test]
fn terminal_find_closes_instead_of_straying_to_another_pane() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.terminals[0].feed_bytes_for_test(b"\r\nerror one\r\nerror two\r\n");
app.handle_terminal_key(key(KeyCode::Char('f'), KeyModifiers::SUPER));
app.handle_terminal_key(key(KeyCode::Char('e'), KeyModifiers::NONE));
assert!(
app.terminals[0].has_search_for_test(),
"staging: the owning pane is highlighted"
);
app.terminals.push(
crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sleep",
&[String::from("30")],
tmp.path(),
)
.unwrap(),
);
app.active_terminal = 1;
app.sync_focus_flags();
assert!(
app.terminal_find.is_none(),
"a pane switch closes find instead of retargeting the new pane"
);
assert!(
!app.terminals[0].has_search_for_test(),
"the owning pane's highlight must be cleared on close"
);
}
#[test]
fn copy_mode_closes_instead_of_hijacking_another_pane() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.open_terminal_copy_mode();
assert!(app.terminal_copy_mode.is_some());
app.terminals.push(
crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sleep",
&[String::from("30")],
tmp.path(),
)
.unwrap(),
);
app.active_terminal = 1;
app.handle_terminal_copy_mode_key(key(KeyCode::Char('j'), KeyModifiers::NONE));
assert!(
app.terminal_copy_mode.is_none(),
"a pane switch closes copy mode instead of hijacking the new pane"
);
assert!(
app.terminals[1].selection().is_none(),
"the sibling pane must not inherit a painted selection"
);
}
#[test]
fn the_deleted_side_says_so_in_its_pane_title() {
let tmp = tempfile::tempdir().unwrap();
let mut app = open_modify_delete(tmp.path(), true);
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer().clone();
let a = buf.area;
let text: String = (a.y..a.y + a.height)
.map(|y| {
(a.x..a.x + a.width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n");
assert!(text.contains("INCOMING (theirs): deleted"), "{text}");
assert!(text.contains("CURRENT (yours)") && !text.contains("CURRENT (yours): deleted"));
}
#[test]
fn finished_settles_pending_matches_pane_and_command() {
assert!(finished_settles_pending(
7,
" cargo build\n",
7,
"cargo build"
));
assert!(
!finished_settles_pending(8, "cargo build", 7, "cargo build"),
"wrong pane"
);
assert!(
!finished_settles_pending(7, "cargo test", 7, "cargo build"),
"different command"
);
}
#[test]
fn a_parked_launch_aborts_when_its_pane_dies_or_never_reports_a_mark() {
use std::time::Duration;
let quick = Duration::from_secs(1);
let over = PRELAUNCH_MARK_GRACE + Duration::from_secs(1);
assert!(
pending_abort_reason(false, false, quick).is_some(),
"a closed pane aborts immediately"
);
assert_eq!(
pending_abort_reason(true, false, over),
None,
"a busy pane (long build) waits indefinitely"
);
assert_eq!(
pending_abort_reason(true, true, quick),
None,
"an idle pane inside the grace window keeps waiting for the mark"
);
assert!(
pending_abort_reason(true, true, over).is_some(),
"idle past the grace with no mark = shell integration never reported; abort"
);
}
#[test]
fn a_restored_terminal_pane_shows_the_output_it_had_before() {
let tmp = tempfile::tempdir().unwrap();
let session_path = tmp.path().join("sessions.json");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminal_session_path = session_path.clone();
app.split_terminal().unwrap();
app.terminals[0].resize(80, 24);
app.terminals[0].feed_bytes_for_test(b"unique-marker-249\r\n");
app.save_terminal_session();
let raw = std::fs::read_to_string(&session_path).unwrap();
assert!(
raw.contains("unique-marker-249"),
"the store carries the pane's output: {raw}"
);
let mut app2 = App::new(tmp.path().to_path_buf()).unwrap();
app2.terminal_session_path = session_path.clone();
app2.restore_terminal_session_with(true);
app2.terminals[0].resize(80, 24);
let (lines, _) = app2.terminals[0].grid_lines();
assert!(
lines.iter().any(|l| l.contains("unique-marker-249")),
"the restored pane repaints its previous output: {lines:?}"
);
}
#[test]
fn restored_output_is_painted_above_the_new_prompt() {
use crate::widgets::terminal::PtyTerminal;
let tmp = tempfile::tempdir().unwrap();
let transcript: Vec<String> = (1..=3).map(|i| format!("restored-line-{i}")).collect();
let t = PtyTerminal::new_with_transcript(tmp.path(), &transcript).unwrap();
let (lines, _) = t.grid_lines();
let row_of = |needle: &str| lines.iter().position(|l| l.contains(needle));
let first = row_of("restored-line-1").expect("first restored line is on screen");
let last = row_of("restored-line-3").expect("last restored line is on screen");
assert!(
first < last,
"the transcript keeps its order: {first} then {last} in {lines:?}"
);
let after: Vec<&String> = lines.iter().skip(last + 1).collect();
assert!(
after.iter().all(|l| !l.contains("restored-line")),
"nothing restored appears below the last restored line: {after:?}"
);
}
#[test]
fn an_alt_screen_frame_is_not_persisted_as_scrollback() {
let tmp = tempfile::tempdir().unwrap();
let session_path = tmp.path().join("sessions.json");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminal_session_path = session_path.clone();
app.split_terminal().unwrap();
app.terminals[0].resize(80, 24);
app.terminals[0].feed_bytes_for_test(b"real-scrollback-line\r\n");
app.terminals[0].feed_bytes_for_test(b"\x1b[?1049h");
app.terminals[0].feed_bytes_for_test(b"FULLSCREEN-TUI-FRAME\r\n");
assert!(
app.terminals[0].alt_screen(),
"the pane is on the alternate screen"
);
app.save_terminal_session();
let raw = std::fs::read_to_string(&session_path).unwrap();
assert!(
!raw.contains("FULLSCREEN-TUI-FRAME"),
"the TUI's frame must not reach the store: {raw}"
);
}
#[test]
fn a_pane_record_without_a_transcript_still_parses() {
let rec: crate::terminal_session::PaneRecord =
serde_json::from_str(r#"{"cwd":"/tmp","name":null}"#).unwrap();
assert!(rec.transcript.is_empty());
}
#[test]
fn a_recorded_frame_is_the_visible_screen_not_the_scrollback() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0].last_inner = ratatui::layout::Rect {
x: 1,
y: 1,
width: 40,
height: 20,
};
app.terminals[0].resize(40, 20);
let mut flood = String::new();
for i in 0..200 {
flood.push_str(&format!("line-{i}\r\n"));
}
app.terminals[0].feed_bytes_for_test(flood.as_bytes());
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
app.record_active_screen();
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
let path = std::fs::read_dir(app.workspace_root())
.unwrap()
.filter_map(|e| e.ok().map(|e| e.path()))
.find(|p| p.extension().is_some_and(|x| x == "cast"))
.expect("a .cast file was written");
let text = std::fs::read_to_string(&path).unwrap();
let frame = text
.lines()
.skip(1)
.filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
.find(|ev| ev[1] == "o")
.and_then(|ev| ev[2].as_str().map(String::from))
.expect("an output event");
let header: serde_json::Value =
serde_json::from_str(text.lines().next().expect("a header")).expect("the header is JSON");
let rows = frame.split("\r\n").count();
let (all, top) = app.terminals[0].grid_lines();
let visible = all.len() - (-top).max(0) as usize;
assert_eq!(
rows, visible,
"the frame must be the {visible}-row screen, not {rows} rows of history"
);
assert_eq!(
(header["width"].as_u64(), header["height"].as_u64()),
(Some(40), Some(rows as u64)),
"the geometry a player reads must describe the frame that follows it"
);
assert!(
!frame.contains("line-100"),
"the frame reaches back into scrollback: {frame:?}"
);
assert!(
frame.contains("line-198\r\nline-199"),
"the frame must carry the screen's rows in order: {frame:?}"
);
assert!(
frame.contains("line-199"),
"the frame must show what was last on screen: {:?}",
&frame[..frame.len().min(120)]
);
assert!(
!frame.contains("line-0\r\n"),
"the frame reaches back to the first line ever printed"
);
}
#[test]
fn a_recorded_frames_rows_wrap_at_the_width_its_header_declares() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0].last_inner = ratatui::layout::Rect {
x: 1,
y: 1,
width: 40,
height: 20,
};
app.terminals[0].resize(40, 20);
let long: String = (0..100u8).map(|i| char::from(b'0' + (i % 7))).collect();
app.terminals[0].feed_bytes_for_test(format!("\r\n{long}\r\n").as_bytes());
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
app.record_active_screen();
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
let path = std::fs::read_dir(app.workspace_root())
.unwrap()
.filter_map(|e| e.ok().map(|e| e.path()))
.find(|p| p.extension().is_some_and(|x| x == "cast"))
.expect("a .cast file was written");
let text = std::fs::read_to_string(&path).unwrap();
let header: serde_json::Value =
serde_json::from_str(text.lines().next().expect("a header")).expect("the header is JSON");
let frame = text
.lines()
.skip(1)
.filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
.find(|ev| ev[1] == "o")
.and_then(|ev| ev[2].as_str().map(String::from))
.expect("an output event");
let body = frame
.strip_prefix("\u{1b}[H\u{1b}[2J")
.expect("a recorded frame opens with clear-and-home, then the rows");
let declared = header["width"]
.as_u64()
.expect("the header declares a width");
assert_eq!(
declared, 40,
"the fixture's own premise: the header must declare the 40 columns the pane was sized to"
);
let rows: Vec<&str> = body.split("\r\n").collect();
assert!(
rows.iter().any(|r| r.starts_with(&long[..8])),
"the payload must still be on the visible screen: {body:?}"
);
assert!(
rows.windows(2)
.any(|w| w[0] == &long[..40] && w[1] == &long[40..80]),
"the long line must wrap at column {declared}, the width the header promises: {body:?}"
);
let widest = body.split("\r\n").map(visible_width).max().unwrap_or(0);
assert!(
widest as u64 <= declared,
"the widest row is {widest} columns and the header promises {declared}: \
a player sizes its window from the header, so the frame has to fit it"
);
}
#[test]
#[ignore = "needs agg; set CROFT_TEST_AGG"]
fn a_recorded_cast_converts_to_a_gif_with_agg() {
let agg = std::env::var("CROFT_TEST_AGG").unwrap();
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let size = |app: &mut App, w: u16, h: u16| {
app.terminals[0].last_inner = ratatui::layout::Rect {
x: 1,
y: 1,
width: w,
height: h,
};
app.terminals[0].resize(w, h);
};
size(&mut app, 60, 10);
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
app.terminals[0].feed_bytes_for_test(
b"\x1b[1;31mbold red\x1b[0m \x1b[30;42mblack on green\x1b[0m \x1b[4;34munderlined\x1b[0m\r\n",
);
app.record_active_screen();
size(&mut app, 40, 8);
app.terminals[0].feed_bytes_for_test(
"a line long enough to wrap at forty columns, with \u{4e00} wide text\r\n".as_bytes(),
);
app.record_active_screen();
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
let cast = std::fs::read_dir(app.workspace_root())
.unwrap()
.filter_map(|e| e.ok().map(|e| e.path()))
.find(|p| p.extension().is_some_and(|x| x == "cast"))
.expect("a .cast file was written");
let gif = tmp.path().join("out.gif");
let out = std::process::Command::new(&agg)
.arg(&cast)
.arg(&gif)
.output()
.unwrap();
assert!(
out.status.success(),
"agg refused the cast: {}",
String::from_utf8_lossy(&out.stderr)
);
let bytes = std::fs::read(&gif).unwrap();
assert!(bytes.starts_with(b"GIF89a"), "a GIF was written");
}
#[test]
fn a_recorded_resize_precedes_the_frame_it_was_drawn_for() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0].last_inner = ratatui::layout::Rect {
x: 1,
y: 1,
width: 40,
height: 20,
};
app.terminals[0].resize(40, 20);
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
app.record_active_screen();
app.terminals[0].last_inner = ratatui::layout::Rect {
x: 1,
y: 1,
width: 60,
height: 10,
};
app.record_active_screen();
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
let path = std::fs::read_dir(app.workspace_root())
.unwrap()
.filter_map(|e| e.ok().map(|e| e.path()))
.find(|p| p.extension().is_some_and(|x| x == "cast"))
.expect("a .cast file was written");
let text = std::fs::read_to_string(&path).unwrap();
let kinds: Vec<String> = text
.lines()
.skip(1)
.filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
.filter_map(|ev| ev[1].as_str().map(String::from))
.collect();
assert_eq!(
kinds,
vec!["o", "r", "o"],
"the cast must carry the new geometry before the frame drawn at it, got {kinds:?}"
);
}
#[test]
fn a_fold_mid_recording_narrows_the_frame_and_announces_nothing() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0].last_inner = ratatui::layout::Rect {
x: 1,
y: 1,
width: 40,
height: 20,
};
app.terminals[0].resize(40, 20);
app.terminals[0].feed_bytes_for_test(b"\r\nbefore the fold\r\n");
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
app.record_active_screen();
app.terminals[0].last_inner.width = 0;
app.terminals[0].resize(0, 20);
app.record_active_screen();
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
let path = std::fs::read_dir(app.workspace_root())
.unwrap()
.filter_map(|e| e.ok().map(|e| e.path()))
.find(|p| p.extension().is_some_and(|x| x == "cast"))
.expect("a .cast file was written");
let text = std::fs::read_to_string(&path).unwrap();
let events: Vec<(String, String)> = text
.lines()
.skip(1)
.filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
.filter_map(|ev| {
Some((
ev[1].as_str()?.to_string(),
ev[2].as_str().unwrap_or_default().to_string(),
))
})
.collect();
let widths: Vec<usize> = events
.iter()
.filter(|(kind, _)| kind == "o")
.map(|(_, frame)| {
frame
.strip_prefix("\u{1b}[H\u{1b}[2J")
.expect("a recorded frame opens with clear-and-home")
.split("\r\n")
.map(visible_width)
.max()
.unwrap_or(0)
})
.collect();
assert_eq!(widths.len(), 2, "one frame each side of the fold");
let (before, after) = (widths[0], widths[1]);
assert!(
after < before,
"the fold must narrow the recorded rows, got {before} then {after}"
);
assert_eq!(
after, 2,
"and the folded frame carries the GRID's two-column floor (`cols.max(2)` \
in src/widgets/terminal.rs) rather than a snapshot taken before the \
resize landed"
);
assert!(
events.iter().all(|(kind, _)| kind == "o"),
"a fold announces no geometry, got {:?}",
events.iter().map(|(k, _)| k).collect::<Vec<_>>()
);
}
#[test]
fn a_widened_pane_announces_its_new_geometry_before_the_wider_frame() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0].last_inner = ratatui::layout::Rect {
x: 1,
y: 1,
width: 40,
height: 20,
};
app.terminals[0].resize(40, 20);
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
app.record_active_screen();
app.terminals[0].last_inner.width = 80;
app.terminals[0].resize(80, 20);
let wide: String = std::iter::repeat_n('w', 60).collect();
app.terminals[0].feed_bytes_for_test(format!("\r\n{wide}\r\n").as_bytes());
app.record_active_screen();
app.record_active_screen();
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
let path = std::fs::read_dir(app.workspace_root())
.unwrap()
.filter_map(|e| e.ok().map(|e| e.path()))
.find(|p| p.extension().is_some_and(|x| x == "cast"))
.expect("a .cast file was written");
let text = std::fs::read_to_string(&path).unwrap();
let header: serde_json::Value =
serde_json::from_str(text.lines().next().expect("a header")).expect("the header is JSON");
let declared = header["width"]
.as_u64()
.expect("the header declares a width");
let events: Vec<serde_json::Value> = text
.lines()
.skip(1)
.filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
.collect();
let kinds: Vec<&str> = events.iter().filter_map(|ev| ev[1].as_str()).collect();
assert_eq!(
kinds,
vec!["o", "r", "o", "o"],
"the widened geometry must reach the player BEFORE the frame wrapped \
for it, and exactly once, got {kinds:?}"
);
let widest = events[2][2]
.as_str()
.expect("the second frame is text")
.strip_prefix("\u{1b}[H\u{1b}[2J")
.expect("a recorded frame opens with clear-and-home")
.split("\r\n")
.map(visible_width)
.max()
.unwrap_or(0);
assert!(
widest as u64 > declared,
"the fixture must produce a frame the HEADER cannot hold, or the \
resize event is not load-bearing: widest {widest}, header {declared}"
);
assert_eq!(
events[1][2].as_str(),
Some("80x20"),
"the `r` must name the pane's new geometry, got {:?}",
events[1]
);
}
#[test]
fn a_recording_writes_a_parseable_asciicast() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0].last_area = ratatui::layout::Rect {
x: 0,
y: 0,
width: 80,
height: 24,
};
app.terminals[0].last_inner = ratatui::layout::Rect {
x: 1,
y: 1,
width: 78,
height: 22,
};
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
assert!(app.recording.is_some(), "recording started: {}", app.status);
app.record_terminal_output("\u{1b}[32m\"quoted\" \\ back\u{1b}[0m");
app.record_resize(132, 50);
app.record_terminal_output("after the resize");
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
assert!(app.recording.is_none(), "recording stopped: {}", app.status);
let path = std::fs::read_dir(app.workspace_root())
.unwrap()
.filter_map(|e| e.ok().map(|e| e.path()))
.find(|p| p.extension().is_some_and(|x| x == "cast"))
.expect("a .cast file was written");
let text = std::fs::read_to_string(&path).expect("the cast file exists");
let mut lines = text.lines();
let header: serde_json::Value =
serde_json::from_str(lines.next().expect("a header line")).expect("header is JSON");
assert_eq!(header["version"], 2);
assert_eq!(
header["width"], 78,
"the header must carry the GRID size, not the bordered pane's"
);
assert_eq!(header["height"], 22);
let mut kinds = Vec::new();
let mut last_time = -1.0f64;
for line in lines {
let ev: serde_json::Value = serde_json::from_str(line)
.unwrap_or_else(|e| panic!("event is not JSON: {line:?} — {e}"));
let t = ev[0].as_f64().expect("a numeric timestamp");
assert!(
t >= last_time,
"time went backwards: {t} after {last_time} — a player would hang"
);
last_time = t;
kinds.push(ev[1].as_str().unwrap_or("?").to_string());
}
assert!(
kinds.iter().any(|k| k == "o") && kinds.iter().any(|k| k == "r"),
"both output and resize events must reach the file: {kinds:?}"
);
}
#[test]
fn the_minus_button_still_closes_and_the_chevron_collapses() {
let (_tmp, mut app, _term) = app_with_terminal_panes(3);
let fold = app.panel_hits.collapse_buttons[1];
assert!(fold.width > 0, "the collapse button must be painted");
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
fold.x + 1,
fold.y,
));
assert_eq!(app.terminals.len(), 3, "collapsing must never close a pane");
assert!(app.terminals[1].collapsed, "the clicked pane folded");
let close = app.panel_hits.close_buttons[0];
assert!(close.width > 0, "the close button must be painted");
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
close.x + 1,
close.y,
));
assert_eq!(
app.terminals.len(),
2,
"`-` still closes the pane - it was NOT repurposed to collapse"
);
}
#[test]
fn ctrl_b_belongs_to_the_app_in_a_focused_terminal() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.bottom_panel_tab = BottomPanelTab::Terminal;
let before = app.show_tree;
app.handle_key(key(KeyCode::Char('b'), KeyModifiers::CONTROL))
.unwrap();
assert_eq!(
app.show_tree, before,
"Ctrl+B in a focused terminal must not move the side bar"
);
assert!(
app.terminals[app.active_terminal]
.written_bytes_for_test()
.contains(&0x02),
"Ctrl+B must reach the PTY as 0x02"
);
app.handle_key(key(KeyCode::Char('b'), KeyModifiers::SUPER))
.unwrap();
assert_ne!(
app.show_tree, before,
"Cmd+B still toggles the side bar from the terminal"
);
}
fn pty_bytes(app: &App) -> Vec<u8> {
app.terminals[app.active_terminal].written_bytes_for_test()
}
#[test]
fn ctrl_q_in_a_focused_terminal_reaches_the_app_instead_of_quitting() {
let tmp = tempfile::tempdir().unwrap();
let mut app = focused_terminal_app(tmp.path());
app.handle_key(key(KeyCode::Char('q'), KeyModifiers::CONTROL))
.unwrap();
assert!(!app.quit, "Ctrl+Q in the terminal must not quit croft");
assert!(
pty_bytes(&app).contains(&0x11),
"Ctrl+Q must reach the PTY as 0x11"
);
}
#[test]
fn ctrl_v_in_a_focused_terminal_reaches_the_app_and_shifted_paste_still_pastes() {
let tmp = tempfile::tempdir().unwrap();
let mut app = focused_terminal_app(tmp.path());
app.handle_key(key(KeyCode::Char('v'), KeyModifiers::CONTROL))
.unwrap();
assert_eq!(
pty_bytes(&app),
vec![0x16],
"Ctrl+V must reach the PTY as 0x16"
);
assert!(!app.status.starts_with("Paste"), "Ctrl+V must not paste");
for chord in [
key(
KeyCode::Char('V'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
),
key(KeyCode::Char('v'), KeyModifiers::SUPER),
] {
app.status.clear();
let before = pty_bytes(&app).len();
app.handle_key(chord).unwrap();
let sent = pty_bytes(&app)[before..].to_vec();
assert!(
!sent.contains(&0x16),
"{chord:?} pastes rather than sending 0x16"
);
assert!(
!sent.is_empty() || app.status.starts_with("Paste"),
"{chord:?} still pastes the clipboard"
);
}
}
#[test]
fn right_clicking_a_collapsed_strip_offers_to_expand_it() {
let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
app.toggle_terminal_collapse(1);
term.draw(|f| app.render(f)).unwrap();
let strip = app.panel_hits.collapsed_strips[1];
assert_eq!(strip.width, 1, "precondition: the strip is painted");
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Right),
strip.x,
strip.y + 1,
));
let menu = app
.context_menu
.as_ref()
.expect("a strip right-click opens the pane menu");
let labels: Vec<String> = menu
.items
.iter()
.filter_map(|e| match e {
MenuEntry::Item { label, .. } => Some(label.clone()),
_ => None,
})
.collect();
assert!(
labels.iter().any(|l| l == "Expand Terminal"),
"the folded pane offers the way back out: {labels:?}"
);
}
#[test]
fn restore_all_is_inert_while_a_pane_is_maximized() {
let (_tmp, mut app, _term) = app_with_terminal_panes(3);
app.toggle_terminal_collapse(2);
app.active_terminal = 0;
app.toggle_terminal_pane_maximize();
assert!(app.terminal_pane_maximized, "precondition");
assert!(app.handle_cmd_k_chord(key(KeyCode::Char(']'), KeyModifiers::NONE)));
assert!(
app.terminals[2].collapsed,
"restore must not silently clear folding the user cannot see"
);
}
#[test]
fn jumping_to_a_captured_line_reveals_the_folded_pane_that_holds_it() {
let (_tmp, mut app, _term) = app_with_terminal_panes(3);
let pid = app.terminals[1]
.shell_pid()
.expect("a real shell to key on");
app.terminals[1].feed_bytes_for_test(b"a captured line worth jumping to\r\n");
app.toggle_terminal_collapse(1);
assert!(
app.terminals[1].collapsed,
"precondition: the target is folded"
);
assert_ne!(app.active_terminal, 1, "precondition: focus left it");
app.captures.push(crate::widgets::captures::CapturedLine {
pane: String::from("build"),
shell_pid: Some(pid),
message: String::from("captured"),
line: String::from("a captured line worth jumping to"),
anchor: None,
});
app.captures_open_selected();
assert_eq!(
app.active_terminal, 1,
"the jump must land on the pane that HOLDS the captured line"
);
assert!(
!app.terminals[1].collapsed,
"and that pane must be visible: applying a selection to a folded pane \
shows the user nothing"
);
}
#[test]
fn maximizing_from_a_folded_strip_shows_the_pane_the_menu_named() {
let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
app.toggle_terminal_collapse(1);
term.draw(|f| app.render(f)).unwrap();
let strip = app.panel_hits.collapsed_strips[1];
let folded_width = app.terminals[1].last_area.width;
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Right),
strip.x,
strip.y + 1,
));
let action = app
.context_menu
.as_ref()
.expect("a strip right-click opens the pane menu")
.items
.iter()
.find_map(|e| match e {
MenuEntry::Item { label, action } if label == "Maximize Terminal" => {
Some(action.clone())
}
_ => None,
})
.expect("a folded pane still offers maximize: the entry carries its own index");
app.context_menu = None;
let root = app.workspace_root().to_path_buf();
app.dispatch_menu_action(action, root);
term.draw(|f| app.render(f)).unwrap();
assert_eq!(
app.active_terminal, 1,
"the maximized pane is the one the menu named"
);
assert!(
app.terminals[1].last_area.width > folded_width,
"the folded pane is painted across the panel, not left as a strip: \
{folded_width} then {}",
app.terminals[1].last_area.width
);
assert!(
app.panel_hits.collapsed_strips.iter().all(|r| r.width == 0),
"no strip survives maximize, or a click could land on a pane that is not painted"
);
}
fn tracking_terminal_app(modes: &[u8]) -> (App, tempfile::TempDir, u16, u16, u16, u16) {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
draw(&mut app, 120, 40);
app.terminals[0].feed_bytes_for_test(modes);
let inner = app.terminals[0].last_inner;
assert!(
inner.width > 6 && inner.height > 3,
"terminal grid must be laid out, got {inner:?}"
);
let (col, row) = (inner.x + 3, inner.y + 2);
let (lr, lc) = app.terminals[0]
.cell_at(col, row)
.expect("the test cell lies inside the grid");
(app, tmp, col, row, lc, lr)
}
#[test]
fn a_click_over_a_mouse_tracking_child_is_forwarded_as_press_and_release() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, col, row, lc, lr) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
assert!(app.terminals[0].mouse_reporting());
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert_eq!(
String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
format!("\x1b[<0;{};{}M", lc + 1, lr + 1),
"the press is an SGR button-0 report at the 1-based grid cell"
);
assert!(
app.terminals[0].selection().is_none(),
"a forwarded press plants no croft selection: the child owns the click"
);
let uid = app.terminals[0].uid();
assert!(
matches!(
app.gesture,
Some(Gesture::TerminalForwarded { fp, .. })
if fp.pane == uid && fp.press == (col, row) && !fp.selecting
),
"the pane (by uid) and cell that got the press are remembered for the release"
);
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row));
assert_eq!(
String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
format!("\x1b[<0;{c};{r}M\x1b[<0;{c};{r}m", c = lc + 1, r = lr + 1),
"the release follows as the lower-case SGR terminator"
);
assert!(
!matches!(app.gesture, Some(Gesture::TerminalForwarded { .. })),
"the release ends the forwarded gesture"
);
assert!(
app.terminals[0].selection().is_none(),
"nor does the release leave a highlight behind"
);
}
#[test]
fn a_click_over_a_child_that_is_not_tracking_stays_a_croft_selection() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, col, row, _, _) = tracking_terminal_app(b"");
assert!(!app.terminals[0].mouse_reporting());
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert!(
app.terminals[0].written_bytes_for_test().is_empty(),
"no report is written to a child that never asked for the mouse"
);
assert!(
app.terminals[0].selection().is_some(),
"the click anchors croft's own selection as before"
);
assert!(!matches!(
app.gesture,
Some(Gesture::TerminalForwarded { .. })
));
}
#[test]
fn shift_click_over_a_tracking_child_keeps_the_click_for_croft() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, col, row, _, _) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
let mut shift = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
shift.modifiers = KeyModifiers::SHIFT;
app.handle_mouse(shift);
assert!(
app.terminals[0].written_bytes_for_test().is_empty(),
"Shift+click is croft's: nothing is reported to the child"
);
assert!(
app.terminals[0].selection().is_some(),
"Shift+click anchors croft's own selection over a tracking child"
);
assert!(!matches!(
app.gesture,
Some(Gesture::TerminalForwarded { .. })
));
}
#[test]
fn a_click_on_the_pane_border_is_not_forwarded_to_a_tracking_child() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, col, _, _, _) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
let border_row = app.terminals[0].last_area.y;
assert!(
app.terminals[0].cell_at(col, border_row).is_none(),
"the top border is not a grid cell"
);
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
col,
border_row,
));
assert!(
app.terminals[0].written_bytes_for_test().is_empty(),
"no report for a cell outside the child's grid"
);
assert!(!matches!(
app.gesture,
Some(Gesture::TerminalForwarded { .. })
));
}
#[test]
fn a_forwarded_drag_reports_motion_only_when_the_child_asked_for_it() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, col, row, lc, lr) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
col + 2,
row + 1,
));
assert_eq!(
String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
format!("\x1b[<0;{};{}M", lc + 1, lr + 1),
"under 1000 the drag adds nothing after the press: the child asked for clicks"
);
let sel = app.terminals[0]
.selection()
.expect("under 1000 the drag is croft's text selection");
let (sr, sc, er, ec) = sel.normalised();
assert_eq!(
(sr, sc, er, ec),
(lr as i32, lc, lr as i32 + 1, lc + 2),
"the selection runs from the press cell to the drag cell"
);
assert!(
matches!(
app.gesture,
Some(Gesture::TerminalForwarded { fp, .. }) if fp.selecting
),
"the gesture is still open and marked as croft's selection"
);
app.handle_mouse(mouse(
MouseEventKind::Up(MouseButton::Left),
col + 2,
row + 1,
));
assert_eq!(
String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
format!(
"\x1b[<0;{};{}M\x1b[<0;{};{}m",
lc + 1,
lr + 1,
lc + 3,
lr + 2
),
"the child that got the press still gets the release"
);
assert!(
app.terminals[0].selection().is_some_and(|s| s.has_area()),
"and croft's selection survives the release for copying"
);
assert!(app.gesture.is_none());
let (mut app, _tmp, col, row, lc, lr) = tracking_terminal_app(b"\x1b[?1002h\x1b[?1006h");
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
col + 2,
row + 1,
));
assert_eq!(
String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
format!(
"\x1b[<0;{};{}M\x1b[<32;{};{}M",
lc + 1,
lr + 1,
lc + 3,
lr + 2
),
"under 1002 the drag is a button-0 motion report at the new cell"
);
assert!(app.terminals[0].selection().is_none());
}
#[test]
fn a_forwarded_release_outside_the_pane_is_clamped_to_its_grid() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, col, row, lc, lr) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
let inner = app.terminals[0].last_inner;
assert!(
app.terminals[0].cell_at(0, 0).is_none(),
"(0,0) must be outside the pane, or nothing is clamped"
);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), 0, 0));
assert_eq!(
String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
format!("\x1b[<0;{};{}M\x1b[<0;1;1m", lc + 1, lr + 1),
"the release lands on the grid's top-left cell, the nearest to (0,0)"
);
assert_eq!(
app.terminals[0].clamp_to_grid(u16::MAX, u16::MAX),
(inner.x + inner.width - 1, inner.y + inner.height - 1),
"the far corner clamps to the last cell, never one past it"
);
assert!(app.gesture.is_none());
}
#[test]
fn a_forwarded_release_over_a_sibling_pane_goes_to_the_pane_that_got_the_press() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert_eq!(app.terminals.len(), 2, "two panes are visible");
app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h\x1b[?1006h");
assert!(app.terminals[0].mouse_reporting());
assert!(!app.terminals[1].mouse_reporting());
let inner0 = app.terminals[0].last_inner;
let inner1 = app.terminals[1].last_inner;
assert!(
inner0.width > 4 && inner0.height > 3 && inner1.width > 4 && inner1.height > 3,
"both panes need a real grid: {inner0:?} {inner1:?}"
);
let (col, row) = (inner0.x + 2, inner0.y + 1);
let (lr, lc) = app.terminals[0].cell_at(col, row).unwrap();
let (far_col, far_row) = (inner1.x + 2, row);
assert!(
app.terminals[1].cell_at(far_col, far_row).is_some()
&& app.terminals[0].cell_at(far_col, far_row).is_none(),
"the release cell must belong to pane 1 only"
);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
app.handle_mouse(mouse(
MouseEventKind::Up(MouseButton::Left),
far_col,
far_row,
));
let (clamped_col, clamped_row) = app.terminals[0].clamp_to_grid(far_col, far_row);
let (er, ec) = app.terminals[0].cell_at(clamped_col, clamped_row).unwrap();
assert_eq!(
String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
format!(
"\x1b[<0;{};{}M\x1b[<0;{};{}m",
lc + 1,
lr + 1,
ec + 1,
er + 1
),
"pane 0 gets the press and the release, the latter at its nearest edge cell"
);
assert!(
app.terminals[1].written_bytes_for_test().is_empty(),
"pane 1 never saw a press, so it gets no release either"
);
assert!(app.gesture.is_none());
}
#[test]
fn a_forwarded_release_finds_its_pane_after_an_earlier_pane_closes() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert_eq!(app.terminals.len(), 2);
app.terminals[1].feed_bytes_for_test(b"\x1b[?1000h\x1b[?1006h");
let pressed_uid = app.terminals[1].uid();
let inner = app.terminals[1].last_inner;
let (col, row) = (inner.x + 2, inner.y + 1);
let (lr, lc) = app.terminals[1].cell_at(col, row).unwrap();
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert!(matches!(
app.gesture,
Some(Gesture::TerminalForwarded { fp, .. }) if fp.pane == pressed_uid
));
assert!(app.close_terminal_at(0), "the EARLIER pane closes");
assert_eq!(app.terminals.len(), 1);
assert_eq!(
app.terminals[0].uid(),
pressed_uid,
"the pressed pane now sits at index 0"
);
term.draw(|f| app.render(f)).unwrap();
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row));
let written = String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()).into_owned();
assert!(
written.starts_with(&format!("\x1b[<0;{};{}M", lc + 1, lr + 1)),
"the press went to the pane before the close: {written:?}"
);
assert!(
written.ends_with('m') && written.matches("\x1b[<0;").count() == 2,
"the release still reaches the same pane after it moved to index 0: {written:?}"
);
assert!(app.gesture.is_none());
}
#[test]
fn a_click_only_drag_keeps_extending_the_origin_pane_after_the_active_pane_moves() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h\x1b[?1006h");
let inner = app.terminals[0].last_inner;
assert!(
inner.width > 6 && inner.height > 3,
"pane 0 needs a grid: {inner:?}"
);
let (col, row) = (inner.x + 2, inner.y + 1);
let (lr, lc) = app.terminals[0].cell_at(col, row).unwrap();
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert_eq!(
app.active_terminal, 0,
"the press activates the pressed pane"
);
app.cycle_terminal();
assert_eq!(app.active_terminal, 1, "Cmd+] moved the active pane");
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
col + 3,
row + 1,
));
let sel = app.terminals[0]
.selection()
.expect("the origin pane carries the drag-selection");
let (sr, sc, er, ec) = sel.normalised();
assert_eq!(
(sr, sc, er, ec),
(lr as i32, lc, lr as i32 + 1, lc + 3),
"the origin's selection runs from the press cell to the drag cell"
);
assert!(
app.terminals[1].selection().is_none(),
"the pane that merely became active gets no selection"
);
app.handle_mouse(mouse(
MouseEventKind::Up(MouseButton::Left),
col + 3,
row + 1,
));
assert!(
app.terminals[0].selection().is_some_and(|s| s.has_area()),
"the release finalises the origin's selection"
);
assert!(
String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()).ends_with('m'),
"and the origin child gets the release"
);
assert!(
app.terminals[1].written_bytes_for_test().is_empty(),
"the active pane's child sees nothing"
);
assert!(app.gesture.is_none());
}
#[test]
fn a_double_click_over_a_tracking_child_is_two_forwarded_clicks_not_a_word_select() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, col, row, lc, lr) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
app.terminals[0].feed_bytes_for_test(b"\x1b[3;1Hhello_world_token\r\n");
let (text, idx) = app.terminals[0]
.line_text_at(col, row)
.expect("the click must resolve to a grid cell");
assert!(
text.contains("hello_world_token") && idx < text.len(),
"the click must land ON the token: {text:?} at {idx}"
);
for _ in 0..2 {
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row));
}
let written = String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()).into_owned();
let pair = format!("\x1b[<0;{c};{r}M\x1b[<0;{c};{r}m", c = lc + 1, r = lr + 1);
assert_eq!(
written,
format!("{pair}{pair}"),
"two press/release pairs reach the child"
);
assert!(
app.terminals[0].selection().is_none(),
"no word is selected: the pair was never croft's"
);
}
#[test]
fn shift_drag_over_a_1002_child_selects_with_croft_and_reports_nothing() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, col, row, _, _) = tracking_terminal_app(b"\x1b[?1002h\x1b[?1006h");
let mut ev = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ev.modifiers = KeyModifiers::SHIFT;
app.handle_mouse(ev);
let mut ev = mouse(MouseEventKind::Drag(MouseButton::Left), col + 3, row + 1);
ev.modifiers = KeyModifiers::SHIFT;
app.handle_mouse(ev);
let mut ev = mouse(MouseEventKind::Up(MouseButton::Left), col + 3, row + 1);
ev.modifiers = KeyModifiers::SHIFT;
app.handle_mouse(ev);
assert!(
app.terminals[0].written_bytes_for_test().is_empty(),
"Shift keeps every event of the gesture from the child"
);
assert!(
app.terminals[0].selection().is_some_and(|s| s.has_area()),
"and croft's selection has the dragged area"
);
}
#[test]
fn copy_on_select_fires_for_a_click_only_forwarded_drag() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, _, _, _, _) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
app.copy_on_select = true;
app.terminals[0].feed_bytes_for_test(b"\x1b[H");
app.terminals[0].feed_bytes_for_test(b"copy-me-please\r\n");
let inner = app.terminals[0].last_inner;
let (x0, y0) = (inner.x, inner.y);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), x0, y0));
app.handle_mouse(mouse(MouseEventKind::Drag(MouseButton::Left), x0 + 13, y0));
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), x0 + 13, y0));
assert_eq!(
crate::clipboard::read_string().as_deref(),
Some("copy-me-please"),
"the origin pane's selection landed on the clipboard"
);
}
#[test]
fn edge_autoscroll_stands_down_while_the_forwarded_pane_is_not_active_and_resumes() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h\x1b[?1006h");
app.terminals[1].feed_bytes_for_test("row\r\n".repeat(200).as_bytes());
let inner = app.terminals[0].last_inner;
let (col, row) = (inner.x + 2, inner.y + 1);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert_eq!(app.active_terminal, 0);
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
col,
inner.y.saturating_sub(1),
));
assert!(
matches!(
app.gesture,
Some(Gesture::TerminalForwarded {
autoscroll: Some(_),
..
})
),
"precondition: auto-scroll armed"
);
app.cycle_terminal();
assert_eq!(app.active_terminal, 1);
let pane1_before = app.terminals[1].viewport_top_line();
std::thread::sleep(std::time::Duration::from_millis(40));
assert!(
!app.tick_terminal_autoscroll(),
"the tick stands down for a non-origin active pane"
);
assert_eq!(
app.terminals[1].viewport_top_line(),
pane1_before,
"pane 1's viewport did not move"
);
assert!(
matches!(
app.gesture,
Some(Gesture::TerminalForwarded {
autoscroll: Some(_),
..
})
),
"the armed state is held, not dropped"
);
app.cycle_terminal_back();
assert_eq!(app.active_terminal, 0);
std::thread::sleep(std::time::Duration::from_millis(40));
assert!(
app.tick_terminal_autoscroll(),
"back on the origin pane the tick resumes without a new Drag"
);
}
#[test]
fn a_bare_forwarded_click_never_reaches_the_clipboard() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, _, _, _, _) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
app.copy_on_select = true;
app.terminals[0].feed_bytes_for_test(b"\x1b[H");
app.terminals[0].feed_bytes_for_test(b"not-for-the-clipboard\r\n");
let inner = app.terminals[0].last_inner;
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
inner.x + 2,
inner.y,
));
app.handle_mouse(mouse(
MouseEventKind::Up(MouseButton::Left),
inner.x + 2,
inner.y,
));
assert_eq!(
crate::clipboard::read_string().as_deref().unwrap_or(""),
"",
"a click that was the child's copies nothing"
);
assert!(app.terminals[0].selection().is_none());
}
#[test]
fn edge_autoscroll_is_dropped_when_the_forwarded_pane_closes_mid_gesture() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h\x1b[?1006h");
let inner = app.terminals[0].last_inner;
let (col, row) = (inner.x + 2, inner.y + 1);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
col,
inner.y.saturating_sub(1),
));
assert!(
matches!(
app.gesture,
Some(Gesture::TerminalForwarded {
autoscroll: Some(_),
..
})
),
"precondition: armed"
);
assert!(
app.close_terminal_at(0),
"the origin pane closes under the held button"
);
std::thread::sleep(std::time::Duration::from_millis(40));
assert!(!app.tick_terminal_autoscroll(), "nothing to scroll");
assert!(app.gesture.is_none(), "the gesture is dropped, not held");
}
#[test]
fn a_drag_after_releasing_a_terminal_selection_does_not_change_it_or_arm_autoscroll() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
app.terminals[0].feed_bytes_for_test("row\r\n".repeat(120).as_bytes());
let inner = app.terminals[0].last_inner;
let (col, row) = (inner.x + 2, inner.y + 2);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
app.handle_mouse(mouse(MouseEventKind::Drag(MouseButton::Left), col + 6, row));
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col + 6, row));
let finished = app.terminals[0]
.selection()
.expect("selection survives mouse-up");
assert!(finished.has_area(), "precondition: selection has area");
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
col + 1,
inner.y.saturating_sub(1),
));
assert_eq!(
app.terminals[0].selection(),
Some(finished),
"a stray drag after release must not overwrite the finished selection"
);
std::thread::sleep(std::time::Duration::from_millis(40));
assert!(
!app.tick_terminal_autoscroll(),
"a stray drag after release must not arm edge auto-scroll"
);
}
#[test]
fn a_press_after_a_lost_forwarded_release_releases_the_child_and_drops_autoscroll() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h\x1b[?1006h");
let inner = app.terminals[0].last_inner;
let (col, row) = (inner.x + 2, inner.y + 1);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
col,
inner.y.saturating_sub(1),
));
let before_new_press =
String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()).into_owned();
assert!(
!before_new_press.ends_with('m'),
"precondition: child has not seen a release yet: {before_new_press:?}"
);
let seam = app.sidebar_splitter_x.expect("sidebar splitter drawn");
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), seam, 5));
let after_new_press =
String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()).into_owned();
assert!(
after_new_press.ends_with('m'),
"abandoning the forwarded press must still send a release to the child: {after_new_press:?}"
);
assert_eq!(app.gesture, Some(Gesture::Splitter(SplitterDrag::Sidebar)));
std::thread::sleep(std::time::Duration::from_millis(40));
assert!(
!app.tick_terminal_autoscroll(),
"replacing the gesture must drop edge auto-scroll"
);
}
#[test]
fn an_untouched_offer_expires_and_a_closed_pane_takes_its_offer_along() {
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")));
app.ssh_offer.as_mut().unwrap().since =
std::time::Instant::now() - SSH_OFFER_TTL - std::time::Duration::from_secs(1);
app.expire_ssh_offer();
assert!(
app.ssh_offer.is_none(),
"an offer past its TTL clears itself"
);
app.split_terminal().unwrap();
let second = app.terminals[1].uid();
app.consider_ssh_offer(second, Some(String::from("db-1")));
assert!(app.ssh_offer.as_ref().is_some_and(|o| o.pane == second));
assert!(app.close_terminal_at(1));
app.expire_ssh_offer();
assert!(
app.ssh_offer.is_none(),
"the pane that owned the offer is gone"
);
assert!(
!app.ssh_offer_seen.contains_key(&second),
"and its per-pane memory went with it"
);
}
#[test]
fn a_pane_that_moves_to_another_host_loses_the_old_offer_even_if_the_new_one_is_excluded() {
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("b")];
app.consider_ssh_offer(pane, Some(String::from("a")));
assert!(app.ssh_offer.as_ref().is_some_and(|o| o.host == "a"));
app.consider_ssh_offer(pane, Some(String::from("b")));
assert!(
app.ssh_offer.is_none(),
"the offer for A fell when the pane moved to B"
);
assert!(app.status.is_empty());
}
#[test]
fn switching_the_offer_off_and_on_forgets_what_each_pane_was_last_seen_on() {
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.is_some());
let mut prefs = crate::prefs::Prefs {
disable_remote_offer: true,
..Default::default()
};
app.apply_merged_settings(&prefs);
assert!(app.ssh_offer.is_none(), "the switch took the offer down");
prefs.disable_remote_offer = false;
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.host == "db-1"),
"the first session seen after a re-enable is offered"
);
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn a_restore_reattaches_a_shell_still_running_in_its_pane_host() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("ws");
std::fs::create_dir_all(&root).unwrap();
let spec = crate::pane_host::PaneSpec {
socket: tmp.path().join("pane.sock"),
cwd: Some(root.clone()),
env: Vec::new(),
cols: 80,
rows: 24,
argv: ["sh", "-c", "echo still-$((6*7)); exec sh"]
.iter()
.map(|a| a.to_string())
.collect(),
};
let socket = spec.socket.clone();
let host = std::thread::spawn(move || crate::pane_host::serve(&spec));
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while !crate::session::is_alive(&socket) {
assert!(
std::time::Instant::now() < deadline,
"the host never listened"
);
std::thread::sleep(std::time::Duration::from_millis(10));
}
let root_key = root.display().to_string();
let pane = |name: &str, host: Option<String>| crate::terminal_session::PaneRecord {
cwd: root_key.clone(),
name: Some(String::from(name)),
lane: None,
transcript: vec![String::from("old transcript")],
host,
};
let session = tmp.path().join("sessions.json");
let rec = crate::terminal_session::SessionRecord {
panes: vec![
pane("kept", Some(socket.display().to_string())),
pane(
"gone",
Some(tmp.path().join("dead.sock").display().to_string()),
),
],
active: 0,
};
crate::terminal_session::save_for_root(&session, &root_key, rec).unwrap();
let mut app = App::new(root.clone()).unwrap();
app.terminal_session_path = session.clone();
app.restore_terminal_session_with(true);
assert_eq!(app.terminals.len(), 2);
let kept = &app.terminals[0];
if kept.host_socket() != Some(socket.as_path()) {
let alive = crate::session::is_alive(&socket);
let attach = crate::widgets::terminal::PtyTerminal::attach_hosted(&socket)
.map(|_| ())
.map_err(|e| format!("{e:#}"));
panic!(
"not reattached: the pane's host is {:?}; the live host answers a probe now: \
{alive}; attaching to it now gives {attach:?}",
kept.host_socket()
);
}
assert_eq!(kept.manual_name(), Some("kept"));
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the reattached pane to show the live shell's screen",
|| kept.grid_lines().0.iter().any(|l| l.contains("still-42")),
);
let (lines, _) = kept.grid_lines();
assert!(
!lines.iter().any(|l| l.contains("old transcript")),
"the live screen, not the saved transcript: {lines:?}"
);
let gone = &app.terminals[1];
assert_eq!(
gone.host_socket(),
None,
"a dead host falls back to a fresh shell"
);
assert_eq!(gone.manual_name(), Some("gone"));
let saved = crate::terminal_session::load(&session);
let saved = &saved[&root_key];
assert_eq!(
saved.panes[0].host.as_deref(),
Some(socket.to_str().unwrap())
);
assert_eq!(saved.panes[1].host, None);
drop(app);
host.join().unwrap().unwrap();
}
#[test]
fn a_view_request_from_a_pane_opens_the_file_in_the_editor() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("report.txt");
std::fs::write(&target, "hello from a pane").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
let sock = seat_view_listener(&mut app, tmp.path());
let client = view_from_a_pane(&sock, &target);
drain_until_answered(&mut app, &client);
assert_eq!(client.join().unwrap(), crate::view_ipc::ViewReply::Ok);
let open = app.editor.editors[app.editor.active_index()].path.clone();
assert_eq!(
open.as_deref(),
Some(target.as_path()),
"the requested file must be the active tab"
);
assert!(
app.focus == Pane::Editor,
"the user asked to look at it, so focus follows"
);
}
#[test]
fn a_pane_command_carries_the_view_socket_when_one_is_bound() {
let mut cmd = portable_pty::CommandBuilder::new("/bin/sh");
crate::widgets::terminal::apply_pane_env(
&mut cmd,
Some(std::path::Path::new("/tmp/croft-view-probe.sock")),
);
let carried: Vec<(String, String)> = cmd
.iter_extra_env_as_str()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
assert!(
carried
.iter()
.any(|(k, v)| k == crate::view_ipc::SOCK_ENV && v == "/tmp/croft-view-probe.sock"),
"a pane's command must carry the view socket: {carried:?}"
);
assert!(
carried
.iter()
.any(|(k, v)| k == "TERM" && v == "xterm-256color"),
"TERM must still be applied: {carried:?}"
);
}
#[test]
fn a_pane_command_clears_an_inherited_view_socket_when_none_is_bound() {
let mut cmd = portable_pty::CommandBuilder::new("/bin/sh");
cmd.env(crate::view_ipc::SOCK_ENV, "/tmp/outer-croft.sock");
crate::widgets::terminal::apply_pane_env(&mut cmd, None);
let carried: Vec<(String, String)> = cmd
.iter_full_env_as_str()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
assert!(
!carried.iter().any(|(k, _)| k == crate::view_ipc::SOCK_ENV),
"an inherited socket must be CLEARED, not merely not-added, or a \
nested croft routes `croft view` to its parent: {carried:?}"
);
assert!(
carried
.iter()
.any(|(k, v)| k == "TERM" && v == "xterm-256color"),
"TERM must still reach the child: {carried:?}"
);
}
#[test]
fn a_pane_command_omits_the_view_socket_when_none_is_bound() {
let mut cmd = portable_pty::CommandBuilder::new("/bin/sh");
crate::widgets::terminal::apply_pane_env(&mut cmd, None);
let carried: Vec<(String, String)> = cmd
.iter_extra_env_as_str()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
assert!(
!carried.iter().any(|(k, _)| k == crate::view_ipc::SOCK_ENV),
"no socket bound means no variable: {carried:?}"
);
assert!(
carried.iter().any(|(k, _)| k == "TERM"),
"and the pane is still given its terminal identity: {carried:?}"
);
}
#[test]
fn a_pane_names_croft_as_its_terminal_not_the_host() {
let mut cmd = portable_pty::CommandBuilder::new("/bin/sh");
cmd.env("TERM_PROGRAM", "ghostty");
cmd.env("KITTY_WINDOW_ID", "1");
cmd.env("GHOSTTY_RESOURCES_DIR", "/usr/share/ghostty");
cmd.env("LC_TERMINAL", "iTerm2");
cmd.env("PATH_PROBE_1453", "kept");
crate::widgets::terminal::apply_pane_env(&mut cmd, None);
let env: std::collections::HashMap<String, String> = cmd
.iter_full_env_as_str()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
assert_eq!(env.get("TERM_PROGRAM").map(String::as_str), Some("croft"));
assert_eq!(
env.get("TERM_PROGRAM_VERSION").map(String::as_str),
Some(env!("CARGO_PKG_VERSION"))
);
for host_only in ["KITTY_WINDOW_ID", "GHOSTTY_RESOURCES_DIR", "LC_TERMINAL"] {
assert!(!env.contains_key(host_only), "{host_only} leaked: {env:?}");
}
assert!(
matches!(
env.get("CROFT_INLINE_IMAGES").map(String::as_str),
Some("0" | "1")
),
"a pane says whether its images show: {env:?}"
);
assert_eq!(env.get("PATH_PROBE_1453").map(String::as_str), Some("kept"));
assert_eq!(env.get("TERM").map(String::as_str), Some("xterm-256color"));
}
#[test]
fn right_does_not_accept_a_terminal_suggestion_the_typing_outran() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.term_suggestion = Some((0, String::from("g"), String::from("it status")));
app.handle_terminal_key(key(KeyCode::Char('i'), KeyModifiers::NONE));
app.term_suggestion = Some((0, String::from("g"), String::from("it status")));
app.handle_terminal_key(key(KeyCode::Right, KeyModifiers::NONE));
let written = String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()).into_owned();
assert!(!written.contains("it status"), "{written:?}");
}
#[test]
fn a_pane_program_osc52_copy_reaches_the_clipboard_on_the_drain_tick() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
crate::clipboard::test_clip::mock_write("before");
let script =
"read x; printf '\\033]52;c;\\007'; read y; printf '\\033]52;c;Y29waWVk\\007'; sleep 30";
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from(script)],
tmp.path(),
)
.unwrap();
app.terminals[0].write_input(b"\n");
let deadline = std::time::Instant::now() + std::time::Duration::from_millis(300);
while std::time::Instant::now() < deadline {
app.drain_terminal_bells();
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert_eq!(
crate::clipboard::test_clip::mock_read().as_deref(),
Some("before"),
"an empty OSC 52 store must not wipe the clipboard"
);
app.terminals[0].write_input(b"\n");
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the pane's OSC 52 copy to reach the clipboard",
|| {
app.drain_terminal_bells();
crate::clipboard::test_clip::mock_read().as_deref() == Some("copied")
},
);
assert!(
app.status.starts_with("Copied 6 chars"),
"the copy is reported like croft's own, status: {}",
app.status
);
}
#[test]
fn a_terminal_recording_shows_its_own_badge_until_it_stops() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert!(!status_row(&term).contains("CAST"));
app.toggle_session_recording();
assert!(app.recording.is_some(), "{}", app.status);
app.status.clear();
term.draw(|f| app.render(f)).unwrap();
let row = status_row(&term);
assert!(row.contains("● CAST 0:00"), "{row}");
assert!(!row.contains("REC "), "not the macro badge: {row}");
app.toggle_session_recording();
term.draw(|f| app.render(f)).unwrap();
assert!(!status_row(&term).contains("CAST"));
}
fn visible_width(row: &str) -> usize {
crate::remote_connect::strip_ansi(row.as_bytes())
.chars()
.count()
}
fn recorded_frames(app: &App) -> Vec<String> {
let path = std::fs::read_dir(app.workspace_root())
.unwrap()
.filter_map(|e| e.ok().map(|e| e.path()))
.find(|p| p.extension().is_some_and(|x| x == "cast"))
.expect("a .cast file was written");
std::fs::read_to_string(&path)
.unwrap()
.lines()
.skip(1)
.filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
.filter(|ev| ev[1] == "o")
.filter_map(|ev| ev[2].as_str().map(String::from))
.collect()
}
#[test]
fn a_recorded_frame_keeps_the_panes_colours_and_cursor() {
let tmp = 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("exec sleep 600")],
tmp.path(),
)
.unwrap();
app.terminals[0].last_inner = ratatui::layout::Rect {
x: 1,
y: 1,
width: 60,
height: 10,
};
app.terminals[0].resize(60, 10);
app.terminals[0].feed_bytes_for_test(b"\r\n\x1b[1;31mQQRED\x1b[0m plain\r\n");
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
app.record_active_screen();
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
let frames = recorded_frames(&app);
let frame = frames.first().expect("an output event");
assert!(
frame.contains("\u{1b}[1;31mQQRED\u{1b}[0m plain"),
"the red, bold run is recorded as SGR: {frame:?}"
);
let (row, col) = app.terminals[0]
.screen_ansi_wrapped()
.1
.expect("the quiet pane shows its cursor");
assert!(
frame.ends_with(&format!("\u{1b}[{};{}H\u{1b}[?25h", row + 1, col + 1)),
"the cursor is put back where the pane has it: {frame:?}"
);
}
#[test]
fn a_hidden_cursor_is_recorded_hidden() {
assert_eq!(super::cursor_suffix(None), "\u{1b}[?25l");
assert_eq!(super::cursor_suffix(Some((0, 0))), "\u{1b}[1;1H\u{1b}[?25h");
assert_eq!(super::cursor_suffix(Some((3, 6))), "\u{1b}[4;7H\u{1b}[?25h");
}
#[test]
fn a_masked_row_is_recorded_plain_and_its_neighbours_in_colour() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0].last_inner = ratatui::layout::Rect {
x: 1,
y: 1,
width: 60,
height: 10,
};
app.terminals[0].resize(60, 10);
let key = "AKIAIOSFODNN7EXAMPLE";
app.terminals[0].feed_bytes_for_test(
format!("\r\n\x1b[32mexport KEY={key}\x1b[0m\r\n\x1b[34mQQBLUE\x1b[0m\r\n").as_bytes(),
);
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
app.record_active_screen();
app.run_command(crate::widgets::command_palette::Command::ToggleSessionRecording);
let frames = recorded_frames(&app);
let frame = frames.first().expect("an output event");
assert!(!frame.contains(key), "the key reached the cast: {frame:?}");
let masked = frame
.split("\r\n")
.find(|row| row.contains("export KEY="))
.expect("the masked row is recorded");
assert!(
!masked.contains('\u{1b}'),
"the masked row carries no escapes: {masked:?}"
);
assert!(
frame.contains("\u{1b}[34mQQBLUE\u{1b}[0m"),
"the next row keeps its colour: {frame:?}"
);
}
#[test]
fn a_colour_run_is_not_split_by_the_wrap_column_or_a_wide_char() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0].resize(20, 6);
let long = "y".repeat(30);
app.terminals[0].feed_bytes_for_test(
format!("\r\n\x1b[33m{long}\x1b[0m\r\n\x1b[32mab\u{4e2d}cd\x1b[0m\r\n").as_bytes(),
);
let (rows, _) = app.terminals[0].screen_ansi_wrapped();
let ansi: Vec<&str> = rows.iter().map(|(_, a, _)| a.as_str()).collect();
let first = format!("\x1b[33m{}\x1b[0m", "y".repeat(20));
assert!(
ansi.contains(&first.as_str()),
"the wrapped row is one run: {ansi:?}"
);
assert!(
ansi.contains(&"\x1b[32mab\u{4e2d}cd\x1b[0m"),
"the wide char sits inside its run: {ansi:?}"
);
}
#[test]
fn ctrl_n_leaves_terminals_vim_and_shifted_chords_alone() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "b.txt", "keep\n");
app.handle_key(key(KeyCode::Char('n'), KeyModifiers::SUPER))
.unwrap();
type_keys(&mut app, "note");
app.save();
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(app.prompt.is_none());
assert_eq!(app.editor.path, None);
assert_eq!(app.editor.lines[0], "note");
assert!(app.editor.dirty);
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "b.txt", "keep\n");
app.handle_key(key(
KeyCode::Char('n'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
app.handle_key(key(
KeyCode::Char('n'),
KeyModifiers::SUPER | KeyModifiers::ALT,
))
.unwrap();
app.focus = Pane::Terminal;
app.handle_key(key(KeyCode::Char('n'), KeyModifiers::CONTROL))
.unwrap();
app.focus_pane(Pane::Editor);
app.vim.enabled = true;
app.handle_key(key(KeyCode::Char('n'), KeyModifiers::CONTROL))
.unwrap();
assert_eq!(app.editor.tab_count(), 1, "no untitled tab opened");
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("b.txt").as_path())
);
}
#[test]
fn a_multiline_paste_into_a_plain_shell_waits_for_confirmation() {
let (mut app, _tmp) = plain_paste_app();
app.handle_paste(TWO_LINES);
assert_eq!(pasted(&app), "", "nothing runs before the user agrees");
assert!(app.pending_terminal_paste.is_some());
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(pasted(&app), TWO_LINES);
assert!(app.pending_terminal_paste.is_none());
}
#[test]
fn a_click_while_asking_cannot_move_the_paste_to_another_pane() {
let (mut app, _tmp) = two_pane_paste_app();
app.handle_paste(TWO_LINES);
let other = app.panel_hits.rail_rows[1];
left_click(&mut app, other.x + 1, other.y);
assert_eq!(app.active_terminal, 0, "the click is ignored while asking");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(pasted(&app), TWO_LINES, "the checked pane gets the paste");
}
fn wrapped_find_app(text: &str) -> (tempfile::TempDir, App) {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.apply_theme(crate::theme::Theme::BLACK);
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sleep",
&[String::from("60")],
tmp.path(),
)
.unwrap();
app.terminals[0].resize(30, 10);
app.terminals[0].feed_bytes_for_test(format!("\x1b[2J\x1b[H{text}").as_bytes());
app.focus_pane(Pane::Terminal);
app.open_terminal_find();
(tmp, app)
}
fn terminal_find_count(app: &mut App, query: &str) -> usize {
app.terminal_find_set_query(query.to_string());
app.terminal_find.as_ref().unwrap().match_count
}
fn terminal_cell_bg(app: &mut App, row: u16, col: u16) -> ratatui::style::Color {
let area = ratatui::layout::Rect::new(0, 0, 32, 12);
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut app.terminals[0], area, &mut buf);
let first = (1..area.height - 1)
.find(|&y| buf[(1, y)].symbol() == "x")
.expect("the fed text is on screen");
buf[(col + 1, first + row)].bg
}
#[test]
fn terminal_find_matches_across_a_soft_wrap() {
let line = format!("{}connection-refused port 5432\r\n", "x".repeat(24));
let (_tmp, mut app) = wrapped_find_app(&line);
assert_eq!(terminal_find_count(&mut app, "connection-refused"), 1);
assert_eq!(
app.terminal_find.as_ref().unwrap().match_index,
Some(1),
"1 of 1"
);
let reset = ratatui::style::Color::Reset;
let first_half = terminal_cell_bg(&mut app, 0, 26);
let second_half = terminal_cell_bg(&mut app, 1, 8);
assert_ne!(first_half, reset, "the half before the wrap is painted");
assert_eq!(first_half, second_half, "both halves are the active match");
assert_eq!(terminal_cell_bg(&mut app, 0, 10), reset, "the x run is not");
assert_eq!(terminal_cell_bg(&mut app, 1, 14), reset, "nor is `port`");
}
#[test]
fn terminal_find_never_joins_rows_without_a_wrap_and_counts_an_edge_match_once() {
let text = format!("{}connec\r\ntion-refused\r\n", "x".repeat(24));
let (_tmp, mut app) = wrapped_find_app(&text);
assert_eq!(terminal_find_count(&mut app, "connection-refused"), 0);
assert_eq!(
terminal_cell_bg(&mut app, 0, 26),
ratatui::style::Color::Reset
);
assert_eq!(terminal_find_count(&mut app, "connec"), 1);
let edge = format!("{}abcdef{}\r\n", "x".repeat(24), "y".repeat(10));
let (_tmp, mut app) = wrapped_find_app(&edge);
assert_eq!(terminal_find_count(&mut app, "abcdef"), 1);
assert_eq!(
terminal_find_count(&mut app, "fyy"),
1,
"and across the edge"
);
}
#[test]
fn the_terminal_tab_is_still_announced_as_its_terminal() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus = Pane::Terminal;
app.bottom_panel_tab = BottomPanelTab::Terminal;
let snap = app.a11y_snapshot();
assert_eq!(snap.focus, "Terminal 1");
assert_eq!(snap.item, None);
}
#[test]
fn a_command_with_no_output_keeps_the_panes_problems() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let pane = app.run_project_task(long_task("make")).unwrap();
let cwd = tmp.path().to_path_buf();
assert!(app.apply_build_scan(
pane,
Some(&cwd),
"make",
"main.c:7:3: error: expected ';'\n"
));
finish_pane_command(&mut app, pane, Some(0), 10);
assert_eq!(app.problems.groups().len(), 1, "still listed");
app.watch_published_panes.insert(pane);
assert!(!app.apply_build_scan(pane, Some(&cwd), "tsc --watch", "a.c:1:1: error: old\n"));
assert!(app.apply_build_scan(pane, Some(&cwd), "make", "b.c:1:1: error: new\n"));
}
#[test]
fn a_bracketed_paste_into_the_terminal_find_bar_lands_at_the_caret() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.open_terminal_find();
app.terminal_find_set_query(String::from("ac"));
app.terminal_find.as_mut().unwrap().set_caret(1);
app.handle_paste("b\n");
let find = app.terminal_find.as_ref().unwrap();
assert_eq!(find.query, "abc");
assert_eq!(find.caret(), 2, "the caret stays after what was pasted");
}
#[test]
fn the_shell_suggestion_never_draws_over_a_popup() {
use crate::app::popups::Popup;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.command_history =
crate::command_history::CommandHistory::load(&tmp.path().join("hist.jsonl"));
let typed = format!("echo {}", "a".repeat(60));
app.command_history
.entries
.push(crate::command_history::HistoryEntry {
cmd: format!("{typed} && echo done"),
cwd: String::new(),
host: String::new(),
exit: Some(0),
dur_ms: 0,
ts: 0,
});
let script = format!(
"printf '\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\033]133;A\\007$ \\033]133;B\\007{typed}'; sleep 30"
);
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), script],
tmp.path(),
)
.unwrap();
app.active_terminal = 0;
app.show_terminal = true;
app.terminal_maximized = true;
app.focus_pane(Pane::Terminal);
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 45)).unwrap();
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the shell's suggestion to show",
|| {
term.draw(|f| app.render(f)).unwrap();
app.term_suggestion.is_some()
},
);
let mut draw = |app: &mut App, suggest: bool| {
app.term_suggest_enabled = suggest;
term.draw(|f| app.render(f)).unwrap().buffer.clone()
};
let base = draw(&mut app, false);
let shown = draw(&mut app, true);
let suggestion: Vec<(u16, u16)> = base
.content
.iter()
.enumerate()
.filter(|(i, c)| shown.content[*i] != **c)
.map(|(i, _)| base.pos_of(i))
.collect();
assert!(
!suggestion.is_empty(),
"the suggestion must show with no pop-up open"
);
let mut over = Vec::new();
let mut covering = Vec::new();
for p in Popup::ALL {
let _hook = super::popups::open(&mut app, p);
let without = draw(&mut app, false);
let with = draw(&mut app, true);
let popup = |xy: (u16, u16)| {
without[xy].symbol() != base[xy].symbol() || without[xy].bg != base[xy].bg
};
if suggestion.iter().any(|&xy| popup(xy)) {
covering.push(p);
}
let drawn_over = suggestion
.iter()
.filter(|&&xy| with[xy] != without[xy] && popup(xy))
.count();
if drawn_over > 0 {
over.push(format!("{p:?} ({drawn_over} cells)"));
}
super::popups::close(&mut app, p);
assert!(!p.is_open(&app), "{p:?} must close again");
}
assert!(
covering.contains(&Popup::SettingsEditor),
"Settings must cover the suggestion, or this test proves nothing: {covering:?}"
);
assert!(
over.is_empty(),
"the shell's suggestion was drawn over these pop-ups: {}",
over.join(", ")
);
}