use super::*;
use crate::gradient::lerp_rgb;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
fn key(code: KeyCode, mods: KeyModifiers) -> KeyEvent {
KeyEvent::new(code, mods)
}
/// Shell command that prints `probe` on its own line WITHOUT the typed
/// command line spelling the probe out.
///
/// The terminal end-to-end tests find their probe by searching the rendered
/// grid for it, but the shell echoes what was typed, so a literal
/// `printf '<probe>\n'` puts two matching rows on screen. Under load the echo
/// arrives first, the wait loop is satisfied by it, and the row search lands
/// on the echoed command: its quoting shifts the columns, and the selection
/// comes back as `"oft-e2e-638881\\n"` instead of the probe (issue #226).
/// Splitting the probe across two printf arguments leaves the echo carrying
/// only the fragments, so nothing but the OUTPUT can ever match.
fn probe_command(probe: &str) -> String {
let (head, tail) = probe.split_at(1);
format!("printf '%s%s\\n' '{head}' '{tail}'\r")
}
/// Run the probe command in the app's embedded terminal and wait until the
/// probe is on screen. Panics with the actual screen contents if it never
/// arrives, so a failure says what the terminal was showing instead of
/// unwrapping `None` several lines later.
///
/// The wait is load-scaled (#397): a real shell has to start, run the
/// command, and have the reader thread drain the bytes into the grid, and
/// what stretches that is contention from the rest of the suite, not this
/// test. The fixed 15s this replaced (#226 had raised it from 3s) is what a
/// quiet machine still gets at the floor; the captured failure had the probe
/// command echoed on screen and unanswered at 15s, a starved shell rather
/// than a broken one. `spawn_budget` rather than `await_spawned` so the
/// panic can keep showing the screen.
fn await_terminal_probe(app: &mut App, probe: &str) {
app.terminal_mut()
.write_input(probe_command(probe).as_bytes());
let base = crate::test_budget::tests::TERMINAL_PROBE_BASE;
let budget = crate::test_budget::spawn_budget(base);
let started = std::time::Instant::now();
while started.elapsed() < budget {
if app.terminal().visible_text().contains(probe) {
return;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
panic!(
"the shell never printed the probe {probe:?} within {budget:?} ({base:?} base x{} total \
for calibration and load); if this is a real failure it would also fail at 1x, so \
re-run the full suite on the unmodified merge base under the same load before \
suspecting your diff. Terminal showed:\n{}",
budget.as_millis() / base.as_millis().max(1),
app.terminal().visible_text()
);
}
#[test]
fn minimap_rgba_paints_chars_skips_whitespace() {
let mut e = crate::widgets::editor::Editor::new();
// Two leading spaces then a glyph: indentation must read as bg, the glyph
// in fg. Second (blank) line keeps the file at 2 rows so each maps to one
// pixel row in a height-2 canvas.
e.lines = vec![String::from(" x"), String::new()];
let bg = (0u8, 0, 0);
let fg = (200u8, 200, 200);
let buf = e.minimap_rgba(4, 2, 2, bg, fg);
let px = |x: u32, y: u32| {
let i = ((y * 4 + x) * 4) as usize;
(buf[i], buf[i + 1], buf[i + 2])
};
assert_eq!(px(0, 0), bg, "indentation stays background");
assert_eq!(px(1, 0), bg, "indentation stays background");
assert_eq!(px(2, 0), fg, "the glyph is painted in the default fg");
}
#[test]
fn minimap_goto_moves_the_cursor() {
// The editor force-follows the cursor on render, so minimap navigation must
// move the caret to the target line or the scroll would snap straight back
// (the bug behind "clicking the minimap does nothing").
let mut e = crate::widgets::editor::Editor::new();
e.lines = (0..200).map(|i| format!("line {i}")).collect();
e.goto_line_centered(100);
assert_eq!(e.cursor_row, 100, "caret jumps to the clicked line");
assert!(e.scroll <= 100, "viewport scrolls toward the target");
}
#[test]
fn minimap_short_file_does_not_stretch() {
// Two lines into a tall (h=10) canvas with content_h=4: the lines occupy
// the top 4 rows; the rest of the strip stays background (no stretching a
// short file down the whole column).
let mut e = crate::widgets::editor::Editor::new();
e.lines = vec![String::from("x"), String::from("y")];
let bg = (0u8, 0, 0);
let fg = (200u8, 200, 200);
let buf = e.minimap_rgba(1, 10, 4, bg, fg);
let px = |y: u32| {
let i = (y * 4) as usize;
(buf[i], buf[i + 1], buf[i + 2])
};
assert_eq!(px(0), fg, "first line sits at the top");
assert_eq!(
px(8),
bg,
"rows past the content stay background, not stretched"
);
}
#[test]
fn minimap_viewport_box_lightens_visible_rows_only() {
// 1px-wide, 4px-tall black raster; viewport = top 2 of 4 lines.
let base = vec![0u8; 4 * 4];
let out = composite_minimap_viewport(
&base,
1,
4,
MinimapOverlay {
top: 0,
rows: 2,
total: 4,
light: false,
selection: None,
sel_rgb: (0, 0, 0),
content_h: 4,
},
);
let row = |y: usize| out[y * 4]; // R channel
assert!(row(0) > 0, "a visible row is lightened toward white");
assert!(row(1) > 0, "a visible row is lightened toward white");
assert_eq!(row(3), 0, "an off-screen row is untouched");
}
#[test]
fn minimap_selection_band_tints_selected_rows() {
// 1px-wide, 4px-tall black raster; rows 2..=3 selected in red, viewport is
// the top row only, so the selection band shows on its own.
let base = vec![0u8; 4 * 4];
let out = composite_minimap_viewport(
&base,
1,
4,
MinimapOverlay {
top: 0,
rows: 1,
total: 4,
light: false,
selection: Some((2, 3)),
sel_rgb: (255, 0, 0),
content_h: 4,
},
);
let r = |y: usize| out[y * 4];
assert!(r(2) > 0, "selected row picks up the selection color");
assert!(r(3) > 0, "selected row picks up the selection color");
}
#[test]
fn minimap_rgba_to_png_roundtrips() {
let png = rgba_to_png(vec![1u8; 2 * 2 * 4], 2, 2).expect("encode");
assert_eq!(
&png[1..4],
b"PNG",
"emits a PNG the inline-image path can use"
);
}
/// Display label of a menu entry ("---" for a divider) — test helper for the
/// `MenuEntry`-based context menus.
fn menu_label(e: &MenuEntry) -> &str {
match e {
MenuEntry::Item { label, .. }
| MenuEntry::Submenu { label, .. }
| MenuEntry::Header(label) => label,
MenuEntry::Separator => "---",
}
}
/// Top-level labels of a menu, in order.
fn menu_labels(items: &[MenuEntry]) -> Vec<&str> {
items.iter().map(menu_label).collect()
}
/// The action carried by the first `Item` with `label`, if any.
fn menu_action_of<'a>(items: &'a [MenuEntry], label: &str) -> Option<&'a MenuAction> {
items.iter().find_map(|e| match e {
MenuEntry::Item { label: l, action } if l == label => Some(action),
_ => None,
})
}
#[test]
fn explorer_boots_with_gradient_focus_under_black_theme() {
// Regression: the explorer auto-focuses at startup, but the Black-theme
// gradient border used to arm only on the first focus change because
// `sync_focus_flags` never ran during construction. `App::new` now syncs
// once before returning, so the initial focus already carries the gradient.
let tmp = tempfile::tempdir().unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
assert_eq!(app.theme, crate::theme::Theme::BLACK);
assert!(app.tree.focused, "explorer should boot focused");
assert!(
app.tree.focus_gradient,
"Black-theme gradient border must arm at startup, not just after a focus change"
);
}
#[test]
fn persistence_advisory_only_for_nonpersistent_remote_sessions() {
// Remote session without dtach: warn on the status line. Remote-with-dtach
// and any local session: nothing.
assert!(super::remote_persistence_status(true, false).is_some());
assert!(super::remote_persistence_status(true, true).is_none());
assert!(super::remote_persistence_status(false, false).is_none());
assert!(super::remote_persistence_status(false, true).is_none());
}
#[test]
fn sqlite_pages_step_at_batch_boundaries() {
// #201 review: PageDown at the bottom of a full batch fetches the
// next page; PageUp at the top returns.
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("big.db");
{
let conn = rusqlite::Connection::open(&p).unwrap();
conn.execute_batch("CREATE TABLE t (n INTEGER);").unwrap();
let mut ins = conn.prepare("INSERT INTO t VALUES (?1)").unwrap();
for i in 0..700 {
ins.execute([i]).unwrap();
}
}
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&p).unwrap();
let view = app.editor.sheet.as_ref().unwrap();
assert_eq!(view.sheets[0].row_count(), 500);
assert!(view.sheets[0].name.contains("rows 1-500, more follow"));
app.handle_sheet_key(key(KeyCode::End, KeyModifiers::SUPER));
app.handle_sheet_key(key(KeyCode::PageDown, KeyModifiers::NONE));
let view = app.editor.sheet.as_ref().unwrap();
assert_eq!(view.sheets[0].row_count(), 200, "second page loaded");
assert!(
view.sheets[0].name.ends_with("rows 501-700"),
"{}",
view.sheets[0].name
);
assert_eq!(view.sheets[0].cell(0, 0), "500", "first value of page 2");
app.handle_sheet_key(key(KeyCode::Home, KeyModifiers::SUPER));
app.handle_sheet_key(key(KeyCode::PageUp, KeyModifiers::NONE));
let view = app.editor.sheet.as_ref().unwrap();
assert!(
view.sheets[0].name.contains("rows 1-500"),
"{}",
view.sheets[0].name
);
}
#[test]
fn media_file_opens_as_an_info_card_and_save_refuses() {
// #183: a WAV opens as the rendered info card (duration, rates), a
// save refuses (#185 class), and junk with a media extension falls
// through to the binary path instead of erroring.
use std::io::Write as _;
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("tone.wav");
let mut f = std::fs::File::create(&p).unwrap();
let byte_rate = 16000u32;
let data = vec![0u8; byte_rate as usize]; // 1 second
let mut hdr = Vec::new();
hdr.extend_from_slice(b"RIFF");
hdr.extend_from_slice(&((36 + data.len()) as u32).to_le_bytes());
hdr.extend_from_slice(b"WAVEfmt ");
hdr.extend_from_slice(&16u32.to_le_bytes());
hdr.extend_from_slice(&1u16.to_le_bytes());
hdr.extend_from_slice(&1u16.to_le_bytes());
hdr.extend_from_slice(&8000u32.to_le_bytes());
hdr.extend_from_slice(&byte_rate.to_le_bytes());
hdr.extend_from_slice(&2u16.to_le_bytes());
hdr.extend_from_slice(&16u16.to_le_bytes());
hdr.extend_from_slice(b"data");
hdr.extend_from_slice(&(data.len() as u32).to_le_bytes());
f.write_all(&hdr).unwrap();
f.write_all(&data).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&p).unwrap();
let md = app
.editor
.markdown_preview
.as_ref()
.expect("media opens as the info card");
assert!(md.media && md.doc_path.is_some());
let all: String = md
.lines
.iter()
.flat_map(|l| l.spans.iter())
.map(|s| s.content.as_ref())
.collect();
assert!(all.contains("tone.wav"), "{all}");
assert!(all.contains("8000 Hz"), "{all}");
let before = std::fs::read(&p).unwrap();
assert!(app.editor.save_to_disk().is_err(), "info card save refuses");
assert_eq!(std::fs::read(&p).unwrap(), before);
// Junk wearing .mp3: never a dead-end.
let junk = tmp.path().join("noise.mp3");
std::fs::write(&junk, b"\x00\x01 not audio").unwrap();
let mut e = crate::widgets::editor::Editor::new();
e.open(&junk).unwrap();
assert!(e.hex.is_some(), "junk media falls to hex");
}
#[test]
fn docx_opens_as_a_rendered_document() {
// #181: a docx renders headings/emphasis through the preview
// machinery; the text side is a stub (Reopen as Text routes the zip
// container onward, never a mojibake buffer).
use std::io::Write as _;
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("memo.docx");
let f = std::fs::File::create(&p).unwrap();
let mut z = zip::ZipWriter::new(f);
let o =
zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
z.start_file("word/document.xml", o).unwrap();
z.write_all(
br#"<w:document xmlns:w="x"><w:body>
<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Memo Title</w:t></w:r></w:p>
<w:p><w:r><w:t>memo body</w:t></w:r></w:p></w:body></w:document>"#,
)
.unwrap();
z.finish().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&p).unwrap();
let md = app
.editor
.markdown_preview
.as_ref()
.expect("docx opens rendered");
assert!(md.doc_path.is_some());
let all: String = md
.lines
.iter()
.flat_map(|l| l.spans.iter())
.map(|s| s.content.as_ref())
.collect();
assert!(all.contains("Memo Title"), "{all}");
assert!(all.contains("memo body"));
// #200 review: the text side is a stub - a save must refuse at the
// choke point (#185 class), leaving the document untouched.
let before = std::fs::read(&p).unwrap();
assert!(
app.editor.save_to_disk().is_err(),
"doc preview save refuses"
);
assert_eq!(std::fs::read(&p).unwrap(), before, "document intact");
}
#[test]
fn notebook_opens_rendered_with_reopen_as_text_for_the_json() {
// #180: an .ipynb opens as the rendered view over its JSON text;
// Reopen as Text shows the raw JSON and sticks.
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("run.ipynb");
std::fs::write(
&p,
r##"{"nbformat":4,"metadata":{"kernelspec":{"language":"python"}},"cells":[
{"cell_type":"markdown","source":["# Report"]},
{"cell_type":"code","execution_count":3,"source":["x = 1"],
"outputs":[{"output_type":"stream","text":["done\n"]}]}]}"##,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&p).unwrap();
let md = app
.editor
.markdown_preview
.as_ref()
.expect("notebook opens rendered");
assert!(md.notebook);
let all: String = md
.lines
.iter()
.flat_map(|l| l.spans.iter())
.map(|s| s.content.as_ref())
.collect();
assert!(all.contains("Report"));
assert!(all.contains("In [3]:"));
assert!(all.contains("done"));
// Reopen as Text: the raw JSON, sticky across a same-path reload.
app.editor.force_text = true;
app.editor.open(&p).unwrap();
assert!(app.editor.markdown_preview.is_none());
assert!(app.editor.lines[0].contains("nbformat"));
app.editor.open(&p).unwrap();
assert!(app.editor.markdown_preview.is_none(), "sticky");
// And back to the render.
app.editor.force_text = false;
app.editor.open(&p).unwrap();
assert!(app.editor.markdown_preview.is_some());
}
#[test]
fn archive_tab_lists_members_and_enter_opens_an_extracted_copy() {
// #179 end-to-end: a zip opens as the member browser, Enter on a
// text member extracts it to scratch and opens it through the
// normal dispatch.
use std::io::Write as _;
let tmp = tempfile::tempdir().unwrap();
let zp = tmp.path().join("bundle.zip");
let f = std::fs::File::create(&zp).unwrap();
let mut z = zip::ZipWriter::new(f);
let opts =
zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
z.start_file("notes/inner.txt", opts).unwrap();
z.write_all(b"member text").unwrap();
z.finish().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&zp).unwrap();
let view = app.editor.archive.as_ref().expect("zip opens as a browser");
assert_eq!(view.entries.len(), 1);
assert_eq!(view.entries[0].path, "notes/inner.txt");
app.handle_archive_key(key(KeyCode::Enter, KeyModifiers::NONE));
assert!(
app.editor.archive.is_none(),
"the member opened in the editor: {}",
app.status
);
assert_eq!(app.editor.lines, vec!["member text".to_string()]);
}
#[test]
fn misnamed_zip_routes_to_the_archive_browser_by_content() {
use std::io::Write as _;
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("data.bin");
let f = std::fs::File::create(&p).unwrap();
let mut z = zip::ZipWriter::new(f);
let opts =
zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
z.start_file("x.txt", opts).unwrap();
z.write_all(b"in").unwrap();
z.finish().unwrap();
let mut e = crate::widgets::editor::Editor::new();
e.open(&p).unwrap();
assert!(
e.archive.is_some(),
"sniffed zip lands in the browser, not hex"
);
}
#[test]
fn markdown_preview_computes_image_anchor_frame_truth() {
// #176: the preview render must publish each image's wrapped visual
// row and the paragraph's text area, which the overlay driver
// consumes.
let tmp = tempfile::tempdir().unwrap();
image::RgbaImage::new(100, 50)
.save(tmp.path().join("pic.png"))
.unwrap();
std::fs::write(
tmp.path().join("doc.md"),
"# Title\n\nintro text\n\n\n\ntail",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&tmp.path().join("doc.md")).unwrap();
assert!(app.editor.toggle_markdown_preview());
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let md = app.editor.markdown_preview.as_ref().unwrap();
assert_eq!(md.images.len(), 1);
assert_eq!(md.anchor_rows.len(), 1);
assert!(
md.anchor_rows[0] >= 3,
"the anchor sits below the heading and intro: {}",
md.anchor_rows[0]
);
assert!(md.last_area.width > 0, "frame-truth area published");
// The reserved rows are blank in the paint: no placeholder glyph.
let mut all = String::new();
for y in 0..30 {
for x in 0..100 {
all.push_str(term.backend().buffer()[(x, y)].symbol());
}
}
assert!(
!all.contains("(pic.png)"),
"no labelled placeholder for a local image"
);
}
#[test]
fn terminal_warning_renders_inside_a_narrow_frame_without_panicking() {
// #192: the modal's width clamp had a lower bound of 50, so any
// terminal narrower than that produced a rect wider than the buffer
// and the paint panicked at launch.
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();
// And pathologically small: still no panic.
let backend = ratatui::backend::TestBackend::new(8, 3);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
}
/// A context menu longer than the terminal is tall, or on a terminal under
/// 18 columns, renders clipped instead of panicking.
#[test]
fn a_context_menu_bigger_than_the_terminal_renders_without_panicking() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let items: Vec<(String, MenuAction)> = (0..30)
.map(|i| (format!("item {i}"), MenuAction::Create(CreateKind::File)))
.collect();
app.context_menu = Some(ContextMenu::flat((2, 2), items, tmp.path().to_path_buf()));
for (w, h) in [(80, 12), (12, 30), (8, 3)] {
let backend = ratatui::backend::TestBackend::new(w, h);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let r = app.menu_rect().unwrap();
assert!(r.width <= w && r.height <= h, "{r:?} in {w}x{h}");
}
}
/// Overlays on a terminal smaller than their minimum size: `clamp(40, w)`
/// panics when the width is under 40, and a confirm dialog's 50-column
/// floor built a rect outside the buffer. A phone in portrait or a small
/// tmux split is enough.
#[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 {
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 terminal_warning_swallows_a_key_and_dismisses_for_the_session() {
// While the unsupported-terminal nudge is up, any non-D key dismisses it
// for this session and is swallowed so it never reaches the editor below.
// Uses a plain letter so nothing is persisted to the real prefs file.
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 caret_move_clears_lsp_occurrence_tints_and_edits_already_did() {
// The occurrences tick keeps a resting caret's tints and drops them the
// moment the caret moves; a reply for the old spot must also be dropped
// (the in-flight request is cancelled on move).
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("occ.txt");
std::fs::write(&file, "one two\nthree\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_at(&file, 0, 0).unwrap();
app.tick_occurrences(); // observe the caret's resting spot
app.editor
.apply_occurrences(vec![crate::lsp::manager::OccurrenceItem {
start_line: 0,
start_char: 0,
end_line: 0,
end_char: 3,
write: false,
}]);
app.tick_occurrences();
assert_eq!(
app.editor.occurrence_count_for_test(),
1,
"a resting caret must keep its tints across ticks"
);
app.editor.cursor_col = 4;
let changed = app.tick_occurrences();
assert!(changed, "the clearing tick must report a redraw");
assert_eq!(
app.editor.occurrence_count_for_test(),
0,
"moving the caret must drop the old symbol's tints"
);
}
/// SGR mouse reporting carries only shift/meta/ctrl — there is no super bit
/// (crossterm `parse_cb`), so Cmd+click and Option+click are the same event and
/// Go to Definition cannot share ALT with VS Code's multi-cursor. ALT is the
/// caret modifier; CTRL is go-to, matching the terminal pane's file/URL click.
#[test]
fn alt_click_adds_a_caret_and_ctrl_click_goes_to_definition() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("t.rs");
std::fs::write(&f, "fn main() {}\nlet x = 1;\nlet y = 2;\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(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
// A body column clear of the gutter, on a different row from the caret.
let col = app.editor.last_inner.x + 8;
let row = app.editor.last_inner.y + 2;
let mut alt = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
alt.modifiers = KeyModifiers::ALT;
app.handle_mouse(alt);
assert!(
!app.editor.carets.is_empty(),
"Alt+click must add a secondary caret, not go to definition"
);
// Ctrl+click is go-to-definition. With no language server attached the
// jump cannot land, so what is pinned is that it does NOT add a caret.
let before = app.editor.carets.len();
let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row + 1);
ctrl.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ctrl);
assert_eq!(
app.editor.carets.len(),
before,
"Ctrl+click is Go to Definition and must never add a caret"
);
}
#[test]
fn shift_alt_drag_starts_a_column_selection() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("t.rs");
std::fs::write(&f, "aaaaaaaa\nbbbbbbbb\ncccccccc\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(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
// Clear of the gutter: the sign margin / line-number columns are not
// buffer positions, so begin_box_select would refuse there.
let col = app.editor.last_inner.x + 8;
let row = app.editor.last_inner.y;
let mut down = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
down.modifiers = KeyModifiers::ALT | KeyModifiers::SHIFT;
app.handle_mouse(down);
assert!(
app.editor.box_selecting(),
"Shift+Alt press must anchor a column selection"
);
// Drag DOWN AND ACROSS. A drag that only moves vertically produces
// zero-width selections on every row, which an implementation that ignored
// the anchor column entirely would also satisfy.
let mut drag = mouse(MouseEventKind::Drag(MouseButton::Left), col + 3, row + 2);
drag.modifiers = KeyModifiers::ALT | KeyModifiers::SHIFT;
app.handle_mouse(drag);
assert!(
app.editor.carets.len() >= 2,
"Shift+Alt+drag must build a column of carets, got {}",
app.editor.carets.len()
);
// The head row's span lives in `selection`; the rows above it are carets.
// Every one must cover the SAME three columns — that is what makes it a
// column selection rather than a stack of bare cursors.
let head = app
.editor
.selection
.expect("the head row must span columns");
assert_eq!(
head.head.1 - head.anchor.1,
3,
"head row must span 3 columns"
);
for c in &app.editor.carets {
assert_eq!(
(c.anchor.1, c.head.1),
(head.anchor.1, head.head.1),
"every row of a column selection covers the same columns"
);
}
}
#[test]
fn alt_clicking_the_gutter_play_glyph_debugs_that_test() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("Cargo.toml"),
"[package]\nname = \"t\"\nversion = \"0.0.0\"\n",
)
.unwrap();
let f = tmp.path().join("t.rs");
std::fs::write(&f, "#[test]\nfn my_case() { assert!(true); }\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(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
// Occupy the build slot so the debug route reports it instead of detaching
// a real `cargo test --no-run` into a TempDir this test is about to delete.
let (_tx, rx) = std::sync::mpsc::channel();
app.pending_test_debug = Some((rx, String::from("other"), tmp.path().to_path_buf()));
let col = app.editor.last_inner.x;
let row = app.editor.last_inner.y + 1;
let mut ev = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ev.modifiers = KeyModifiers::ALT;
app.handle_mouse(ev);
// The ALT guard at the top of the Down(Left) arm returns ~1000 lines before
// the gutter's own hit-test, so without an explicit glyph check there the
// documented gesture reaches Go to Definition instead of the debugger.
// Either debug status proves the click routed to the debugger; which one
// depends on whether the host has an lldb-dap installed, and a machine
// without one must not fail a test about a mouse gesture.
assert!(
app.status == "A test binary is already building"
|| app.status.starts_with("lldb-dap not found"),
"Alt+click on the gutter play glyph must debug that test, got {:?}",
app.status
);
}
#[test]
fn clicking_the_gutter_play_glyph_runs_that_test() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
// A real Cargo marker: the run gestures refuse a workspace no enabled
// runner claims, and this test pins the click-to-run wiring, not that.
std::fs::write(
tmp.path().join("Cargo.toml"),
"[package]\nname = \"t\"\nversion = \"0.0.0\"\n",
)
.unwrap();
let f = tmp.path().join("t.rs");
std::fs::write(&f, "#[test]\nfn my_case() { assert!(true); }\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(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
// The play glyph sits in the sign margin on `fn my_case`'s row (buffer
// line 1 -> second content row). Drive the REAL mouse dispatch so a
// splitter grab zone or click-ordering regression fails this test.
let col = app.editor.last_inner.x;
let row = app.editor.last_inner.y + 1;
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert_eq!(
app.status, "Running test my_case",
"the glyph click must start that test by name"
);
}
/// A minimal two-page PDF whose page 1 carries the text "go to two" under a
/// GoTo link annotation targeting page 2. Hand-assembled (correct xref
/// offsets included) so the test needs no pdflatex, only poppler to read it.
fn two_page_pdf_with_internal_link() -> Vec<u8> {
let s1 = b"BT /F1 12 Tf 20 50 Td (go to two) Tj ET";
let s2 = b"BT /F1 12 Tf 20 50 Td (second page) Tj ET";
let objs: Vec<Vec<u8>> = vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R 5 0 R] /Count 2 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Contents 4 0 R \
/Resources << /Font << /F1 6 0 R >> >> /Annots [7 0 R] >>"
.to_vec(),
[
format!("<< /Length {} >>\nstream\n", s1.len()).into_bytes(),
s1.to_vec(),
b"\nendstream".to_vec(),
]
.concat(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Contents 8 0 R \
/Resources << /Font << /F1 6 0 R >> >> >>"
.to_vec(),
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(),
b"<< /Type /Annot /Subtype /Link /Rect [18 44 92 64] /Border [0 0 0] \
/A << /S /GoTo /D [5 0 R /Fit] >> >>"
.to_vec(),
[
format!("<< /Length {} >>\nstream\n", s2.len()).into_bytes(),
s2.to_vec(),
b"\nendstream".to_vec(),
]
.concat(),
];
let mut out = b"%PDF-1.4\n".to_vec();
let mut offsets = Vec::new();
for (i, body) in objs.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
out.extend_from_slice(body);
out.extend_from_slice(b"\nendobj\n");
}
let xref = out.len();
out.extend_from_slice(format!("xref\n0 {}\n", objs.len() + 1).as_bytes());
out.extend_from_slice(b"0000000000 65535 f \n");
for off in &offsets {
out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n",
objs.len() + 1
)
.as_bytes(),
);
out
}
/// The user's gesture end to end: a PDF preview is on screen and a click on
/// a link flips to its target page — through the REAL mouse dispatch, the
/// real overlay geometry from a rendered frame, and real poppler extraction.
#[test]
fn clicking_an_internal_pdf_link_flips_to_its_page() {
use crossterm::event::{MouseButton, MouseEventKind};
if crate::pdf::detect_backend() != Some(crate::pdf::PdfBackend::PdftoppmCli)
|| crate::pdf::page_links(std::path::Path::new("/nonexistent"), 1)
.err()
.is_some_and(|e| e.to_string().contains("install poppler"))
{
eprintln!("skipping: poppler (pdftoppm + pdftohtml) not installed");
return;
}
let tmp = tempfile::tempdir().unwrap();
let pdf = tmp.path().join("linked.pdf");
std::fs::write(&pdf, two_page_pdf_with_internal_link()).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// A real terminal would have reported these during startup; the overlay
// bake (whose layout the hit-test reads) is gated on both.
app.cell_pixel = Some((10, 20));
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
app.editor.open_pinned(&pdf).unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let layout = app.overlays.editor[0]
.layout()
.expect("rendering a PDF tab bakes the image overlay")
.clone();
let image = app.editor.image.as_ref().unwrap();
let (px_w, px_h) = (image.pixel_w, image.pixel_h);
// The link's text run "go to two" sits around (0.22, 0.47) of the page
// (measured: x 30..103 of 300, y 62..79 of 150 in pdftohtml space).
// Find the screen cell covering that point instead of hardcoding one,
// so the test survives font-metric drift across poppler versions.
let (mut col, mut row) = (0u16, 0u16);
'outer: for r in 0..layout.cell_h {
for c in 0..layout.cell_w {
if let Some((x0, y0, x1, y1)) = crate::iterm2_inline::cell_source_fraction(
(c, r),
(10, 20),
(layout.cell_w, layout.cell_h),
(px_w, px_h),
) && x0 <= 0.22
&& 0.22 < x1
&& y0 <= 0.47
&& 0.47 < y1
{
(col, row) = (layout.cell_x + c, layout.cell_y + r);
break 'outer;
}
}
}
assert!(col > 0, "some cell must cover the link's page position");
assert_eq!(app.editor.pdf_page(), Some(1));
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert_eq!(
app.editor.pdf_page(),
Some(2),
"clicking the internal link must flip the preview to page 2; status: {}",
app.status
);
}
#[test]
fn cmd_k_shift_enter_debugs_instead_of_running_the_test_at_cursor() {
// The Shift arm must precede the plain-Enter run arm, or the chord
// silently RUNS the test it was asked to DEBUG.
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("t.rs");
std::fs::write(&f, "#[test]\nfn my_case() { assert!(true); }\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.editor.cursor_row = 1;
assert!(app.handle_cmd_k_chord(key(KeyCode::Enter, KeyModifiers::SHIFT)));
// The tmp root has no manifest, so the debug path reports the missing
// runner — the run path would have said "Running test my_case".
assert_eq!(app.status, "No test runner detected in this workspace");
assert!(
!app.testing.is_busy(),
"the debug chord must not start a run"
);
}
#[test]
fn cmd_k_h_chords_fire_call_hierarchy_requests() {
// Cmd+K H asks for incoming calls, Cmd+K Shift+H for outgoing; both
// must arm the request id so the drain can match the reply.
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("a.py");
std::fs::write(&f, "def target():\n pass\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('h'), KeyModifiers::NONE)));
let first = app
.call_hierarchy_request_id
.expect("incoming request armed");
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('H'), KeyModifiers::SHIFT)));
let second = app
.call_hierarchy_request_id
.expect("outgoing request armed");
assert!(second > first, "each chord fires a fresh request");
}
#[test]
fn cmd_k_shift_u_and_d_fire_type_hierarchy_requests() {
// #613: Shift+U asks for supertypes, Shift+D for subtypes, and neither
// falls through to the plain U / D arms (close saved tabs, etc.).
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("a.py");
std::fs::write(&f, "class A:\n pass\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('U'), KeyModifiers::SHIFT)));
let first = app.call_hierarchy_request_id.expect("supertypes armed");
// CSI-u hosts report Shift+D as a lowercase char with SHIFT.
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('d'), KeyModifiers::SHIFT)));
let second = app.call_hierarchy_request_id.expect("subtypes armed");
assert!(second > first);
assert_eq!(
app.editor.tab_count(),
1,
"the tab survived: no close arm ran"
);
}
#[test]
fn a_late_call_hierarchy_reply_does_not_clobber_an_open_menu() {
// rust-analyzer can answer seconds later; if the user opened another
// menu while waiting, the reply must be dropped, not replace what they
// are looking at (and yank focus to the editor).
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let items = vec![(
String::from("caller — a.rs:1"),
MenuAction::GoToLocation {
path: tmp.path().join("a.rs"),
line: 0,
col: 0,
},
)];
let other = ContextMenu::flat((1, 1), items.clone(), tmp.path().to_path_buf());
app.context_menu = Some(other);
let menu_before = app.context_menu.as_ref().map(|m| m.items.len());
app.present_call_hierarchy_menu(items, "incoming calls");
assert_eq!(
app.context_menu.as_ref().map(|m| m.items.len()),
menu_before,
"an open menu survives a late reply"
);
assert_eq!(app.status, "Call hierarchy ready, but another menu is open");
// With no menu open, the reply presents normally.
app.context_menu = None;
app.present_call_hierarchy_menu(
vec![(
String::from("caller — a.rs:1"),
MenuAction::GoToLocation {
path: tmp.path().join("a.rs"),
line: 0,
col: 0,
},
)],
"incoming calls",
);
assert!(
app.context_menu.is_some(),
"a free slot presents the picker"
);
assert_eq!(app.status, "1 incoming calls");
}
#[test]
fn a_late_location_picker_reply_does_not_clobber_an_open_menu() {
// Go to Implementations / References share the async-reply shape with
// call hierarchy: the LSP can answer seconds later, and the picker must
// not replace a menu the user opened while waiting.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let items = vec![(
String::from("a.rs:1"),
MenuAction::GoToLocation {
path: tmp.path().join("a.rs"),
line: 0,
col: 0,
},
)];
app.context_menu = Some(ContextMenu::flat(
(1, 1),
items.clone(),
tmp.path().to_path_buf(),
));
let menu_before = app.context_menu.as_ref().map(|m| m.items.len());
app.open_location_picker(vec![(tmp.path().join("a.rs"), 0, 0)], "references");
assert_eq!(
app.context_menu.as_ref().map(|m| m.items.len()),
menu_before,
"an open menu survives a late reply"
);
assert_eq!(app.status, "Locations ready, but another menu is open");
// With no menu open, the reply presents normally.
app.context_menu = None;
app.open_location_picker(vec![(tmp.path().join("a.rs"), 0, 0)], "references");
assert!(
app.context_menu.is_some(),
"a free slot presents the picker"
);
assert_eq!(app.status, "1 references");
}
#[test]
fn a_workspace_change_cancels_the_pending_test_debug_build() {
// The drain already refuses to launch a binary whose build root no
// longer matches, but the occupied slot also kept refusing NEW builds
// ("A test binary is already building") until the stale compile
// finished. Re-rooting must free the slot immediately.
let tmp = tempfile::tempdir().unwrap();
let inner = tmp.path().join("inner");
std::fs::create_dir(&inner).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let (_tx, rx) = std::sync::mpsc::channel();
app.pending_test_debug = Some((rx, String::from("my_case"), tmp.path().to_path_buf()));
app.change_workspace_root(inner);
assert!(
app.pending_test_debug.is_none(),
"re-rooting drops the in-flight build so a new one can start"
);
}
#[test]
fn popup_gradient_tracks_black_theme() {
// Popups/menus/tooltips wear the gradient + muted selection only under the
// Black theme; Croft Dark keeps the legacy bright-blue accent so it stays
// coherent with that theme's blue focus border.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.theme = crate::theme::Theme::BLACK;
assert!(app.popup_gradient());
app.theme = crate::theme::Theme::DARK_BLUE;
assert!(!app.popup_gradient());
}
#[test]
fn run_spec_for_runs_an_executable_binary_directly() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
// An extensionless file with the +x bit is runnable: run it directly.
let bin = tmp.path().join("myapp");
std::fs::write(&bin, b"#!/bin/sh\necho hi\n").unwrap();
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
let spec = App::run_spec_for(&bin, tmp.path()).expect("executable must be runnable");
assert_eq!(spec.program, bin.to_string_lossy());
assert!(spec.args.is_empty(), "the binary is run with no extra args");
// A non-executable, unknown file (like .git/config) is not runnable.
let cfg = tmp.path().join("config");
std::fs::write(&cfg, b"[core]\n").unwrap();
assert!(App::run_spec_for(&cfg, tmp.path()).is_none());
}
#[test]
fn debug_stop_immediately_deactivates_the_run_debug_panel() {
// Repro: Shift+F5 tore down the session but left the panel showing the
// stale "Paused" tree, because poll_dap early-returns with no session and
// never refreshes. debug_stop must refresh the panel itself.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Simulate a paused panel.
app.run_debug.debug_active = true;
app.run_debug.feedback = Some("Paused (breakpoint)".into());
app.run_debug.debug_rows = vec![crate::widgets::run_debug::DebugRow {
indent: 0,
kind: crate::widgets::run_debug::DebugRowKind::Header {
title: "CALL STACK".into(),
},
}];
app.debug_stop();
assert!(
!app.run_debug.debug_active,
"panel must deactivate the instant the session stops"
);
assert!(
app.run_debug.debug_rows.is_empty(),
"stale call-stack/variables rows must be cleared on stop"
);
assert!(
app.run_debug.feedback.is_none(),
"stale 'Paused' feedback must be cleared so the empty state is clean"
);
}
#[test]
fn lldb_dap_rank_prefers_unversioned_then_highest_version() {
// The Linux bug: lldb-dap ships under versioned names (`lldb-dap-18`) with
// no unversioned symlink, so resolution must rank candidates rather than
// only matching the bare `lldb-dap` name.
// Non-matches return None.
assert_eq!(lldb_dap_rank("lldb"), None);
assert_eq!(lldb_dap_rank("lldb-dap-"), None);
assert_eq!(lldb_dap_rank("lldb-dapper"), None);
assert_eq!(lldb_dap_rank("clangd"), None);
// Every real adapter name ranks.
let unversioned = lldb_dap_rank("lldb-dap").expect("bare name must rank");
let v18 = lldb_dap_rank("lldb-dap-18").expect("versioned name must rank");
let v17 = lldb_dap_rank("lldb-dap-17").expect("versioned name must rank");
let legacy_v18 = lldb_dap_rank("lldb-vscode-18").expect("legacy name must rank");
// The unversioned binary wins outright (it tracks the system default).
assert!(
unversioned > v18,
"unversioned lldb-dap outranks any versioned"
);
// Among versioned binaries, the newer LLVM release wins.
assert!(v18 > v17, "lldb-dap-18 outranks lldb-dap-17");
// At equal version, the modern `lldb-dap` name beats legacy `lldb-vscode`.
assert!(
v18 > legacy_v18,
"lldb-dap-18 is preferred over the legacy lldb-vscode-18 name"
);
}
#[test]
fn lldb_dap_missing_message_is_platform_appropriate() {
// Regression: Linux users saw "install Xcode Command Line Tools", which is
// nonsense off macOS. The hint must match the host's package manager.
let msg = lldb_dap_missing_message();
assert!(
msg.contains("lldb-dap not found"),
"message must name the missing adapter: {msg}"
);
if cfg!(target_os = "macos") {
assert!(
msg.contains("Xcode"),
"macOS hint should mention Xcode: {msg}"
);
} else {
assert!(
!msg.contains("Xcode"),
"non-macOS hint must not mention Xcode: {msg}"
);
}
}
#[test]
fn f5_failure_reaches_the_status_bar_when_run_debug_panel_is_hidden() {
// Repro (remote Linux with no lldb-dap installed): pressing F5 on a file
// croft can't debug wrote the reason ONLY into the Run/Debug panel's
// feedback line, which renders solely while that sidebar is the active
// view. With the Explorer focused the message landed nowhere, so F5 looked
// like it did nothing. Every debug-start failure must also reach the
// always-visible status bar. Exercised here via the platform-independent
// "no adapter for this file type" branch (the lldb-missing branch shares
// the same surfacing path but can't be reproduced on a dev Mac, where the
// Xcode lldb-dap is always present).
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let file = tmp.path().join("notes.txt");
std::fs::write(&file, b"hi\n").unwrap();
app.editor.path = Some(file);
app.set_sidebar_view(SidebarView::Explorer);
app.debug_start_or_continue();
assert!(
app.status.contains("No debugger"),
"F5 failure must explain itself in the status bar, not just the hidden panel: {}",
app.status
);
}
#[test]
fn run_debug_icon_clears_when_a_paused_session_takes_over_the_panel() {
// Repro (Run/Debug panel already open when F5 starts a session, as seen on
// a remote): the empty-state debug icon is an OSC-1337 inline image. When
// the panel flips to the paused call-stack tree the widget stops re-emitting
// it (last_icon_cell = None), but text drawn over an inline image does NOT
// evict it, so the icon ghosted on top of the call stack. The flush must arm
// a one-shot terminal clear whenever a previously-emitted icon is no longer
// shown — the same eviction the welcome/hero overlays use.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.show_tree = true;
app.set_sidebar_view(SidebarView::RunDebug);
app.overlays
.run_debug
.set_image("\x1b]1337;File=inline=1:AAAA\x07".to_string());
app.overlays.run_debug.mark_emitted_at((5, 5));
// A paused session now owns the panel: render draws the tree, not the icon.
app.run_debug.last_icon_cell = None;
app.flush_run_debug_icon_overlay();
assert!(
app.consume_run_debug_image_clear(),
"a one-shot terminal clear must be armed to evict the ghosted debug icon"
);
assert!(
!app.overlays.run_debug.was_emitted(),
"emitted-position tracking must reset so the clear fires exactly once"
);
}
#[test]
fn black_theme_context_menu_uses_gradient_border_and_muted_selection() {
use crate::gradient::{GRAD_TL, POPUP_SEL_BG, rgb_color};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.theme = crate::theme::Theme::BLACK;
app.context_menu = Some(ContextMenu::flat(
(10, 10),
vec![
(
String::from("New File"),
MenuAction::Create(CreateKind::File),
),
(
String::from("New Folder"),
MenuAction::Create(CreateKind::Folder),
),
],
tmp.path().to_path_buf(),
));
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
// The menu's top-left corner carries the gradient's TL colour, not blue.
assert_eq!(buf[(10, 10)].fg, rgb_color(GRAD_TL));
// The selected (first) row sits on the muted dark-teal fill.
assert_eq!(buf[(11, 11)].bg, rgb_color(POPUP_SEL_BG));
}
#[test]
fn black_theme_status_bar_is_near_black_not_navy() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.theme = crate::theme::Theme::BLACK;
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let last_y = buf.area.height - 1;
let near_black = Color::Rgb(0x18, 0x18, 0x18);
let navy = Color::Rgb(0x1e, 0x3a, 0x6e);
assert!(
(0..buf.area.width).any(|x| buf[(x, last_y)].bg == near_black),
"status bar should paint the near-black seam under the Black theme"
);
assert!(
!(0..buf.area.width).any(|x| buf[(x, last_y)].bg == navy),
"status bar must not keep the legacy navy under the Black theme"
);
}
#[test]
fn resting_on_an_activity_icon_arms_its_button_hint() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Render once so the activity-bar icon rectangles are populated.
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let icon = app.sidebar_areas.search_icon;
let (cx, cy) = (icon.x + icon.width / 2, icon.y);
app.on_mouse_moved(cx, cy, false);
assert_eq!(
app.ui_tooltip_label,
Some("Search"),
"hovering the Search activity-bar icon arms its hint label"
);
// Moving onto inert space clears the armed hint.
app.on_mouse_moved(cx, icon.y + 200, false);
assert_eq!(app.ui_tooltip_label, None);
}
#[test]
fn chrome_tooltip_paints_in_the_sidebar_not_clamped_into_the_editor() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// A compact hint anchored over an activity-bar cell (far-left column).
app.ui_tooltip = Some(crate::widgets::hover_popup::HoverPopup::new_compact(
"Search".into(),
(2, 6),
));
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
// The popup's own background must appear in the far-left region near the
// anchor. The regression: it rendered against the editor's focused_area,
// which starts well to the right, so nothing painted over the sidebar.
let popup_bg = Color::Rgb(0x1e, 0x21, 0x2a);
let painted = (0..20).any(|x| (0..12).any(|y| buf[(x, y)].bg == popup_bg));
assert!(
painted,
"the chrome tooltip must paint near its sidebar anchor, not be clamped into the editor"
);
// ...and it must NOT paint over the activity-bar columns, whose inline-image
// icons composite above text and would hide the tooltip's left edge.
let over_bar = (0..ACTIVITY_BAR_WIDTH).any(|x| (0..50).any(|y| buf[(x, y)].bg == popup_bg));
assert!(
!over_bar,
"the tooltip must be shifted clear of the activity-bar image column"
);
}
#[test]
fn tooltip_repaints_over_the_hero_without_hiding_it() {
// The Run-and-Debug activity-icon hint flips up onto the centered no-repo
// hero illustration. The illustration must STAY (it's an OSC-1337 image),
// and the tooltip is re-painted on top of it post-draw. The fix must never
// clear/hide the hero just because a tooltip overlaps it.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_view = SidebarView::SourceControl;
app.cell_pixel = Some((8, 16));
let backend = ratatui::backend::TestBackend::new(63, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert!(!app.source_control.status.in_repo, "tempdir is not a repo");
let hero = app.source_control.last_hero_area;
assert!(hero.width > 0 && hero.height > 0, "hero must be laid out");
assert_eq!(
app.active_sidebar_image_rect(),
Some(hero),
"the no-repo hero is the active sidebar illustration"
);
// A tooltip box squarely over the hero: the hero must keep painting (no
// clear requested), and the overlapping repaint path must engage.
app.ui_tooltip = Some(crate::widgets::hover_popup::HoverPopup::new_compact(
"Run and Debug".into(),
(hero.x, hero.y),
));
app.ui_tooltip_area = Some(hero);
app.flush_no_repo_hero_overlay();
app.flush_tooltip_over_image();
assert!(
!app.consume_no_repo_hero_image_clear(),
"the hero must NOT be hidden/cleared when a tooltip overlaps it"
);
// No active illustration in a repo, so nothing to repaint over.
app.source_control.status.in_repo = true;
assert_eq!(
app.active_sidebar_image_rect(),
None,
"a repo workspace shows no hero, so there is no image to overlay"
);
}
#[test]
fn sidebar_header_actions_are_tooltipped_per_view() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let cell = |x| Rect {
x,
y: 1,
width: 2,
height: 1,
};
// Explorer toolbar (the icons in Image #1: new file / new folder / refresh /
// collapse, plus the ⋯ views menu).
app.sidebar_view = SidebarView::Explorer;
app.tree.header_new_file_btn = cell(20);
app.tree.header_new_folder_btn = cell(23);
app.tree.header_refresh_btn = cell(26);
app.tree.header_collapse_btn = cell(29);
app.tree.header_views_btn = cell(32);
assert_eq!(app.ui_tooltip_at(20, 1), Some("New File"));
assert_eq!(app.ui_tooltip_at(23, 1), Some("New Folder"));
assert_eq!(app.ui_tooltip_at(26, 1), Some("Refresh Explorer"));
assert_eq!(
app.ui_tooltip_at(29, 1),
Some("Collapse Folders in Explorer")
);
assert_eq!(app.ui_tooltip_at(32, 1), Some("Views and More Actions"));
// Remote Explorer header (the + / refresh in Image #2/#3).
app.sidebar_view = SidebarView::Remote;
app.remote.header_add_btn = cell(20);
app.remote.header_refresh_btn = cell(23);
assert_eq!(
app.ui_tooltip_at(20, 1),
Some("Open SSH Configuration File")
);
assert_eq!(app.ui_tooltip_at(23, 1), Some("Refresh"));
// Source Control header refresh.
app.sidebar_view = SidebarView::SourceControl;
app.source_control.header_refresh_btn = cell(20);
assert_eq!(app.ui_tooltip_at(20, 1), Some("Refresh"));
// A view's stored rects go inert once another view is showing, so the
// Remote add button at col 20 must not leak its hint into Explorer.
app.sidebar_view = SidebarView::Explorer;
assert_eq!(app.ui_tooltip_at(23, 1), Some("New Folder"));
}
fn dummy_activity_images() -> ActivityBarImages {
let s = || String::from("\x1b]1337;File=inline=1:Zm9v\x07");
ActivityBarImages {
explorer_active: s(),
explorer_inactive: s(),
explorer_hovered: s(),
search_active: s(),
search_inactive: s(),
search_hovered: s(),
source_control_active: s(),
source_control_inactive: s(),
source_control_hovered: s(),
remote_active: s(),
remote_inactive: s(),
remote_hovered: s(),
run_debug_active: s(),
run_debug_inactive: s(),
run_debug_hovered: s(),
extensions_active: s(),
extensions_inactive: s(),
extensions_hovered: s(),
testing_active: s(),
testing_inactive: s(),
testing_hovered: s(),
codeql_active: s(),
codeql_inactive: s(),
codeql_hovered: s(),
settings_active: s(),
settings_inactive: s(),
settings_hovered: s(),
layout_sidebar_on: s(),
layout_sidebar_on_hover: s(),
layout_sidebar_off: s(),
layout_sidebar_off_hover: s(),
layout_panel_on: s(),
layout_panel_on_hover: s(),
layout_panel_off: s(),
layout_panel_off_hover: s(),
layout_customize: s(),
layout_customize_hover: s(),
}
}
#[test]
fn format_diagnostics_labels_each_message_and_sorts_errors_first() {
use crate::lsp::manager::DiagnosticSeverity;
let diags = vec![
(DiagnosticSeverity::Warning, String::from("unused variable")),
(DiagnosticSeverity::Error, String::from("type mismatch")),
];
assert_eq!(
format_diagnostics(&diags),
Some(String::from(
"Error: type mismatch\n\nWarning: unused variable"
)),
"errors must come before warnings and each line is labelled by severity"
);
assert_eq!(
format_diagnostics(&[]),
None,
"no diagnostics must produce no block"
);
}
#[test]
fn compose_hover_puts_the_diagnostic_above_the_type_info() {
// VS Code (PR microsoft/vscode#166560) renders marker hovers on top.
assert_eq!(
compose_hover(Some("Error: type mismatch"), Some("const x: number")),
Some(String::from(
"Error: type mismatch\n────────\nconst x: number"
)),
"the diagnostic block sits above the language hover, divided by a rule"
);
assert_eq!(
compose_hover(Some("Error: type mismatch"), None),
Some(String::from("Error: type mismatch")),
"a diagnostic with no type info shows on its own"
);
assert_eq!(
compose_hover(None, Some("const x: number")),
Some(String::from("const x: number")),
"type info with no diagnostic shows on its own"
);
assert_eq!(
compose_hover(None, None),
None,
"nothing to show means no popup"
);
}
#[test]
fn hovering_a_diagnostic_on_punctuation_shows_its_message_synchronously() {
use crate::lsp::manager::{Diagnostic, DiagnosticSeverity};
use ratatui::layout::Rect;
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("dot.ts");
std::fs::write(&f, "a.b\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Stand the editor up directly: the `.` at char 1 is not a word, so this
// path never depends on a language server being attached.
app.editor.path = Some(f.clone());
app.editor.lines = vec![String::from("a.b")];
app.editor.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
app.editor.last_gutter_width = 2;
app.editor.apply_diagnostics(
f,
vec![Diagnostic {
start_line: 0,
start_char: 1,
end_line: 0,
end_char: 2,
severity: DiagnosticSeverity::Error,
message: String::from("unexpected token"),
}],
);
// text_x = x(0) + gutter(2) + 1 = 3, so cell col 4 is char 1 (the `.`).
app.hover_at_cell(4, 0);
let popup = app
.hover_popup
.as_ref()
.expect("hovering a squiggle must surface a popup even without an LSP reply");
assert_eq!(
popup.lines,
vec![String::from("Error: unexpected token")],
"the popup must carry the diagnostic's severity and message"
);
}
/// Stand up an app with a real file open in the editor and one frame
/// rendered (so every `last_*` rect is live), returning a cell inside the
/// editor body for tap-hover tests.
fn app_with_open_file_and_editor_cell() -> (App, tempfile::TempDir, u16, u16) {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("m.py");
std::fs::write(&f, "value = compute()\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let col = app.editor.last_inner.x + app.editor.last_gutter_width as u16 + 3;
let row = app.editor.last_inner.y + 1;
assert!(
rect_contains(app.editor.last_area, col, row),
"test cell must land inside the editor body"
);
(app, tmp, col, row)
}
/// Every cell of `pane`'s own `last_area`, row-major.
///
/// ONE walk. The column derivation in it was wrong once, and a second copy is
/// a second place to fix it. `hyperlink_at_screen` and `line_text_at` both
/// hit-test `last_inner`, which this rect contains, and answer `None` outside
/// it, so nothing yielded here is a cell a click could not reach.
fn cells_of(pane: &crate::widgets::terminal::PtyTerminal) -> impl Iterator<Item = (u16, u16)> {
let area = pane.last_area;
(area.y..area.y + area.height)
.flat_map(move |r| (area.x..area.x + area.width).map(move |c| (c, r)))
}
/// The first grid cell of `pane` that falls INSIDE the first occurrence of
/// `needle` on its row, searched row-major over the pane's own `last_area`
/// (#397).
///
/// A test that prints something into a pane and then clicks it must not assume
/// which row it landed on: the pane runs a REAL shell whose prompt races the
/// feed, so the row is a property of machine load rather than of the test.
/// Callers anchor on the exact text they printed, so unrelated output cannot
/// satisfy the search.
fn cell_carrying(pane: &crate::widgets::terminal::PtyTerminal, needle: &str) -> Option<(u16, u16)> {
cells_of(pane).find(|&(c, r)| {
// The cell must be ON the needle, not merely on a ROW containing
// it. `line_text_at` hands back the whole row plus the char index
// under the cell, and every column maps to an index (blanks
// included), so a `text.contains` test succeeds at the row's FIRST
// inner column whatever the needle's position. These fixtures print
// at column 0, which hid it; a row like `bash-5.2$ some_token`
// would have matched and clicked the `b`.
//
// A click lands on a cell, not a row, so the span is the claim.
pane.line_text_at(c, r).is_some_and(|(text, idx)| {
text.find(needle).is_some_and(|byte_start| {
let start = text[..byte_start].chars().count();
(start..start + needle.chars().count()).contains(&idx)
})
})
})
}
/// The first grid cell of `pane` carrying an OSC 8 link to exactly `uri`,
/// searched row-major over the pane's own `last_area` (#397).
///
/// The URI is the anchor rather than "any link", so a decoy printed beside the
/// payload cannot satisfy the search. Below [`cell_carrying`] rather than
/// above it: inserting an item over a `///` block hands that block to the
/// newcomer, which is what happened here once already.
fn cell_with_link(pane: &crate::widgets::terminal::PtyTerminal, uri: &str) -> Option<(u16, u16)> {
cells_of(pane).find(|&(c, r)| pane.hyperlink_at_screen(c, r).as_deref() == Some(uri))
}
/// `cell_carrying` returns a cell INSIDE the needle, not the row's first cell.
///
/// The refinement has exactly one red state in the suite, and it is a
/// downstream word-selection assertion in another test, so it does not
/// depend on that one test surviving: the helper's own doc records that the
/// column derivation in it was wrong once.
///
/// Placed beside the two helpers rather than in the block it was first
/// written in, which was some 35,000 lines away and made "beside the
/// helper" a claim the file did not support. Below `cell_with_link`
/// rather than between the two: inserting above a `///` block hands that
/// block to the newcomer, which this file has been bitten by twice.
#[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"
);
// The needle is NOT at column 0: a shell-shaped prefix in front of it is
// what separates a span predicate from a row-level `contains`, which
// would resolve the `b` of `bash-5.2$` instead.
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"
);
}
fn mouse(
kind: crossterm::event::MouseEventKind,
col: u16,
row: u16,
) -> crossterm::event::MouseEvent {
crossterm::event::MouseEvent {
kind,
column: col,
row,
modifiers: KeyModifiers::NONE,
}
}
/// A tree app, rendered, so `tree.last_area` is populated and a click can be
/// aimed at a real cell.
fn tree_app_with_keymap(json: &str) -> (App, tempfile::TempDir) {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("a.rs");
std::fs::write(&f, "let name = value;\nfn main() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// An open buffer, so a click in the editor region resolves to it. Without
// one there is no editor to hit and the gesture falls through.
app.editor.open_pinned(&f).unwrap();
app.keymap = crate::keymap::Keymap::from_json(json);
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
(app, tmp)
}
#[test]
fn a_bound_gesture_runs_its_command() {
// The headline claim of #259, driven end to end: a gesture in
// keybindings.json reaches `run_command`. Everything else in this file
// tested the parser or the tracker in isolation.
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp) = tree_app_with_keymap(
r#"[{"key": "ctrl+click", "command": "quick_open", "when": "editor"}]"#,
);
assert!(app.file_finder.is_none(), "nothing open yet");
let col = app.editor.last_inner.x + 4;
let row = app.editor.last_inner.y + 1;
let mut ev = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ev.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ev);
assert!(
app.file_finder.is_some(),
"the bound command must run, taking the gesture over from its built-in"
);
}
#[test]
fn a_gesture_runs_the_binding_for_the_region_it_was_clicked_in() {
// The same spelling bound in two regions must resolve by where the click
// landed, which is what `mouse_context_for` exists for.
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp) = tree_app_with_keymap(
r#"[{"key": "ctrl+click", "command": "quick_open", "when": "file_tree"},
{"key": "ctrl+click", "command": "toggle_side_bar", "when": "editor"}]"#,
);
let mut in_tree = mouse(
MouseEventKind::Down(MouseButton::Left),
app.tree.last_area.x + 2,
app.tree.last_area.y + 1,
);
in_tree.modifiers = KeyModifiers::CONTROL;
let tree_was = app.show_tree;
app.handle_mouse(in_tree);
assert!(
app.file_finder.is_some(),
"a click in the tree runs the file_tree row"
);
assert_eq!(
app.show_tree, tree_was,
"and must not run the editor row bound to the same spelling"
);
}
#[test]
fn a_click_binding_does_not_disable_the_double_click_binding_beside_it() {
// The dispatch returns early, skipping the built-in branch that would
// have recorded the click. Without recording it itself, a firing `click`
// binding leaves `is_double` false forever and the `double_click` binding
// beside it never fires again.
//
// Driven through `handle_mouse`: the previous version of this test called
// `tree_click.record` itself and asserted `is_double`, which is a
// tautology about `ClickTracker` that passes with the fix reverted.
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp) = tree_app_with_keymap(
r#"[{"key": "click", "command": "save_file", "when": "file_tree"},
{"key": "double_click", "command": "quick_open", "when": "file_tree"}]"#,
);
let col = app.tree.last_area.x + 2;
let row = app.tree.last_area.y + 1;
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert!(
app.file_finder.is_none(),
"the first click is a single and must run the `click` row"
);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert!(
app.file_finder.is_some(),
"the second must still read as a double — the click binding has to \
keep the tracker the built-in would have kept"
);
}
#[test]
fn a_bound_gesture_dismisses_the_hover_and_tab_tooltip() {
// The dispatch returns early, above the teardown every other left-press
// path runs. Without doing it itself, a fired binding leaves a hover or
// tab tooltip painted over state the command just changed — describing
// what was there before it ran.
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp) = tree_app_with_keymap(
r#"[{"key": "ctrl+click", "command": "quick_open", "when": "editor"}]"#,
);
app.hover_popup = Some(crate::widgets::hover_popup::HoverPopup::new(
String::from("stale hover"),
(1, 1),
));
app.tab_tooltip = Some(crate::widgets::hover_popup::HoverPopup::new(
String::from("stale tab tooltip"),
(1, 1),
));
let mut ev = mouse(
MouseEventKind::Down(MouseButton::Left),
app.editor.last_inner.x + 4,
app.editor.last_inner.y + 1,
);
ev.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ev);
assert!(app.file_finder.is_some(), "the binding fired");
assert!(
app.hover_popup.is_none(),
"a fired binding must dismiss the hover it painted over"
);
assert!(app.tab_tooltip.is_none(), "and the tab tooltip with it");
}
#[test]
fn a_terminal_miss_does_not_blame_a_view_it_never_searched() {
// The refusal was scoped to the editor lookup, but the STATUS derived from
// the same predicate stayed arm-wide: a click in a TERMINAL pane with no
// link reported "No links in this view", naming the editor's view — which
// `editor_blocked` had already short-circuited, so it was never searched.
//
// "a non-text view is up" and "the editor lookup is the one that missed"
// are different questions, and the status must answer the second.
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"
);
// Plain text, no link anywhere on the row.
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() {
// `MouseOpenLinkAtClick` spans two panes: it tries the editor's document
// link, then falls through to the terminal helpers. The `has_non_text_view`
// guard was placed on the whole ARM, but its justification — `buffer_pos_at`
// maps cells from the TEXT layout, so a diff/hex view yields a position
// into a buffer the user is not looking at — is about the EDITOR lookup
// only. `terminal_url_click`/`terminal_file_click` read `self.terminal()`
// and are independent of editor view state.
//
// The built-in this command replaces guards neither, so an arm-wide guard
// made the bound command diverge from the built-in in the opposite
// direction to the one the guard was added to fix.
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();
// `App::new` + direct keymap assignment, matching the sibling OSC 8 tests:
// `tree_app_with_keymap` focuses the TREE, which lays the panes out
// differently and moves the terminal's `last_area`.
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();
// The editor shows a hex preview of an UNRELATED file — the state the
// guard exists for, and which has nothing to do with the terminal.
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"
);
// A non-web OSC 8 link in the terminal: resolves via `hyperlink_at_screen`,
// then `open_detected_url` refuses the scheme INERTLY. A web URL would
// reach `open_url` and launch a real browser.
// The prompt of the real shell in this pane races the fed bytes, so the
// line it lands on is not fixed (#397). This puts a line in front of the
// link deliberately, making the order that used to break this test the
// one it always runs, and the cell is then searched for rather than
// assumed.
app.terminals[0].feed_bytes_for_test(b"a prompt got here first\r\n");
// A DECOY link on an earlier row, which is what gives `cell_with_link`'s
// exact-URI predicate a red state here: weaken it to `.is_some()` and the
// row-major search stops on the decoy, so the click resolves the wrong
// link and the status assertion below rejects it by name. Without this
// the predicate could be reverted and the test would still pass, since
// nothing else in this pane emits OSC 8.
//
// `mailto:` rather than `file://` deliberately: `file://` is intercepted
// by `editor_file_uri` and would exercise a different arm.
app.terminals[0]
.feed_bytes_for_test(b"\x1b]8;;mailto:decoy@example.com\x1b\\decoy\x1b]8;;\x1b\\\r\n");
// Trailing newline parks the cursor on the NEXT row: without it any late
// shell output writes onto the link's own row.
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 the_at_click_commands_all_refuse_a_non_text_view() {
// All three At Click commands guard on `has_non_text_view`, because
// `buffer_pos_at` maps cells from the TEXT layout and still returns a
// position on a diff/sheet/hex/log view — so without the guard they would
// act on coordinates belonging to a buffer the user is not looking at.
//
// Short-circuiting all three guards to false leaves the full suite green,
// so the guards shipped unpinned. Each arm asserts its OWN status, since
// a shared assertion would pass with two of the three guards deleted.
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.editor.hex = Some(crate::hex::HexView::open(&bin).unwrap());
// Positive control: without this the test passes vacuously if the fixture
// ever stops producing a non-text view.
assert!(
app.editor.has_non_text_view(),
"precondition: the fixture must actually open a non-text view, or \
every assertion below is about the ordinary text path"
);
// And the commands must have a click to act on, or they take the
// keyboard-invocation arm and refuse for an unrelated reason.
app.last_mouse_pos = Some((10, 10));
for (cmd, want) in [
(
crate::widgets::command_palette::Command::MouseAddCursorAtClick,
"No cursors in this view",
),
(
crate::widgets::command_palette::Command::MouseGoToDefinitionAtClick,
"No definitions in this view",
),
(
crate::widgets::command_palette::Command::MouseOpenLinkAtClick,
"No links in this view",
),
] {
app.status = String::from("untouched");
app.run_command(cmd);
assert_eq!(
app.status, want,
"{cmd:?} must refuse on a non-text view rather than acting on a \
buffer position the user cannot see"
);
}
}
#[test]
fn a_binding_on_the_terminal_border_fires_because_the_child_cannot_receive_it() {
// `child_owns_pointer` declines a user binding when the child has asked
// for mouse tracking. But `terminal_at_pos` hit-tests `last_area`, which
// INCLUDES the border, while delivery goes through `cell_at`, which
// hit-tests `last_inner` and excludes it. So a click on the border was
// suppressed for the child's benefit and then never reached the child:
// lost by both parties.
//
// The built-in wheel path already has this rule and says so
// ("the wheel sat on the pane BORDER, outside the inner grid ... falls
// through like any non-tracking pane instead of swallowing the notch"),
// but it requires `report_mouse` to actually return true. This predicate
// checked only `mouse_reporting()`.
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp) = tree_app_with_keymap(
r#"[{"key": "ctrl+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();
app.focus_pane(Pane::Terminal);
let area = app.terminals[0].last_area;
assert!(
area.width > 4 && area.height > 2,
"terminal must be laid out"
);
let (col, row) = (area.x + 2, area.y);
// The two facts that make this a BORDER click rather than a grid click.
// Without both, the test would be about something else entirely.
assert!(
app.terminals[0].cell_at(col, row).is_none(),
"precondition: this cell must be OUTSIDE the inner grid, or the child \
could receive it and suppression would be correct"
);
assert_eq!(
app.terminal_at_pos(col, row),
Some(0),
"precondition: but INSIDE last_area, or `child_owns_pointer` never \
considers this terminal and the test proves nothing"
);
// Child asks for tracking: the real predicate `mouse_reporting` consults.
app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h");
assert!(
app.terminals[0].mouse_reporting(),
"precondition: the child must be tracking, or there is nothing to \
decline the binding for"
);
let before = app.editor.wrap_enabled();
let mut ev = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ev.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ev);
assert_ne!(
app.editor.wrap_enabled(),
before,
"a binding on the BORDER must fire: the child cannot own a cell it \
will never be told about, so declining here loses the gesture for \
both parties. The wheel path already falls through on this exact case"
);
}
#[test]
fn the_swallowed_prefix_click_dismisses_the_hover_and_tab_tooltip() {
// The sibling test above binds `ctrl+click` to a real command, so it takes
// the MATCHED branch. The swallow branch needs a gesture that matches
// NOTHING but is the first half of a bound double — a different arm, with
// its own early return, which for a while did none of the teardown.
//
// Deleting `dismiss_click_overlays` from the swallow branch leaves the
// whole suite green without this test, so the code was correct today and
// unguarded tomorrow.
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp) = tree_app_with_keymap(
r#"[{"key": "ctrl+double_click", "command": "quick_open", "when": "editor"}]"#,
);
app.hover_popup = Some(crate::widgets::hover_popup::HoverPopup::new(
String::from("stale hover"),
(1, 1),
));
app.tab_tooltip = Some(crate::widgets::hover_popup::HoverPopup::new(
String::from("stale tab tooltip"),
(1, 1),
));
let mut ev = mouse(
MouseEventKind::Down(MouseButton::Left),
app.editor.last_inner.x + 4,
app.editor.last_inner.y + 1,
);
ev.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ev);
// Proves this took the SWALLOW path, not the matched one: only
// `ctrl+double_click` is bound, so a single click matches no command.
// Without this the test could pass via the sibling branch's teardown and
// say nothing about the swallow.
assert!(
app.file_finder.is_none(),
"the prefix click must NOT fire the bound double's command — if it \
did, this exercises the matched branch and not the swallow"
);
assert!(
app.hover_popup.is_none(),
"a swallowed prefix click must dismiss the hover it painted over, \
exactly as the matched branch does: it re-focuses the pane underneath"
);
assert!(app.tab_tooltip.is_none(), "and the tab tooltip with it");
}
#[test]
fn every_mouse_binding_the_docs_show_actually_loads() {
// Round 7 found `paste` and `page_up` in this example, neither of which is
// a real command id: `Keymap::from_json` skipped both rows with a warning,
// so a user copying the documented snippet got a keymap that silently did
// less than it said. A doc example that does not load is worse than none,
// and the only way that stays true is to load the real file here rather
// than a copy that can drift from it.
let doc = include_str!("../../docs/KEYBINDINGS.md");
let block = doc
.split("## Mouse bindings in `keybindings.json`")
.nth(1)
.expect("the mouse bindings section is still in KEYBINDINGS.md")
.split("```jsonc")
.nth(1)
.and_then(|rest| rest.split("```").next())
.expect("the section still carries a jsonc example block");
assert!(
block.contains("\"command\""),
"the extracted block must be the binding example, not an empty match"
);
let (_km, warnings) = crate::keymap::Keymap::resolve(block);
assert!(
warnings.is_empty(),
"the documented example must load cleanly, but got: {warnings:?}"
);
}
#[test]
fn a_modified_double_click_can_fire_at_all() {
// The dispatch deliberately refuses to record a MODIFIED click into the
// built-in trackers: they are shared with the editor's plain select-word,
// so arming them with a ctrl+click would make the user's next ORDINARY
// click select a word they never asked for. But `double_click` is only
// classified by asking a tracker whether it just saw a click here — so
// with nothing recording modified clicks, `ctrl+double_click` could never
// become true and the binding was unreachable. A separate tracker keeps
// both rules: the built-in one stays unarmed, the modified pair is seen.
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Bound in `terminal`, not `editor`: with no file open the editor is never
// laid out (`last_area` comes back height 0), so no click coordinate can
// land in it and the binding's `when` could never match. The terminal is
// always present, and this test is about whether a modified double-click
// can fire AT ALL — the region it fires in is incidental.
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 before = app.editor.wrap_enabled();
let area = app.terminals[0].last_area;
assert!(
area.width > 4 && area.height > 2,
"the terminal must be laid out, or the click lands nowhere and this \
test passes or fails for reasons unrelated to double-click tracking"
);
let (col, row) = (area.x + 2, area.y + 1);
// First ctrl+click: arms the modified tracker, fires nothing (no `click`
// row is bound), and must NOT arm the plain tracker.
let mut first = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
first.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(first);
assert_eq!(
app.editor.wrap_enabled(),
before,
"the first click of the pair is not yet a double"
);
// Second ctrl+click at the same cell: now it is a double, so it fires.
let mut second = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
second.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(second);
assert_ne!(
app.editor.wrap_enabled(),
before,
"ctrl+double_click must be reachable, not permanently dead"
);
}
#[test]
fn a_bound_gesture_moves_keyboard_focus_to_the_pane_it_clicked() {
// Round 7: the dispatch made the clicked terminal pane ACTIVE (so commands
// read the right grid) but never called `focus_pane`, which is a different
// thing — it decides where the next KEYSTROKE goes. So a bound gesture
// clicked into the terminal ran against the terminal while the user's
// typing kept going to the editor they had left.
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+click", "command": "mouse_open_link_at_click", "when": "terminal"}]"#,
);
app.focus_pane(Pane::Editor);
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 is visible");
let mut ev = mouse(
MouseEventKind::Down(MouseButton::Left),
area.x + 2,
area.y + 1,
);
ev.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ev);
// `matches!` rather than `assert_eq!`: `Pane` has no `Debug`, and deriving
// one on a production type just to format a test failure is the wrong
// trade.
assert!(
matches!(app.focus, Pane::Terminal),
"clicking a pane with a bound gesture must focus it, or the next \
keystroke goes to the pane the user just clicked away from"
);
}
#[test]
fn a_bound_wheel_gesture_fires_and_a_modified_wheel_does_not_match_the_bare_row() {
// The wheel is the one gesture family whose dispatch no other test drives
// end to end — the rest of the coverage stops at the parser. It is also
// the family where a regression is invisible: a wheel that silently falls
// through to the built-in scroll looks like ordinary scrolling.
//
// Modifiers are part of a gesture's identity, so a bare `wheel_up` row
// must not answer a ctrl+wheel_up. That is the same rule the shift test
// above pins for clicks, checked here for the wheel.
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp) =
tree_app_with_keymap(r#"[{"key": "wheel_up", "command": "quick_open", "when": "editor"}]"#);
let _ = MouseButton::Left;
let (col, row) = (app.editor.last_inner.x + 4, app.editor.last_inner.y + 1);
let mut modified = mouse(MouseEventKind::ScrollUp, col, row);
modified.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(modified);
assert!(
app.file_finder.is_none(),
"ctrl+wheel_up must not match a bare `wheel_up` row"
);
app.handle_mouse(mouse(MouseEventKind::ScrollUp, col, row));
assert!(
app.file_finder.is_some(),
"a bare wheel_up binding must fire through the dispatch"
);
}
#[test]
fn a_bound_gesture_resolves_the_link_in_the_pane_it_clicked_not_the_active_one() {
// Splits make several terminals visible at once, and every terminal
// command reads the grid through `self.terminal()`, i.e. the ACTIVE
// pane. The built-in ctrl+click makes the clicked pane active before
// resolving the link; the binding dispatch returns above that point, so
// without its own activation a bound `mouse_open_link_at_click` inspects
// whichever pane happened to be focused and reports "No link there" over
// a URL the user can plainly see.
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+click", "command": "mouse_open_link_at_click", "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");
// The URL is printed into pane 0 only, while pane 1 holds focus.
// An OSC 8 hyperlink with a NON-WEB scheme, not a printed http(s) URL.
// `terminal_url_click` checks `hyperlink_at_screen` before text sniffing,
// so this resolves; and `open_detected_url` then refuses a non-web scheme
// inertly. A printed https URL would reach `open_url`, which is
// `Command::new("open")` with no test guard — the suite would launch a
// real browser on every run (#307's spawning class).
app.terminals[0].feed_bytes_for_test(b"a prompt got here first\r\n");
// A DECOY link on an earlier row. It pins the exact-URI predicate the
// same way it is pinned in the split-feed siblings: under `.is_some()`
// the row-major search hits the decoy, the click resolves it, and the
// `zero@` status assertion below fails by name. The decoy goes into pane
// 0 alongside the payload, so it cannot weaken the "WHICH pane resolved"
// claim: pane 1 still carries no link at all.
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:zero@example.com\x1b\\zero-link\x1b]8;;\x1b\\\r\n");
app.active_terminal = 1;
term.draw(|f| app.render(f)).unwrap();
// Click directly on the URL, in pane 0, the pane that is NOT active.
//
// The cell is SEARCHED FOR rather than computed as "first row after the
// border". Pane 0 runs a real shell, so its prompt races the fed bytes:
// when the prompt lands first the printed line is pushed down a row and
// the assumed cell holds nothing, which is a flake under full-suite load
// and passes every time in isolation (#397). The `a prompt got here
// first` line above makes that order permanent instead of occasional, so
// this test now exercises the case that used to break it.
//
// Searching costs nothing here: the claim is "clicking the link in pane 0
// resolves against pane 0", and any cell carrying that link is a fair
// place to click. The precondition survives, because a pane with no such
// cell fails below rather than clicking somewhere arbitrary.
let (col, row) = cell_with_link(&app.terminals[0], "mailto:zero@example.com").expect(
"pane 0 must carry the OSC 8 link somewhere in its area, or a refusal proves nothing",
);
let mut ev = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ev.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ev);
// Positive form, not `assert_ne!("No link there")`: excluding one string
// cannot tell "resolved pane 0's link" from "resolved nothing and said so
// differently". The `zero@` address also pins WHICH pane resolved — pane 1
// holds focus and carries no link.
assert_eq!(
app.status, "Refused to open non-web link: mailto:zero@example.com",
"the bound command must resolve against the CLICKED pane; it read the active one"
);
assert_eq!(
app.active_terminal, 0,
"clicking a pane through a binding makes it active, as the built-in does"
);
}
#[test]
fn a_mouse_tracking_child_keeps_the_pointer_from_a_bound_wheel() {
// A tracking child owns the gestures croft actually FORWARDS: the wheel
// (both wheel arms) and, since #474, the left button. So a bound wheel
// must decline for the child. The left click is covered by
// `a_bound_click_defers_to_a_mouse_tracking_child`, which asserts the
// same rule for the same reason.
//
// SHIFT is the documented override.
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();
// The child enables mouse tracking.
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);
// Precondition: the cell must be inside `last_inner`, or the guard
// declines for the BORDER reason and this proves nothing about tracking.
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"
);
}
/// The Shift half of the same rule, on its own app: the first click of the
/// pair above is forwarded to the child, which starts a selection drag, and
/// a drag in flight legitimately swallows the next press. Sequencing the two
/// halves would test that interaction rather than the bypass.
#[test]
fn holding_shift_takes_the_pointer_back_from_a_tracking_child() {
// Shift is ALSO part of a gesture's identity, so the bypass selects a
// different row rather than rescuing the `ctrl+click` one: over a
// tracking TUI you must bind `ctrl+shift+click` for a gesture that fires.
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 a_tab_strip_binding_fires_only_on_the_strip() {
// `gesture_for` deliberately shares `editor_click` between the strip and
// the editor body. That is only safe because a double needs both clicks
// at the SAME cell and the two regions never overlap, so pin it.
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp) = tree_app_with_keymap(
r#"[{"key": "ctrl+click", "command": "quick_open", "when": "tab_strip"}]"#,
);
let strip_y = app.editor.tab_strip_y_for_test();
let tab = app
.editor
.tab_at(app.editor.last_inner.x + 1, strip_y)
.map(|_| (app.editor.last_inner.x + 1, strip_y))
.expect("a rendered tab cell to aim at");
let mut on_strip = mouse(MouseEventKind::Down(MouseButton::Left), tab.0, tab.1);
on_strip.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(on_strip);
assert!(
app.file_finder.is_some(),
"the strip row fires on the strip"
);
// The body is a different region, so the same spelling must fall through
// to the built-in rather than firing the tab_strip row.
app.file_finder = None;
let body_row = app.editor.last_inner.y + 1;
assert_ne!(body_row, strip_y, "the strip and the body do not overlap");
let mut in_body = mouse(
MouseEventKind::Down(MouseButton::Left),
app.editor.last_inner.x + 4,
body_row,
);
in_body.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(in_body);
assert!(
app.file_finder.is_none(),
"a tab_strip binding must not fire in the editor body"
);
}
#[test]
fn the_at_click_commands_refuse_a_keyboard_invocation() {
// Each reads the click through `last_mouse_pos`, which a palette or
// chord invocation leaves None. They must say so rather than guess at
// the caret and act somewhere the user never pointed.
use crate::widgets::command_palette::Command;
let (mut app, _tmp) = tree_app_with_keymap("[]");
for (cmd, want) in [
(
Command::MouseAddCursorAtClick,
"Mouse: Add Cursor at Click needs a mouse binding",
),
(
Command::MouseGoToDefinitionAtClick,
"Mouse: Go to Definition at Click needs a mouse binding",
),
(
Command::MouseOpenLinkAtClick,
"Mouse: Open Link at Click needs a mouse binding",
),
] {
app.last_mouse_pos = None;
app.status.clear();
app.run_command(cmd);
assert_eq!(app.status, want, "{cmd:?} must refuse a keyboard call");
}
}
#[test]
fn a_modified_click_binding_does_not_arm_the_plain_double_click() {
// `GestureKind::Click` covers `ctrl+click` too, and the built-ins read
// their trackers without consulting modifiers. Recording a modified click
// armed the editor's plain double-click, so the user's next ordinary
// click selected a word they never gestured for.
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("t.rs");
std::fs::write(&file, "let name = value;\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.keymap = crate::keymap::Keymap::from_json(
r#"[{"key": "ctrl+click", "command": "save_file", "when": "editor"}]"#,
);
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let col = app.editor.last_inner.x + 12;
let row = app.editor.last_inner.y;
let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ctrl.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ctrl);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
// A plain click always anchors a collapsed selection (anchor == head);
// that is true with no binding loaded too. The defect is a non-empty one,
// i.e. a WORD the user never gestured for.
let selected_a_word = app.editor.selection.is_some_and(|s| s.anchor != s.head);
assert!(
!selected_a_word,
"a plain click after a bound ctrl+click must not select a word, got {:?}",
app.editor.selection
);
}
#[test]
fn the_first_click_of_a_bound_modified_pair_does_not_fire_the_builtin() {
// The dispatch guard is `Some((ctx, gesture, Some(cmd)))`. When a gesture
// classifies but matches no command — exactly the first click of a
// `ctrl+double_click` pair, which by construction can only be a
// `ctrl+click` — the pattern fails, nothing returns early, and control
// reaches the built-in Ctrl+click arm. So binding ONLY the double gave a
// spurious Go to Definition on every first click: the gesture was
// recognised as half of a bound pair and then leaked into the built-in it
// was supposed to be part of.
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("t.rs");
std::fs::write(&file, "let name = value;\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.keymap = crate::keymap::Keymap::from_json(
r#"[{"key": "ctrl+double_click", "command": "save_file", "when": "editor"}]"#,
);
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let (col, row) = (app.editor.last_inner.x + 12, app.editor.last_inner.y);
let (before_row, before_col) = (app.editor.cursor_row, app.editor.cursor_col);
let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ctrl.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ctrl);
// `trigger_definition_at` moves the caret to the clicked position before
// asking the server, so an unmoved caret is the observable proof the
// built-in did not run. Asserting on the LSP request itself would need a
// live server; the caret is the same signal without one.
assert_eq!(
(app.editor.cursor_row, app.editor.cursor_col),
(before_row, before_col),
"the first click of a bound ctrl+double_click must not reach the \
built-in Ctrl+click Go to Definition, but the caret moved as though \
it had"
);
}
#[test]
fn an_unmatched_modified_click_does_not_arm_the_tracker() {
// The shape that actually reaches the built-in `terminal_click.record`,
// which has no modifier guard: a modified click that CLASSIFIES, matches
// no binding, and is NOT the first half of a bound double-click. Binding
// `alt+double_click` and clicking with CTRL gives exactly that — the
// swallow branch declines (the bound double is ALT, the click is CTRL, so
// `is_double_click_prefix` is false for this gesture), and the dispatch
// falls through to the built-in for real.
//
// If `record` armed on it, the user's next ordinary click would select a
// word they never gestured for.
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": "alt+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"
);
// A line of output IN FRONT of the token, so the ordering that used to
// break these tests is the one this test always runs (#397), and the cell
// is SEARCHED rather than assumed.
//
// Assuming it made this test conditionally vacuous, which is worse than
// plainly vacuous: measured both ways, with `ClickTracker::record`'s
// modifier guard deliberately broken, it FAILED with the token on the
// assumed row and PASSED with the token one row down. So it discriminated
// whenever it was checked by hand and went blind precisely under load,
// which is the only condition it exists to cover. The negative assertion
// at the end is satisfied by a click that lands on blank and selects
// nothing, whether or not the tracker armed.
// One call rather than two, which is fewer moving parts and nothing more:
// `cell_carrying` searches every cell of every row, so a prompt landing
// between two feeds and prefixing the payload row is tolerated either way.
// The sibling tests still feed their decoy and payload separately.
//
// The payload row OPENS with a shell-shaped prefix on purpose. It is what
// gives the span predicate a red state: under a row-level `contains` the
// search resolves the `b` of `bash-5.2$`, `select_word_at` takes the word
// there instead of the token, and the positive control below fails by
// name. Every other fixture in this file prints its needle at column 0,
// where a row test and a span test pick the same cell and the refinement
// cannot go red.
app.terminals[0].feed_bytes_for_test(
b"a prompt got here first\r\nbash-5.2$ hello_world_token some other text\r\n",
);
term.draw(|f| app.render(f)).unwrap();
let (col, row) = cell_carrying(&app.terminals[0], "hello_world_token")
.expect("the pane must show THIS test's token, or there is no word to mis-select");
// Precondition: the CTRL click must match nothing, or it returns early
// from the matched dispatch and never reaches the built-in.
let ctrl_gesture = crate::keymap::Gesture {
kind: crate::keymap::GestureKind::Click,
mods: KeyModifiers::CONTROL,
};
assert!(
app.keymap
.command_for_mouse(ctrl_gesture, crate::keymap::MouseContext::Terminal)
.is_none(),
"ctrl+click must match nothing, or this never reaches the built-in"
);
assert!(
!app.keymap
.is_double_click_prefix(ctrl_gesture, crate::keymap::MouseContext::Terminal),
"ctrl+click must NOT be a double-click prefix here, or the swallow \
branch returns first and the built-in is never reached"
);
let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ctrl.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ctrl);
// A following PLAIN click must be a fresh single click, not the second
// half of a double the modified click armed.
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col + 1, row));
let selected = app.terminal().selection_text();
assert!(
!selected.contains("hello_world_token"),
"a plain click after an unmatched ctrl+click must not select a WORD: \
the ctrl+click must not have armed the double-click tracker, but \
selection was {selected:?}"
);
// The POSITIVE half, over the same cell. Without it, "the tracker stayed
// unarmed" and "word selection could never have happened here" are the
// same green: a click landing somewhere unselectable satisfies the
// negative whatever the tracker did.
//
// ONE more click, not two. The plain click above DID arm the tracker -
// that is the behaviour being contrasted with the ctrl+click, which must
// not - so this one pairs with it (`is_double` allows a one-column drift)
// and selects the word. A second click would then start a FRESH
// single-cell selection and wipe it, which is what the first draft of this
// control did and why it failed.
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
// The WORD, exactly. `select_word_at` brackets the alphanumeric run
// around the pivot and `selection_text` extracts that span, so a correct
// select yields the token and nothing else; `contains` would also accept
// a selection wider than the word, which is the shape a scroll-clock
// rebase can produce. This PR tightened two status assertions for the
// same reason, so its own new control should not be looser.
assert_eq!(
app.terminal().selection_text(),
"hello_world_token",
"a PLAIN click pairing with the plain click above must select the \
word: the tracker arms on plain clicks and refuses only modified \
ones, and without this the negative above proves nothing"
);
}
#[test]
fn a_modified_click_binding_does_not_arm_the_plain_double_click_in_the_terminal() {
// `terminal_click.record` has no modifier guard, so a ctrl+click that
// REACHES it arms the plain double-click tracker and the user's next
// ordinary click selects a word they never gestured for.
//
// What this test ACTUALLY covers is the swallow branch, not the built-in.
// With only `ctrl+double_click` bound, the pair's first click matches no
// command, `is_double_click_prefix` is therefore true, and the SWALLOW
// branch returns before the built-in path runs — so `terminal_click.record`
// is never reached here. Deleting the swallow branch does fail this test,
// which is what it guards: the prefix click must not arm the tracker.
//
// The unguarded `record` itself is covered separately by
// `an_unmatched_modified_click_does_not_arm_the_tracker`, which uses a
// gesture that classifies, matches nothing, and is NOT a double-click
// prefix — the only shape that actually reaches the built-in.
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,
"the terminal must be laid out, or the clicks land nowhere and this \
test passes for reasons unrelated to tracker arming"
);
// There must be a WORD under the pointer. `select_word_at` is what a
// spuriously-armed tracker triggers, and it selects nothing on a blank
// cell — so clicking an empty terminal makes this test pass vacuously
// whether the tracker armed or not. Print text first, and assert it
// arrived, so the click has a real word to wrongly select.
// A line of output IN FRONT of the token, so the ordering that used to
// break these tests is the one this test always runs (#397).
app.terminals[0].feed_bytes_for_test(b"a prompt got here first\r\nhello_world_token\r\n");
term.draw(|f| app.render(f)).unwrap();
// SEARCHED, not assumed. This test already carried a positive control, so
// a displaced token failed it outright rather than passing vacuously - the
// flaking half of the same defect its sibling had the vacuous half of.
let (col, row) = cell_carrying(&app.terminals[0], "hello_world_token")
.expect("the pane must show THIS test's token, or there is no word to mis-select");
// No re-derivation of `cell_carrying`'s own predicate here. It ran that
// exact span test on this pane and this cell to produce `(col, row)`, so
// repeating it can only fail if the live shell scrolled the grid between
// the search and the re-read - a different fault from the one such an
// assertion would name.
//
// The span property is not pinned HERE. This test's payload prints at
// column 0, where a row predicate and a span predicate select the same
// cell, and both assertions below are negatives. Its red state lives in
// `an_unmatched_modified_click_does_not_arm_the_tracker`, whose payload
// row opens with a shell prefix and whose positive control fails by name
// under a row predicate.
let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ctrl.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ctrl);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
// A plain click ALWAYS anchors a collapsed one-cell selection
// (`start_selection_at`), so the correct outcome here is the single
// character under the pointer — not an empty string. The defect is the
// tracker firing `select_word_at`, which yields the whole WORD.
//
// Asserting emptiness would fail on correct behaviour, so the assertion
// is against the word: anything longer than the one anchored cell means a
// double-click fired off a click the user never paired.
let selected = app.terminal().selection_text();
assert!(
!selected.contains("hello_world_token"),
"a plain click after a bound ctrl+click must not select a WORD in the \
terminal — the ctrl+click armed the plain double-click tracker. \
Expected the one anchored cell, got {selected:?}"
);
assert!(
selected.chars().count() <= 1,
"a plain click anchors exactly one cell; a longer selection means the \
tracker fired a double-click, got {selected:?}"
);
}
#[test]
fn a_bound_click_defers_to_a_mouse_tracking_child() {
// `child_owns_pointer` covers a bound CLICK the same way it covers the
// wheel, because since #474 the left button is a gesture croft actually
// forwards: the Down(Left) arm sends the press to a tracking child. So a
// `ctrl+click` binding must decline over a tracking child -- the child
// asked for the pointer -- and the press must reach it with the Ctrl bit
// set, exactly as it would under a bare terminal emulator. SHIFT remains
// the bypass (`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.keymap = crate::keymap::Keymap::from_json(
r#"[{"key": "ctrl+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"
);
let (col, row) = (area.x + 2, area.y + 1);
app.terminals[0].feed_bytes_for_test(b"\x1b[?1000h\x1b[?1006h");
assert!(
app.terminals[0].mouse_reporting(),
"the child must be tracking, or this test says nothing about the guard"
);
let Some((lr, lc)) = app.terminals[0].cell_at(col, row) else {
panic!(
"the click must land on a real grid cell, or the guard declines for the \
border reason instead of the tracking one and the test is vacuous"
);
};
let before = app.editor.wrap_enabled();
let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ctrl.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ctrl);
assert_eq!(
app.editor.wrap_enabled(),
before,
"a bound ctrl+click over a tracking child must NOT run: the child asked \
for the pointer and croft forwards the press to it"
);
let expected = format!("\x1b[<16;{};{}M", lc + 1, lr + 1);
assert_eq!(
String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()),
expected,
"the press reaches the child as an SGR report carrying the Ctrl bit"
);
}
#[test]
fn the_swallow_guard_reads_the_clicked_terminal_not_the_active_one() {
// `terminal_would_open_something_at` decides whether swallowing a
// double-click prefix would cost the user a built-in link-open. The
// built-in calls `activate_terminal_pane(idx)` BEFORE it looks for a
// link, so it reads the CLICKED pane. A predicate reading
// `self.terminal()` reads the ACTIVE pane, and in any split layout where
// the click lands outside the focused pane those are different content —
// so the swallow decision disagrees with what the built-in then does.
//
// Observable is a REFUSED link (`open_detected_url` rejects a non-web
// scheme inertly). A printed https URL would reach `open_url`, which is
// `Command::new("open")` with no test guard, and the suite would launch a
// real browser on every run.
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);
// Only the DOUBLE is bound, so a single ctrl+click is a prefix and the
// swallow branch is the one under test.
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");
// Link in pane 0; pane 1 is ACTIVE. The two panes must differ, or the
// bug is unreachable and this test proves nothing.
app.terminals[0]
// A DECOY link on an earlier row. Under the `.is_some()` this branch
// replaced, the row-major search hits the decoy first and the click
// resolves the wrong link, so the exact-status assertion fails with
// `decoy@` in the message. That is the red state the tightening
// shipped without: nothing else in these panes emits OSC 8, so
// reverting it left the suite green.
//
// `mailto:` rather than `file://` deliberately: `file://` is
// intercepted by `editor_file_uri` and would exercise a different arm.
.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();
// FIND the link's cell rather than assuming which row it landed on
// (#397). Pane 0 has a real shell, and its prompt arrives from the
// reader thread whenever the OS gets round to it - before the injected
// bytes on a loaded machine, after them on a quiet one. Either way the
// link is in the pane; only its row moves, and hard-coding
// `area.y + 1` made the test a race against shell startup rather than a
// check of the swallow guard it is named for.
//
// The search IS the click coordinate here, not a separate check ahead of
// one, and it is anchored on this test's own URI rather than on "a link":
// the decoy above is what makes that distinction fail loudly. Every cell
// `cells_of` yields is inside `last_area`, which `hyperlink_at_screen`
// hit-tests, so a cell found is a cell a click reaches - the claim is not
// weakened by not naming the row.
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 ctrl_click_on_a_line_range_selects_the_range() {
// #804: `path:62-69` opens with lines 62 to 69 selected, the view on 62.
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("t.py");
std::fs::write(&file, "l1\nl2\nl3\nline four\nl5\nl6\n").unwrap();
let log = tmp.path().join("agent.log");
// An escape makes it a rendered log, where Ctrl+click follows references.
std::fs::write(&log, "\x1b[1mt.py:2-4\x1b[0m has the case\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
assert!(
app.editor.log.is_some(),
"the log opens in the rendered view"
);
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let body = app.editor.log.as_ref().unwrap().last_body;
app.handle_mouse(MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column: body.x + 6,
row: body.y,
modifiers: KeyModifiers::CONTROL,
});
assert_eq!(app.editor.path.as_deref(), Some(file.as_path()));
let sel = app.editor.selection.expect("the range is selected");
assert_eq!(sel.normalised(), ((1, 0), (3, 9)), "lines 2 to 4, whole");
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 0));
assert!(app.status.ends_with(":2-4"), "{}", app.status);
}
/// A `path:line` printed in a RENDERED ANSI log is Ctrl+clickable, the
/// same as one printed in a terminal pane (#257).
///
/// The reference is scanned against the text the user SEES. The fixture is
/// built so that matters: the second path sits after a 36-character SGR run
/// with no printed width, so its visible column falls INSIDE an escape
/// sequence in the raw bytes. A raw-bytes scan finds no reference at that
/// column at all, which is what makes this test turn on the mapping rather
/// than merely coexist with it.
///
/// Ctrl is what separates it from a selection drag: `begin_log_selection`
/// runs before the editor's Ctrl handling, so without the guard the modifier
/// click would just start a selection.
#[test]
fn a_file_reference_in_a_rendered_log_is_ctrl_clickable() {
let tmp = tempfile::tempdir().unwrap();
let first = tmp.path().join("first.rs");
let second = tmp.path().join("second.rs");
std::fs::write(&first, "a\nb\nc\n").unwrap();
std::fs::write(&second, "one\ntwo\nthree\nfour\nfive\nsix\nseven\n").unwrap();
// An SGR run with zero printed width, placed BETWEEN the two references
// so the second one's screen column and byte offset diverge. It must be
// LONGER than the path itself, or the shifted column still lands inside
// the raw path token and both implementations agree - tempdir paths are
// ~50 characters and vary per platform, so scale it rather than picking
// a constant that silently stops discriminating. The assertion below
// proves the fixture actually discriminates.
let esc = "\x1b[1;3;4;38;2;255;0;0m".repeat(second.display().to_string().len() / 10 + 4);
let log = tmp.path().join("build.log");
std::fs::write(
&log,
format!(
"{}:1 {esc}then {}:7 end\nconnecting to host.com:443\n",
first.display(),
second.display()
),
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
assert!(
app.editor.log.is_some(),
"the log must open in the rendered view, or this tests nothing"
);
let backend = ratatui::backend::TestBackend::new(200, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let body = app.editor.log.as_ref().unwrap().last_body;
let visible = |app: &App, line: usize| -> String {
app.editor
.log
.as_ref()
.unwrap()
.visible_text(line)
.expect("line is parsed")
.to_string()
};
// The second reference: visible column lands inside an escape in the raw
// bytes, so only the escape-free scan can resolve it.
let text = visible(&app, 0);
let at = text.find("second.rs").expect("visible after stripping");
let raw = std::fs::read_to_string(&log).unwrap();
let raw_line = raw.lines().next().unwrap();
assert!(
crate::file_ref::file_ref_at(raw_line, at)
.is_none_or(|fr| fr.path != second.display().to_string()),
"fixture is wrong: a raw-bytes scan at column {at} already finds this \
reference, so the test would pass without the escape-free mapping"
);
app.handle_mouse(MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column: body.x + u16::try_from(at).unwrap(),
row: body.y,
modifiers: KeyModifiers::CONTROL,
});
assert_eq!(
app.editor.path.as_deref(),
Some(second.as_path()),
"Ctrl+click on a path after an escape run opens that file"
);
assert_eq!(
app.editor.cursor_row, 6,
"and lands on the referenced line (`:7`, 0-based)"
);
// A lookalike must NOT be opened: only `is_file()` separates
// `host.com:443` from a real reference, and nothing else asserts it.
app.editor.open(&log).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let host_line = visible(&app, 1);
let hat = host_line
.find("host.com")
.expect("the lookalike is on line 1");
app.handle_mouse(MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column: body.x + u16::try_from(hat).unwrap(),
row: body.y + 1,
modifiers: KeyModifiers::CONTROL,
});
assert_eq!(
app.editor.path.as_deref(),
Some(log.as_path()),
"`host.com:443` resolves to no file, so the click must not navigate"
);
assert!(
app.editor.log.as_ref().is_some_and(|l| l.dragging),
"and it falls through to a selection drag rather than being eaten"
);
// Without Ctrl the same cell still starts a selection drag. `has_selection`
// needs a != b, so a press alone is not yet a selection: the anchor IS the
// head until a drag moves it.
app.editor.open(&log).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
app.handle_mouse(MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column: body.x + u16::try_from(at).unwrap(),
row: body.y,
modifiers: KeyModifiers::NONE,
});
assert_eq!(
app.editor.path.as_deref(),
Some(log.as_path()),
"a plain click stays in the log"
);
assert!(
app.editor.log.as_ref().is_some_and(|l| l.dragging),
"a plain click still begins a selection drag"
);
}
#[test]
fn a_prefix_click_defers_to_the_builtin_for_a_file_reference_too() {
// The built-in Ctrl+click tries `terminal_url_click` OR
// `terminal_file_click`. A swallow guard that consults only the URL half
// still eats the file jump -- the same defect one branch over, which is
// exactly the shape that produced this PR's major 2. Both arms or neither.
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("target_file.rs"), "fn main() {}\n").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 > 12 && area.height > 2,
"terminal must be laid out"
);
// The same class as the OSC 8 tests, reached through `terminal_file_click`
// rather than `terminal_url_click`. The audit that found the others was
// scoped to "tests that feed an OSC 8 link", which excludes a bare file
// reference BY CONSTRUCTION - so the scope, not the code, is what hid it.
app.terminals[0].feed_bytes_for_test(b"a prompt got here first\r\ntarget_file.rs:1:1\r\n");
term.draw(|f| app.render(f)).unwrap();
let (col, row) = cell_carrying(&app.terminals[0], "target_file.rs:1:1")
.expect("the pane must carry THIS test's file reference");
// Precondition: a file REFERENCE must be under the cursor, or the guard
// declines for "nothing there" and the test says nothing about the file
// half specifically.
let has_ref = app.terminals[0]
.line_text_at(col, row)
.is_some_and(|(t, c)| crate::file_ref::file_ref_at(&t, c).is_some());
assert!(
has_ref,
"the cell must carry a file reference, or this test cannot distinguish \
the file arm from the URL arm"
);
let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ctrl.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ctrl);
// The built-in ran: it opened the file rather than the click being
// swallowed as a double-click prefix.
assert!(
app.editor
.path
.as_deref()
.is_some_and(|p| p.ends_with("target_file.rs")),
"the prefix click must fall through to the built-in file jump, but the \
editor holds {:?}",
app.editor.path.as_deref()
);
}
#[test]
fn a_double_click_prefix_over_a_mouse_tracking_child_leaves_the_builtin_alone() {
// The swallow branch exists so the FIRST click of a bound `ctrl+double_click`
// does not fire the built-in that owns the same modifier. Over a
// mouse-tracking child it must still fall through, because swallowing
// would disable the built-in Ctrl+click over every full-screen TUI while
// binding `ctrl+click` leaves it working -- backwards.
//
// Since #474 the child DOES own a left click here (`child_owns_pointer`
// covers Click/DoubleClick), so the swallow steps aside for that reason
// too. The fall-through is right for a narrower reason that survives it:
// the Cmd/Ctrl link-open runs BEFORE the forward in the Down(Left) arm,
// so swallowing this click costs the user the link and buys nobody
// anything -- the bound double is already unreachable over a tracker.
//
// The observable is deliberately a REFUSED link: `open_detected_url`
// rejects a non-web scheme and sets a status without spawning anything.
// Asserting on a successful open would shell out to `open`/`xdg-open` for
// real, creating exactly the flaky spawning test #307 is about.
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"
);
// A real OSC 8 hyperlink with a non-web scheme: the built-in finds it via
// `hyperlink_at_screen`, and `open_detected_url` then refuses it inertly.
// The leading line forces the shell-prompt race (#397) to resolve the way
// that used to break this test, so the cell is searched for instead of
// computed from the border row.
app.terminals[0].feed_bytes_for_test(b"a prompt got here first\r\n");
// Two links in one feed, in the order the bytes carry them: the DECOY
// first, then the payload. The `a prompt got here first` line above is a
// SEPARATE feed, and that is fine here for a reason worth stating, since
// a sibling test was just rewritten to avoid exactly that: this search is
// anchored on a URI, not on a column, so a prompt arriving between the
// two feeds moves the link's row and changes nothing the test asserts.
// The wrap test cannot say that, because a column is precisely its
// claim.
//
// The decoy is what gives the exact-URI SEARCH a
// red state: revert the predicate to `.is_some()` and the row-major scan
// stops on the decoy, so the status assertion rejects it by name. It does
// NOT pin the assertion's FORM - with the search intact, `contains`
// accepts the same correct answer, and an earlier version of this comment
// claimed otherwise.
//
// The trailing newline after the payload parks the cursor on the NEXT
// row, so late shell output cannot write onto the link's own row.
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 a_modified_click_that_drags_away_does_not_pair_with_the_click_it_returns_to() {
// The built-in trackers get `clear_if_moved` on every drag, so click,
// drag away, click back is not a double. `ModifiedClickTracker` has no
// such call anywhere, so the modified pair fires where the identical
// unmodified sequence correctly does not.
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"
);
let (col, row) = (area.x + 2, area.y + 1);
let before = app.editor.wrap_enabled();
let mut ctrl = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
ctrl.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(ctrl);
// Drag well away, then release, then click the origin again.
let mut drag = mouse(MouseEventKind::Drag(MouseButton::Left), col + 20, row + 3);
drag.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(drag);
app.handle_mouse(mouse(
MouseEventKind::Up(MouseButton::Left),
col + 20,
row + 3,
));
let mut back = mouse(MouseEventKind::Down(MouseButton::Left), col, row);
back.modifiers = KeyModifiers::CONTROL;
app.handle_mouse(back);
assert_eq!(
app.editor.wrap_enabled(),
before,
"a modified click that dragged away must not pair with the click it \
returns to, but the double fired"
);
}
#[test]
fn a_reloaded_keymap_with_a_refused_row_reports_its_warning_count() {
// Asserts the summary the reload sets, against a keymap built in memory.
// Writing the real `~/.config/croft/keybindings.json` — which is what the
// previous version of this test did — leaks into every concurrently
// running test that builds an `App`, because `App::new` loads that path
// unconditionally.
let (_refused, warns) = crate::keymap::Keymap::resolve(
r#"[{"key": "cmd+click", "command": "save_file", "when": "editor"}]"#,
);
assert_eq!(warns.len(), 1, "the Cmd row is refused with a reason");
let status = super::keybindings_reload_status(&warns);
assert!(
status.contains("1 warning") && status.contains("OUTPUT"),
"the count must reach the status bar and point at the channel, got {status:?}"
);
assert!(
!super::keybindings_reload_status(&[]).contains("warning"),
"a clean reload says nothing about warnings"
);
}
#[test]
fn a_cmd_or_triple_gesture_is_refused_rather_than_bound_to_a_dead_entry() {
// Both parse but can never match, so binding them would make
// `has_mouse_bindings()` true for entries nothing can look up — and
// would let cmd+click dodge the reserved bare-click check.
let (km, warnings) = crate::keymap::Keymap::resolve(
r#"[{"key": "cmd+click", "command": "save_file"},
{"key": "triple_click", "command": "save_file"}]"#,
);
assert_eq!(warnings.len(), 2, "{warnings:?}");
assert!(
!km.has_mouse_bindings(),
"neither is bound, so the per-event dispatch stays off"
);
assert!(
warnings.iter().any(|w| w.contains("second click")),
"triple_click says the real reason, not 'not a gesture': {warnings:?}"
);
}
#[test]
fn outline_scrollbar_drag_is_not_hijacked_by_the_sidebar_splitter() {
use crate::lsp::manager::{OutlineKind, OutlineSymbol};
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("a.rs");
std::fs::write(&f, "fn main() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Hermetic: App::new reads the user's real config; force the documented
// default views so this test never depends on a personal Outline-off pref.
app.explorer_views = Default::default();
app.editor.open_pinned(&f).unwrap();
// Enough symbols to overflow the OUTLINE's capped half-height so a scrollbar
// is drawn; expand the panel so the body (and its bar) render.
let syms: Vec<_> = (0..200u32)
.map(|i| OutlineSymbol {
name: format!("f{i}"),
detail: None,
kind: OutlineKind::Function,
depth: 0,
line: i,
character: 0,
range_start_line: i,
range_end_line: i,
})
.collect();
app.outline.set_symbols(f.clone(), syms);
app.outline.collapsed = false;
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let bar = app.outline.last_scrollbar;
assert!(
bar.width > 0 && bar.height > 0,
"the overflowing outline must draw a scrollbar"
);
// The outline panel has no right border, so its scrollbar lands on the
// sidebar's rightmost column, inside the splitter's two-cell grab zone. A
// press there must drive the outline's bar, not start a sidebar resize.
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
bar.x,
bar.y + bar.height - 1,
));
assert!(
app.splitter_drag.is_none(),
"pressing the outline scrollbar must not start a sidebar splitter drag"
);
assert!(
app.outline_scrollbar_drag,
"pressing the outline scrollbar must arm the outline scrollbar drag"
);
}
#[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();
// A pane whose script emits the OSC 133 protocol, so a decoration dot
// lands on its left border.
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"
);
// The regression: a lone pane's left border sits exactly in the sidebar
// splitter's two-column grab zone, which used to swallow the click as a
// resize drag before the decoration handler could see it.
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!(
app.splitter_drag.is_none(),
"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 tap_in_the_editor_arms_the_hover_dwell_and_release_keeps_it_armed() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, col, row) = app_with_open_file_and_editor_cell();
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert_eq!(
app.hover.cell(),
Some((col, row)),
"a tap is the touch equivalent of the pointer arriving: it must arm \
the dwell at the tapped cell (a touchscreen never emits Moved events)"
);
assert!(
app.hover
.due(std::time::Instant::now() + HOVER_DELAY, HOVER_DELAY),
"the tap-armed dwell must come due HOVER_DELAY after the press"
);
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row));
assert_eq!(
app.hover.cell(),
Some((col, row)),
"lifting the finger must not cancel the pending dwell, or a quick \
tap could never fire"
);
}
#[test]
fn drag_and_scroll_cancel_a_tap_armed_hover_dwell() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, col, row) = app_with_open_file_and_editor_cell();
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
app.handle_mouse(mouse(MouseEventKind::Drag(MouseButton::Left), col + 3, row));
assert_eq!(
app.hover.cell(),
None,
"a drag is a selection, not a rest: it must cancel the pending dwell"
);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
app.handle_mouse(mouse(MouseEventKind::ScrollDown, col, row));
assert_eq!(
app.hover.cell(),
None,
"scrolling moves the text under the tapped cell; the dwell must cancel"
);
}
#[test]
fn press_and_hold_hover_popup_survives_the_finger_release() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, col, row) = app_with_open_file_and_editor_cell();
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
// The dwell fired while the finger was still down (press-and-hold).
app.hover_popup = Some(crate::widgets::hover_popup::HoverPopup::new(
String::from("int"),
(col, row),
));
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row));
assert!(
app.hover_popup.is_some(),
"releasing the press must not dismiss the popup it just summoned"
);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert!(
app.hover_popup.is_none(),
"the next tap is a new gesture and dismisses the previous popup"
);
}
#[test]
fn a_second_tap_on_the_same_cell_rearms_the_dwell() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, col, row) = app_with_open_file_and_editor_cell();
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
app.hover.mark_fired();
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert!(
app.hover
.due(std::time::Instant::now() + HOVER_DELAY, HOVER_DELAY),
"a fresh tap must restart the dwell even on the same cell, else a \
dismissed popup could never be re-summoned by tapping again"
);
}
/// Right-clicking the editor gutter (glyph margin / line-number column)
/// opens the breakpoint context menu and toggles the breakpoint on the
/// CLICKED line, not the cursor line, mirroring VS Code's glyph-margin
/// menu. The cursor must not move.
#[test]
fn right_click_on_the_gutter_opens_the_breakpoint_menu_and_toggles_the_clicked_line() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("prog.py");
std::fs::write(&f, "l1\nl2\nl3\nl4\nl5\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(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
// Glyph-margin column (left of text_x) on the 3rd content row => 1-based
// line 3. Cursor stays on line 1 throughout.
let gutter_col = app.editor.last_inner.x;
let row = app.editor.last_inner.y + 2;
assert_eq!(app.editor.cursor_row, 0, "precondition: cursor on line 1");
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Right),
gutter_col,
row,
));
let menu = app
.context_menu
.as_ref()
.expect("a gutter right-click must open a context menu");
let labels = menu_labels(&menu.items);
assert!(
labels.contains(&"Add Breakpoint"),
"menu must offer Add Breakpoint when none exists; got {labels:?}"
);
assert!(
labels.contains(&"Add Conditional Breakpoint\u{2026}"),
"menu must offer Add Conditional Breakpoint; got {labels:?}"
);
// Select "Add Breakpoint" and commit it through the real menu key path.
let idx = menu
.items
.iter()
.position(|e| menu_label(e) == "Add Breakpoint")
.unwrap();
app.context_menu.as_mut().unwrap().selected = idx;
app.handle_menu_key(key(KeyCode::Enter, KeyModifiers::NONE));
assert!(
app.context_menu.is_none(),
"committing a menu item must close the menu"
);
assert_eq!(
app.editor.breakpoint_lines(&f),
vec![3u32],
"the breakpoint must land on the clicked line (3), not the cursor line (1)"
);
assert_eq!(
app.editor.cursor_row, 0,
"the gutter click must not move the cursor"
);
// Right-clicking the same gutter line now offers Remove Breakpoint.
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Right),
gutter_col,
row,
));
let labels = menu_labels(&app.context_menu.as_ref().unwrap().items);
assert!(
labels.contains(&"Remove Breakpoint"),
"an existing breakpoint must offer Remove Breakpoint; got {labels:?}"
);
}
/// "Add Conditional Breakpoint" must open a visible popup (the centered
/// `Prompt` overlay), NOT capture keystrokes on the bottom status line. The
/// status line is reserved for read-only info.
#[test]
fn add_conditional_breakpoint_opens_a_popup_not_the_status_line() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("prog.py");
std::fs::write(&f, "l1\nl2\nl3\nl4\nl5\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(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let gutter_col = app.editor.last_inner.x;
let row = app.editor.last_inner.y + 2; // 1-based line 3
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Right),
gutter_col,
row,
));
let idx = app
.context_menu
.as_ref()
.unwrap()
.items
.iter()
.position(|e| menu_label(e) == "Add Conditional Breakpoint\u{2026}")
.expect("menu must offer Add Conditional Breakpoint");
app.context_menu.as_mut().unwrap().selected = idx;
app.handle_menu_key(key(KeyCode::Enter, KeyModifiers::NONE));
// A visible popup must open on the clicked line; nothing should be armed
// on the status line.
let prompt = app
.prompt
.as_ref()
.expect("conditional breakpoint must open a popup prompt, not a status-line input");
assert!(
matches!(prompt.kind, PromptKind::BreakpointCondition { line: 3, .. }),
"popup must target the clicked line (3)"
);
// Type a condition into the popup and commit it via the real key path.
for c in "x > 1".chars() {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(app.prompt.is_none(), "committing must close the popup");
assert_eq!(
app.editor.breakpoint_lines(&f),
vec![3u32],
"committing a condition must create the breakpoint on line 3"
);
let lines = app.editor.breakpoints.get(&f).unwrap();
let specs = app.editor.source_breakpoints(&f, lines);
assert_eq!(
specs[0].condition.as_deref(),
Some("x > 1"),
"the typed expression must be attached as the breakpoint condition"
);
}
/// The gutter menu's "Add Logpoint" opens the popup prompt; committing a
/// message creates the breakpoint with a `logMessage` attached, so the
/// adapter prints instead of pausing (VS Code's logpoint).
#[test]
fn add_logpoint_attaches_a_log_message_to_the_line() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("prog.py");
std::fs::write(&f, "l1\nl2\nl3\nl4\nl5\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(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let gutter_col = app.editor.last_inner.x;
let row = app.editor.last_inner.y + 2; // 1-based line 3
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Right),
gutter_col,
row,
));
let idx = app
.context_menu
.as_ref()
.unwrap()
.items
.iter()
.position(|e| menu_label(e) == "Add Logpoint")
.expect("menu must offer Add Logpoint");
app.context_menu.as_mut().unwrap().selected = idx;
app.handle_menu_key(key(KeyCode::Enter, KeyModifiers::NONE));
let prompt = app.prompt.as_ref().expect("logpoint must open a popup");
assert!(
matches!(prompt.kind, PromptKind::Logpoint { line: 3, .. }),
"popup must target the clicked line (3)"
);
for c in "x is {x}".chars() {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(app.prompt.is_none(), "committing must close the popup");
assert_eq!(
app.editor.breakpoint_lines(&f),
vec![3u32],
"committing a logpoint must create the breakpoint on line 3"
);
let lines = app.editor.breakpoints.get(&f).unwrap();
let specs = app.editor.source_breakpoints(&f, lines);
assert_eq!(
specs[0].log_message.as_deref(),
Some("x is {x}"),
"the typed message must ride the breakpoint as logMessage"
);
assert_eq!(
specs[0].condition, None,
"a logpoint sets no condition of its own"
);
}
#[test]
fn opening_a_search_hit_moves_focus_to_the_editor() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("hit.txt");
std::fs::write(&f, "needle here\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Search);
app.search.query = String::from("needle");
app.search.run_query();
assert!(
matches!(app.focus, Pane::Tree),
"precondition: search holds focus"
);
let hit = app.search.selected_hit().cloned().expect("a hit");
app.open_search_hit(&hit);
assert!(
matches!(app.focus, Pane::Editor),
"opening a search result must hand keyboard focus to the editor so typing no longer leaks into the search box"
);
assert!(!app.search.focused);
}
#[test]
fn opening_a_search_hit_marks_the_active_match_so_the_renderer_paints_it_orange() {
// Global search (Cmd+Shift+F) result navigation must mark the occurrence
// it lands on as the *active* match, the same way the in-file Cmd+F path
// does, so the editor paints that one occurrence orange while the sibling
// matches stay yellow. Without active_search_match every match renders the
// same uniform yellow and the user can't tell which result they are on.
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("hit.rs");
// Line 2 (index 1) has two "alpha" matches: "let " is 4 chars, so the
// first "alpha" starts at char col 4, and the second is later on the line.
std::fs::write(&f, "fn main() {}\nlet alpha = alpha + 1;\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Search);
app.search.query = String::from("alpha");
app.search.run_query();
let hit = app.search.selected_hit().cloned().expect("a hit");
app.open_search_hit(&hit);
assert_eq!(
app.editor.active_search_match,
Some((1, 4, 5)),
"opening a global-search hit must record the first match on the line as the active match (row 1, col 4, len 5) so the renderer paints exactly those cells orange; the second 'alpha' stays yellow"
);
}
#[test]
fn go_to_definition_opens_the_target_file_and_moves_the_caret() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("target.rs");
std::fs::write(&target, "fn a() {}\nfn b() {}\nfn c() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.go_to_definition(target.clone(), 2, 3);
assert_eq!(
app.editor.path.as_deref(),
Some(target.as_path()),
"the definition's file is opened in the editor"
);
assert_eq!(
app.editor.cursor_row, 2,
"caret lands on the definition line"
);
assert_eq!(
app.editor.cursor_col, 3,
"caret lands at the definition column"
);
assert!(
matches!(app.focus, Pane::Editor),
"focus moves to the editor"
);
}
#[test]
fn go_back_returns_to_the_location_before_a_definition_jump() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.rs");
let b = tmp.path().join("b.rs");
std::fs::write(&a, "fn main() {}\nlet x = helper();\n").unwrap();
std::fs::write(&b, "fn helper() {}\nfn other() {}\nfn third() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.editor.cursor_row = 1;
app.editor.cursor_col = 8;
app.go_to_definition(b.clone(), 0, 3);
assert_eq!(
app.editor.path.as_deref(),
Some(b.as_path()),
"the definition jump opens B"
);
assert_eq!(
app.editor.cursor_row, 0,
"caret lands on the definition line"
);
app.nav_back();
assert_eq!(
app.editor.path.as_deref(),
Some(a.as_path()),
"go back returns to file A"
);
assert_eq!(
app.editor.cursor_row, 1,
"caret returns to the line we jumped from"
);
assert_eq!(
app.editor.cursor_col, 8,
"caret returns to the column we jumped from"
);
}
/// A `diff://` link opens two files but is ONE jump for the user, so Back
/// must return to where the click happened — not to the left half of the
/// diff on the way there.
#[test]
fn side_by_side_diff_link_records_one_go_back_entry() {
let tmp = tempfile::tempdir().unwrap();
let origin = tmp.path().join("origin.rs");
let left = tmp.path().join("left.rs");
let right = tmp.path().join("right.rs");
std::fs::write(&origin, "fn main() {}\nlet x = 1;\n").unwrap();
std::fs::write(&left, "fn left() {}\n").unwrap();
std::fs::write(&right, "fn right() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&origin).unwrap();
app.editor.cursor_row = 1;
app.editor.cursor_col = 4;
let lref = crate::file_ref::FileRef {
path: left.to_string_lossy().into_owned(),
line: 1,
column: None,
end_line: None,
};
let rref = crate::file_ref::FileRef {
path: right.to_string_lossy().into_owned(),
line: 1,
column: None,
end_line: None,
};
assert!(app.open_side_by_side(&lref, &rref), "both sides open");
app.nav_back();
assert_eq!(
app.editor.path.as_deref(),
Some(origin.as_path()),
"one Back returns to the clicked location, not the left half"
);
assert_eq!(app.editor.cursor_row, 1, "caret returns to the click row");
assert_eq!(
app.editor.cursor_col, 4,
"caret returns to the click column"
);
}
/// #31: navigate-back rested entirely on the Ctrl+Shift+click mouse chord.
/// The VS Code keyboard chord (Ctrl+-) and the palette command are the
/// fallbacks that work when the host terminal never delivers that chord.
#[test]
fn ctrl_minus_and_the_palette_both_navigate_back() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.rs");
let b = tmp.path().join("b.rs");
std::fs::write(&a, "fn main() {}\nlet x = helper();\n").unwrap();
std::fs::write(&b, "fn helper() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.editor.cursor_row = 1;
app.focus_pane(Pane::Editor);
// The keyboard chord.
app.go_to_definition(b.clone(), 0, 3);
assert_eq!(app.editor.path.as_deref(), Some(b.as_path()));
app.handle_key(key(KeyCode::Char('-'), KeyModifiers::CONTROL))
.unwrap();
assert_eq!(
app.editor.path.as_deref(),
Some(a.as_path()),
"Ctrl+- goes back"
);
// The legacy encoding: Ctrl+- folds to 0x1F, decoded as Ctrl+_.
app.go_to_definition(b.clone(), 0, 3);
app.handle_key(key(KeyCode::Char('_'), KeyModifiers::CONTROL))
.unwrap();
assert_eq!(
app.editor.path.as_deref(),
Some(a.as_path()),
"the legacy Ctrl+- spelling goes back too"
);
// The palette command.
app.go_to_definition(b.clone(), 0, 3);
app.run_command(crate::widgets::command_palette::Command::NavigateBack);
assert_eq!(
app.editor.path.as_deref(),
Some(a.as_path()),
"the Go Back palette command goes back"
);
}
#[test]
fn go_back_with_empty_history_stays_put() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.rs");
std::fs::write(&a, "fn main() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.editor.cursor_row = 0;
app.nav_back();
assert_eq!(
app.editor.path.as_deref(),
Some(a.as_path()),
"with nothing to go back to, go back is a no-op"
);
}
#[test]
fn cmd_shift_s_jumps_to_source_control_from_explorer() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(
KeyCode::Char('S'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(
app.sidebar_view,
SidebarView::SourceControl,
"Cmd+Shift+S must jump to Source Control, not Search"
);
assert!(
matches!(app.focus, Pane::Tree),
"Cmd+Shift+S focuses the Source Control panel"
);
}
#[test]
fn typing_after_reactivating_search_replaces_instead_of_appending() {
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("oldterm");
app.search.clear_selection();
app.focus_pane(Pane::Editor);
app.handle_key(key(
KeyCode::Char('F'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.search.query, "x",
"the previous query was selected, so the first keystroke replaces it"
);
}
#[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");
// Cmd+F opens the find bar rather than being forwarded to the shell.
app.handle_terminal_key(key(KeyCode::Char('f'), KeyModifiers::SUPER));
assert!(app.terminal_find.is_some(), "Cmd+F must open the find bar");
// Typing while the bar is open builds the query, it is not sent to the PTY.
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"
);
// Backspace edits the query.
app.handle_terminal_key(key(KeyCode::Backspace, KeyModifiers::NONE));
assert_eq!(app.terminal_find.as_ref().unwrap().query, "l");
// Esc closes it.
app.handle_terminal_key(key(KeyCode::Esc, KeyModifiers::NONE));
assert!(app.terminal_find.is_none(), "Esc must close the find bar");
}
/// VS Code and iTerm2 on macOS reserve Cmd+F for terminal find and let
/// Ctrl+F through to the child — it is a control byte programs bind
/// (vim's page-forward, the shell's emacs forward-char). Stealing both
/// chords left no way to send 0x06 to a pane at all. Linux keeps Ctrl+F
/// opening find, the VS Code default there.
#[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:?}"
);
}
#[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();
// Swap in a pane that emits an OSC 133 prompt mark and then scrolls it
// into history with filler output.
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 and filler output",
|| {
!app.terminals[0].prompt_lines().is_empty()
&& app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("filler-39"))
},
);
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"
);
// Only one mark: jumping forward finds nothing past it.
app.handle_terminal_key(key(KeyCode::Down, KeyModifiers::SUPER | KeyModifiers::ALT));
assert!(
app.status.contains("No next command"),
"status was: {}",
app.status
);
}
#[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();
// A pane that prints two matchable strings, bottom-most last, and stays
// alive so the grid does not vanish under the test.
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();
// The run-label header (`▶ /bin/sh -c echo …`) also contains both
// sentinels, so wait until the SHA shows up on its own echoed row too
// (a second occurrence); otherwise quick-select can open on a
// header-only viewport and the hint set is timing-dependent.
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"
);
// The echoed SHA is the bottom-most match on screen, so it gets the
// cheapest label (WezTerm / tmux-thumbs assignment order).
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<_>>()
);
// Esc cancels without touching anything.
app.handle_terminal_key(key(KeyCode::Esc, KeyModifiers::NONE));
assert!(app.terminal_quick_select.is_none(), "Esc must cancel");
// Re-enter and commit the SHA's label: copies and closes the mode.
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();
// A run-label pane writes its `▶ …` header synchronously at spawn, so
// the first row has deterministic text to select.
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);
// Render so the pane has a real on-screen area to select inside.
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();
// A real protocol + cell geometry: tests run headless, so the values
// init_graphics would have probed are injected directly.
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::ITerm2;
app.cell_pixel = Some((10, 20));
// The image prints first, then enough filler to scroll it into history.
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();
// At the live bottom the anchor sits in scrollback: no overlay.
term.draw(|f| app.render(f)).unwrap();
assert!(
app.terminal_image_payload().is_none(),
"an off-screen anchor must hide the picture"
);
// Scrolling to the top brings the anchor into view: overlay appears,
// anchored inside the pane at the image's viewport row.
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);
// The main loop would flush the escape and mark it displayed.
app.mark_terminal_image_displayed();
// Snapping back to the live bottom hides it again and arms the clear.
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);
// Render once BEFORE opening quick select: the first render resizes the
// pane to its layout size (reflowing the grid), and hints must be
// computed against the geometry they will be painted in.
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));
// Broadcast: the enable confirm modal paints its red title, and once
// confirmed every receiving pane's name pill carries the ⇶ marker.
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)));
fn screen_rows(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> Vec<String> {
let buf = term.backend().buffer();
(0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
.collect()
})
.collect()
}
term.draw(|f| app.render(f)).unwrap();
assert!(
screen_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_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);
// Cmd+K I asks for confirmation first (the classic multi-pane footgun
// is typing a destructive command into panes you forgot were listening).
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);
// Typed keys now reach every pane: both shells read the same line.
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")))
},
);
// Cmd+K Shift+I toggles the active pane out of the broadcast set.
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('I'), KeyModifiers::SHIFT)));
assert!(app.terminals[0].broadcast_excluded);
// Closing down to one pane drops broadcast (safety: never keep
// broadcasting silently to a shrunk set).
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" } ]"#,
));
// The shell waits for input so the drain tick has pushed the trigger set
// into the pane before the matching line is produced.
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 mcp_success_opens_a_scratch_tab_and_tells_the_user_where() {
// Regression: a successful MCP command rendered its output into a scratch
// tab but the only feedback was a terse "— done", so the user couldn't find
// the output. poll_mcp must open the tab AND name where it went.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let (tx, rx) = std::sync::mpsc::channel();
tx.send(crate::mcp::McpOutcome {
title: String::from("Web: Fetch URL as Markdown"),
body: Ok(String::from("# Example Domain\n\nbody text")),
})
.unwrap();
app.mcp_rx = Some(rx);
assert!(app.poll_mcp(), "a delivered outcome must request a redraw");
let active_path = app
.editor
.path
.as_ref()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_default();
assert!(
active_path.contains("Web: Fetch URL as Markdown"),
"the fetched markdown must be the active editor tab; active path was {active_path:?}"
);
assert!(
app.status.to_lowercase().contains("tab"),
"the status must tell the user the output opened in a tab; got: {}",
app.status
);
}
#[test]
fn paste_into_input_prompt_fills_it_not_the_focused_pane() {
// Regression: opening an MCP command's URL prompt then pasting leaked the
// URL into the focused terminal pane (the popup stayed empty). A bracketed
// paste while a modal input prompt is open must fill the prompt.
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() {
// Sibling of paste_while_terminal_focused_does_not_leak_into_search_box,
// but for the in-file Find bar (Cmd+F). The find bar is pane-scoped, not a
// modal: once the user clicks into the terminal, a paste meant for the
// shell must reach the terminal, not get swallowed by the still-open find
// query. Focus is the deciding factor, not whether editor_find is Some.
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 offload_drop_runs_the_destructor_off_the_calling_thread() {
// Regression for the UI freeze: dropping a notify FSEvents watcher runs
// FsEventWatcher::stop(), which busy-spins on thread::yield_now() until
// its CFRunLoop thread parks. On a MustScanSubDirs rescan that spin never
// ends, so dropping on the UI thread (change_workspace_root -> rebind,
// or disable) freezes the app and pins a core. offload_drop must run the
// destructor on another thread so the caller never blocks on stop().
use std::sync::mpsc;
use std::time::Duration;
struct DropSignal(mpsc::Sender<std::thread::ThreadId>);
impl Drop for DropSignal {
fn drop(&mut self) {
let _ = self.0.send(std::thread::current().id());
}
}
let (tx, rx) = mpsc::channel();
let caller = std::thread::current().id();
super::fs_watch::offload_drop(DropSignal(tx));
let dropped_on = rx
.recv_timeout(Duration::from_secs(5))
.expect("destructor must run within the timeout");
assert_ne!(
dropped_on, caller,
"watcher destructor must run off the calling (UI) thread, not block it"
);
}
#[test]
fn fs_watcher_does_not_descend_into_protected_top_level_dirs() {
// Regression for the macOS App Management TCC prompt: when the
// workspace contains a `Library` subdir at the top level (as $HOME
// does), the watcher must not call WalkDir+stat into it. Asserted
// here by making `Library` unreadable (mode 000): a recursive
// watch would fail spawning because notify_debouncer_full would
// hit a permission error inside the walk; our split-watch path
// skips Library entirely and starts cleanly.
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join("src")).unwrap();
std::fs::write(tmp.path().join("src").join("a.txt"), "hi").unwrap();
let library = tmp.path().join("Library");
std::fs::create_dir(&library).unwrap();
std::fs::create_dir(library.join("Containers")).unwrap();
std::fs::write(library.join("Containers").join("payload"), "x").unwrap();
// Mode 000 makes any descent fail; if the watcher were to descend,
// the WalkDir/stat would error during cache init.
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&library, std::fs::Permissions::from_mode(0o000)).unwrap();
}
let result = super::fs_watch::FsWatch::spawn_watcher(tmp.path());
// Restore perms so tempdir cleanup works.
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&library, std::fs::Permissions::from_mode(0o755));
}
assert!(
result.is_ok(),
"watcher must skip protected dirs and start cleanly"
);
}
#[test]
fn fs_watcher_does_not_deliver_events_from_target_or_node_modules_subtrees() {
// Regression for the M4 CPU storm: when the workspace contains
// `target/` or `node_modules/` at the top level, the FSEvents
// thread used to spend ~60% of its samples inside
// notify_debouncer_full's FileIdMap memcmp loop processing cargo
// and npm writes that we then discarded post-event. The fix is to
// never subscribe to those subtrees in the first place (same
// split-watch pattern already used for Library/.Trash, extended
// to NOISE_DIR_NAMES). This test asserts the contract by writing
// a burst of files into `target/` and verifying the debouncer
// channel receives zero events for those paths, while writes
// under a normal sibling like `src/` still come through.
let tmp = tempfile::tempdir().unwrap();
let src_raw = tmp.path().join("src");
let target_raw = tmp.path().join("target");
let node_modules_raw = tmp.path().join("node_modules");
std::fs::create_dir(&src_raw).unwrap();
std::fs::create_dir(&target_raw).unwrap();
std::fs::create_dir(&node_modules_raw).unwrap();
let src = src_raw.canonicalize().unwrap();
let target = target_raw.canonicalize().unwrap();
let node_modules = node_modules_raw.canonicalize().unwrap();
let (_debouncer, rx) = super::fs_watch::FsWatch::spawn_watcher(tmp.path())
.expect("watcher must start cleanly with noise dirs present");
for _ in 0..30 {
while rx.try_recv().is_ok() {}
std::thread::sleep(std::time::Duration::from_millis(10));
}
for i in 0..50 {
std::fs::write(target.join(format!("cargo_{i}.o")), b"x").unwrap();
std::fs::write(node_modules.join(format!("pkg_{i}.js")), b"x").unwrap();
}
std::thread::sleep(std::time::Duration::from_millis(400));
let mut noise_events: Vec<std::path::PathBuf> = Vec::new();
while let Ok(batch) = rx.try_recv() {
for ev in batch.unwrap_or_default() {
for path in &ev.event.paths {
if path.starts_with(&target) || path.starts_with(&node_modules) {
noise_events.push(path.clone());
}
}
}
}
assert!(
noise_events.is_empty(),
"writes under target/ and node_modules/ must not produce debouncer events; got {noise_events:?}"
);
std::fs::write(src.join("a.rs"), b"fn main() {}").unwrap();
let started = std::time::Instant::now();
let mut signal_events: Vec<std::path::PathBuf> = Vec::new();
while started.elapsed() < std::time::Duration::from_millis(1500) {
while let Ok(batch) = rx.try_recv() {
for ev in batch.unwrap_or_default() {
for path in &ev.event.paths {
if path.starts_with(&src) {
signal_events.push(path.clone());
}
}
}
}
if !signal_events.is_empty() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(
!signal_events.is_empty(),
"writes under src/ must still produce debouncer events after the noise-dir split"
);
}
#[test]
fn fs_watcher_prunes_a_go_module_cache_below_the_workspace_root() {
// The whole reason the watcher's skip predicate takes a &Path rather
// than a bare file name: `go` cannot be blacklisted by name, so
// go/pkg/mod is matched as a component run, and that needs the path.
// Without it the module cache is watched like any other subdir.
let tmp = tempfile::tempdir().unwrap();
let cache_raw = tmp.path().join("go/pkg/mod/golang.org/x");
let src_raw = tmp.path().join("go/cmd");
std::fs::create_dir_all(&cache_raw).unwrap();
std::fs::create_dir_all(&src_raw).unwrap();
let cache = cache_raw.canonicalize().unwrap();
let src = src_raw.canonicalize().unwrap();
let (_debouncer, rx) = super::fs_watch::FsWatch::spawn_watcher(tmp.path())
.expect("watcher must start cleanly with a go module cache present");
for _ in 0..30 {
while rx.try_recv().is_ok() {}
std::thread::sleep(std::time::Duration::from_millis(10));
}
for i in 0..50 {
std::fs::write(cache.join(format!("mod_{i}.go")), b"x").unwrap();
}
std::thread::sleep(std::time::Duration::from_millis(400));
let mut noise_events: Vec<std::path::PathBuf> = Vec::new();
while let Ok(batch) = rx.try_recv() {
for ev in batch.unwrap_or_default() {
for path in &ev.event.paths {
if path.starts_with(&cache) {
noise_events.push(path.clone());
}
}
}
}
assert!(
noise_events.is_empty(),
"writes under go/pkg/mod must not produce debouncer events; got {noise_events:?}"
);
// The sibling go/ source tree is NOT noise and must still deliver.
std::fs::write(src.join("main.go"), b"package main").unwrap();
let started = std::time::Instant::now();
let mut signal_events: Vec<std::path::PathBuf> = Vec::new();
while started.elapsed() < std::time::Duration::from_millis(1500) {
while let Ok(batch) = rx.try_recv() {
for ev in batch.unwrap_or_default() {
for path in &ev.event.paths {
if path.starts_with(&src) {
signal_events.push(path.clone());
}
}
}
}
if !signal_events.is_empty() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
assert!(
!signal_events.is_empty(),
"writes under a real go/cmd source dir must still produce events"
);
}
#[test]
fn fs_watcher_still_watches_a_workspace_whose_own_path_is_noise_named() {
// The noise rules describe what is INSIDE a workspace. The root's own
// ancestors are not part of it, so a checkout that happens to live
// under a `build/` (or `go/pkg/mod/`) ancestor must be watched
// normally. Matching the absolute path pruned every child and left the
// workspace with no watches at all.
let tmp = tempfile::tempdir().unwrap();
let root_raw = tmp.path().join("build/myapp");
let src_raw = root_raw.join("src");
std::fs::create_dir_all(&src_raw).unwrap();
let root = root_raw.canonicalize().unwrap();
let src = src_raw.canonicalize().unwrap();
let (_debouncer, rx) = super::fs_watch::FsWatch::spawn_watcher(&root)
.expect("watcher must start for a root under a noise-named ancestor");
for _ in 0..30 {
while rx.try_recv().is_ok() {}
std::thread::sleep(std::time::Duration::from_millis(10));
}
std::fs::write(src.join("a.rs"), b"fn main() {}").unwrap();
let started = std::time::Instant::now();
let mut signal_events: Vec<std::path::PathBuf> = Vec::new();
while started.elapsed() < std::time::Duration::from_millis(1500) {
while let Ok(batch) = rx.try_recv() {
for ev in batch.unwrap_or_default() {
for path in &ev.event.paths {
if path.starts_with(&src) {
signal_events.push(path.clone());
}
}
}
}
if !signal_events.is_empty() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
assert!(
!signal_events.is_empty(),
"a workspace under a build/ ancestor must still deliver its own events"
);
}
/// #147 + #539: the PRIMARY instance's poll walks EVERY root's expanded rows,
/// so a multi-root workspace's secondary folders reach the noise classifier
/// matching neither of the primary's own roots. Measured whole, a secondary
/// folder at `<tmp>/build/second` had its `build` ancestor make every change
/// under it read as noise: the poll refreshed the tree but reported
/// `finder_relevant = false`, so the Cmd+P index stayed stale for that folder
/// for as long as it was open.
#[test]
fn poll_classifies_a_secondary_root_against_the_root_that_owns_it() {
let tmp = tempfile::tempdir().unwrap();
let primary = tmp.path().join("primary");
let secondary = tmp.path().join("build/second");
std::fs::create_dir_all(&primary).unwrap();
std::fs::create_dir_all(&secondary).unwrap();
let mut app = App::new(primary.clone()).unwrap();
// The watcher is off: this is the POLL's question, and leaving events on
// would let them answer it instead.
app.fs_watch.disable();
app.tree.add_root(secondary.clone());
// Baseline every expanded dir, so the next poll sees ONLY what moves
// after it. Without this the primary's own row is "changed" too and
// would set `finder_relevant` on its own, hiding the secondary entirely.
app.fs_watch.force_poll_due();
let _ = app.fs_watch.poll(&mut app.tree, &[]);
std::fs::write(secondary.join("a.rs"), b"fn main() {}").unwrap();
app.fs_watch.force_poll_due();
let poll = app.fs_watch.poll(&mut app.tree, &[]);
assert!(
poll.dirs_changed,
"precondition: the write moved the secondary root's mtime"
);
assert!(
poll.finder_relevant,
"a secondary workspace folder is workspace content, whatever its own \
path is spelled under"
);
}
/// #539 review: the WATCHER stopped rooting streams at or above a
/// noise-named ancestor, but `drain` still classified EVENT paths whole. A
/// workspace living under `build/` therefore had every one of its own events
/// read as noise: `changed_files` never filled, so the agent-lane ledger saw
/// nothing, and `finder_relevant` never went true, so the Cmd+P index never
/// rebuilt. That is the same freeze the branch fixes, reached from the other
/// side.
#[test]
fn drain_reports_writes_in_a_workspace_under_a_noise_named_ancestor() {
let tmp = tempfile::tempdir().unwrap();
let src_raw = tmp.path().join("build/myapp/src");
std::fs::create_dir_all(&src_raw).unwrap();
let root = tmp
.path()
.join("build/myapp")
.canonicalize()
.expect("the workspace root exists");
let src = src_raw.canonicalize().unwrap();
let mut app = App::new(root.clone()).unwrap();
// Let the watcher thread hand its debouncer over, then swallow whatever
// the install itself produced, so the only events left are the write's.
for _ in 1..=FS_SYNC_TICKS {
app.try_install_pending_init();
let _ = app.fs_watch.drain(&mut app.tree, &app.editor);
std::thread::sleep(std::time::Duration::from_millis(10));
}
let signal = src.join("a.rs");
std::fs::write(&signal, b"fn main() {}").unwrap();
let mut changed: std::collections::BTreeSet<std::path::PathBuf> =
std::collections::BTreeSet::new();
let mut finder_relevant = false;
for _ in 1..=FS_SYNC_TICKS {
let d = app.fs_watch.drain(&mut app.tree, &app.editor);
changed.extend(d.changed_files);
finder_relevant |= d.finder_relevant;
if changed.contains(&signal) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
assert!(
changed.contains(&signal),
"a write inside a workspace under a build/ ancestor is the workspace's \
own content, not noise; got {changed:?}"
);
assert!(
finder_relevant,
"and it is worth a finder index rebuild, since the finder indexes it"
);
}
/// A directory made after the watcher started is watched too: on Linux
/// every directory needs its own watch, installed once at startup, so a
/// write inside a new folder used to go unreported.
#[test]
fn writes_inside_a_directory_made_after_startup_are_reported() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let mut app = App::new(root.clone()).unwrap();
for _ in 1..=FS_SYNC_TICKS {
app.try_install_pending_init();
let _ = app.fs_watch.drain(&mut app.tree, &app.editor);
std::thread::sleep(std::time::Duration::from_millis(10));
}
let dir = root.join("newdir");
std::fs::create_dir(&dir).unwrap();
let early = dir.join("early.rs");
std::fs::write(&early, b"1").unwrap();
let mut changed: std::collections::BTreeSet<std::path::PathBuf> =
std::collections::BTreeSet::new();
for _ in 1..=FS_SYNC_TICKS {
changed.extend(app.fs_watch.drain(&mut app.tree, &app.editor).changed_files);
if changed.contains(&early) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
assert!(changed.contains(&early), "{changed:?}");
let late = dir.join("late.rs");
std::fs::write(&late, b"2").unwrap();
for _ in 1..=FS_SYNC_TICKS {
changed.extend(app.fs_watch.drain(&mut app.tree, &app.editor).changed_files);
if changed.contains(&late) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
assert!(
changed.contains(&late),
"the new folder is watched: {changed:?}"
);
}
#[test]
fn fs_watcher_prunes_noise_dirs_nested_below_the_workspace_root() {
// Regression for the freeze when the workspace root is a *parent of
// repos* (e.g. ~/Documents): there the noise dirs (node_modules/, .git/,
// target/) are NOT direct children of the root, so the old depth-1
// pruning missed them and installed one recursive FSEvents watch over
// the whole tree, re-subscribing every repo's node_modules write storm
// (confirmed by `sample`: five fsevents loops + a mutex-bound debouncer
// at ~45% CPU). Pruning must therefore be depth-aware: a noise dir
// nested under a normal subdir must still never deliver events.
let tmp = tempfile::tempdir().unwrap();
let repo_raw = tmp.path().join("repo");
let src_raw = repo_raw.join("src");
let node_modules_raw = repo_raw.join("node_modules");
let git_raw = repo_raw.join(".git");
std::fs::create_dir_all(&src_raw).unwrap();
std::fs::create_dir_all(&node_modules_raw).unwrap();
std::fs::create_dir_all(&git_raw).unwrap();
let src = src_raw.canonicalize().unwrap();
let node_modules = node_modules_raw.canonicalize().unwrap();
let git = git_raw.canonicalize().unwrap();
let (_debouncer, rx) = super::fs_watch::FsWatch::spawn_watcher(tmp.path())
.expect("watcher must start cleanly with nested noise dirs present");
for _ in 0..30 {
while rx.try_recv().is_ok() {}
std::thread::sleep(std::time::Duration::from_millis(10));
}
for i in 0..50 {
std::fs::write(node_modules.join(format!("pkg_{i}.js")), b"x").unwrap();
std::fs::write(git.join(format!("obj_{i}")), b"x").unwrap();
}
std::thread::sleep(std::time::Duration::from_millis(400));
let mut noise_events: Vec<std::path::PathBuf> = Vec::new();
while let Ok(batch) = rx.try_recv() {
for ev in batch.unwrap_or_default() {
for path in &ev.event.paths {
if path.starts_with(&node_modules) || path.starts_with(&git) {
noise_events.push(path.clone());
}
}
}
}
assert!(
noise_events.is_empty(),
"writes under a repo's nested node_modules/ and .git/ must not produce \
debouncer events even when the repo is itself a subdir of the root; got {noise_events:?}"
);
std::fs::write(src.join("a.rs"), b"fn main() {}").unwrap();
let started = std::time::Instant::now();
let mut signal_events: Vec<std::path::PathBuf> = Vec::new();
while started.elapsed() < std::time::Duration::from_millis(1500) {
while let Ok(batch) = rx.try_recv() {
for ev in batch.unwrap_or_default() {
for path in &ev.event.paths {
if path.starts_with(&src) {
signal_events.push(path.clone());
}
}
}
}
if !signal_events.is_empty() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(
!signal_events.is_empty(),
"writes under a nested repo/src/ must still produce events after the depth-aware split"
);
}
// Regression for the two-cores-pegged fan storm: on macOS a "non-recursive"
// FSEvents watch is still a fully recursive stream rooted at the path, so any
// watch target that is an ancestor of a noise dir (target/, node_modules/,
// .git/) re-streams that dir's entire build churn into the fsevents callback
// even though notify discards it before the debouncer. The earlier
// boundary-watch fix left exactly such ancestor watches (on the workspace root
// and on each repo dir) and its tests only checked debouncer events, never the
// callback cost — so the burn shipped. The invariant the watcher MUST hold:
// no installed watch target is an ancestor of any noise dir.
// A parent-of-repos root (e.g. ~/Documents with ~40 repos) holds 100k+
// non-noise dirs. Walking all of them to prove they're noise-free costs
// seconds on the watcher thread and yields thousands of FSEvents watches. The
// walk MUST stop once it has spent its dir-visit budget and let the adaptive
// poll cover the rest, rather than scan the whole tree.
#[cfg(target_os = "macos")]
#[test]
fn macos_watch_walk_stops_when_the_dir_budget_is_spent() {
let tmp = tempfile::tempdir().unwrap();
// A dirty root (has .git) so its clean children are collected individually
// instead of the whole root being watched as one clean subtree.
std::fs::create_dir_all(tmp.path().join(".git")).unwrap();
for i in 0..300 {
std::fs::create_dir_all(tmp.path().join(format!("d{i}/sub"))).unwrap();
}
let mut targets: Vec<(std::path::PathBuf, notify::RecursiveMode)> = Vec::new();
let mut budget = 50usize; // far fewer than the ~600 dirs present
super::fs_watch::collect_macos_watch_targets(tmp.path(), tmp.path(), &mut targets, &mut budget);
assert_eq!(
budget, 0,
"the walk must spend its whole budget and stop, not visit every dir"
);
assert!(
targets.len() < 300,
"once the budget caps, not every clean subtree is watched (the poll covers the rest); got {}",
targets.len()
);
}
#[cfg(target_os = "macos")]
#[test]
fn macos_watch_targets_never_root_a_stream_above_a_noise_dir() {
use crate::widgets::file_finder::is_noise_dir;
// A parent-of-repos layout (~/Documents-shaped): root has no top-level
// noise, but each repo nested under it carries target/, node_modules/, .git.
let tmp = tempfile::tempdir().unwrap();
for repo in ["alpha", "beta"] {
let r = tmp.path().join(repo);
std::fs::create_dir_all(r.join("src/inner")).unwrap();
std::fs::create_dir_all(r.join("target/debug/incremental")).unwrap();
std::fs::create_dir_all(r.join("node_modules/pkg")).unwrap();
std::fs::create_dir_all(r.join(".git/objects")).unwrap();
}
let mut targets: Vec<(std::path::PathBuf, notify::RecursiveMode)> = Vec::new();
let mut budget = usize::MAX; // generous: this small tree is walked in full
super::fs_watch::collect_macos_watch_targets(tmp.path(), tmp.path(), &mut targets, &mut budget);
// No target may contain a noise dir anywhere beneath it (which on macOS
// would put that noise dir inside the target's recursive FSEvents stream).
for (path, _mode) in &targets {
for entry in walkdir_noise(path) {
if let Some(name) = entry.file_name() {
assert!(
!is_noise_dir(name),
"watch target {path:?} roots an FSEvents stream over noise dir {entry:?}; \
cargo/npm build churn there would peg the fsevents callback"
);
}
}
}
// And the clean leaves must still be covered, or external edits go unseen.
assert!(
targets.iter().any(|(p, _)| p.ends_with("alpha/src")
|| p.canonicalize()
.map(|c| c.ends_with("alpha/src"))
.unwrap_or(false)),
"the clean repo subtree (alpha/src) must still be watched; got {targets:?}"
);
}
#[cfg(target_os = "macos")]
fn walkdir_noise(root: &std::path::Path) -> Vec<std::path::PathBuf> {
let mut out = Vec::new();
let mut stack = vec![root.to_path_buf()];
while let Some(dir) = stack.pop() {
let Ok(rd) = std::fs::read_dir(&dir) else {
continue;
};
for entry in rd.filter_map(Result::ok) {
let p = entry.path();
if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
out.push(p.clone());
stack.push(p);
}
}
}
out
}
#[test]
fn drain_fs_events_returns_false_when_nothing_pending() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.fs_watch.disable();
for _ in 0..20 {
let _ = app.drain_fs_events();
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(!app.drain_fs_events(), "no fs events ⇒ no redraw needed");
}
/// How many drain ticks an external filesystem change may take to reach the
/// Explorer: the 200 ms fs-sync invariant, expressed in croft's own work
/// rather than in wall clock (#483). Each tick is one `drain_fs_events` and
/// a 10 ms pause, so twenty ticks is 200 ms of croft's own opportunities to
/// notice the change; a suite that starves this thread for 300 ms between
/// two ticks stretches the clock but not the count. On a quiet machine the
/// change lands in one or two ticks, and the poll fallback alone would land
/// it in about five at `FS_POLL_INTERVAL`'s floor (more once `back_off`
/// widens the interval), so this bound catches a gross regression (a
/// watcher and a poll that both stopped delivering), not drift; the
/// wall-clock figure itself is measured by the `#[ignore]`d serial test
/// below.
const FS_SYNC_TICKS: usize = 20;
#[test]
fn drain_fs_events_returns_true_after_workspace_write() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join(".git")).unwrap();
std::fs::write(tmp.path().join(".gitignore"), "*.txt\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for _ in 0..20 {
let _ = app.drain_fs_events();
std::thread::sleep(std::time::Duration::from_millis(10));
}
let new_file = tmp.path().join("new.txt");
std::fs::write(&new_file, "hi").unwrap();
let mut saw = false;
let mut landed = false;
// Bounded at the invariant itself: every tick past it would give the
// same verdict, so the loop stops where the claim does.
for _ in 1..=FS_SYNC_TICKS {
if app.drain_fs_events() {
saw = true;
}
if app.tree.nodes.iter().any(|n| n.path == new_file) {
landed = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(saw, "workspace write should propagate as a dirty signal");
assert!(
landed,
"created file should appear in Explorer within {FS_SYNC_TICKS} drain ticks (never landed)"
);
}
#[test]
fn drain_fs_events_removes_deleted_root_file_from_tree() {
let tmp = tempfile::tempdir().unwrap();
let doomed = tmp.path().join("doomed.txt");
std::fs::write(&doomed, "bye").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(
app.tree.nodes.iter().any(|n| n.path == doomed),
"precondition: initial tree contains the file"
);
std::fs::remove_file(&doomed).unwrap();
let mut gone = false;
for _ in 1..=FS_SYNC_TICKS {
let _ = app.drain_fs_events();
if !app.tree.nodes.iter().any(|n| n.path == doomed) {
gone = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(
gone,
"deleted file should disappear from Explorer within {FS_SYNC_TICKS} drain ticks (never left)"
);
}
/// The 200 ms invariant as wall clock, for a serial run on a quiet machine
/// (pass `--ignored` with the filter `fs_sync_reflects`). Ignored by default
/// because a full parallel suite is itself the load (#483): the scheduler,
/// not croft, decides whether this thread runs again inside 200 ms while
/// thousands of neighbours spawn shells, so a failure here in that setting
/// says nothing about the watcher. The tick-counted pair above carries the
/// check in the suite; this one measures the invariant itself.
#[test]
#[ignore = "wall clock: run serially on a quiet machine"]
fn fs_sync_reflects_external_changes_within_200ms_wall_clock() {
let tmp = tempfile::tempdir().unwrap();
let doomed = tmp.path().join("doomed.txt");
std::fs::write(&doomed, "bye").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for _ in 0..20 {
let _ = app.drain_fs_events();
std::thread::sleep(std::time::Duration::from_millis(10));
}
let budget = std::time::Duration::from_millis(200);
let new_file = tmp.path().join("new.txt");
std::fs::write(&new_file, "hi").unwrap();
// The budget is checked after every drain as well as before: a drain
// that lands the change past the deadline must still fail, not end the
// loop quietly on the next condition check.
let started = std::time::Instant::now();
while !app.tree.nodes.iter().any(|n| n.path == new_file) {
let _ = app.drain_fs_events();
assert!(
started.elapsed() <= budget,
"created file should appear in Explorer within {budget:?} (deadline passed mid-drain)"
);
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(
started.elapsed() <= budget,
"created file should appear in Explorer within {budget:?} (deadline passed at the last check)"
);
std::fs::remove_file(&doomed).unwrap();
let started = std::time::Instant::now();
while app.tree.nodes.iter().any(|n| n.path == doomed) {
let _ = app.drain_fs_events();
assert!(
started.elapsed() <= budget,
"deleted file should disappear from Explorer within {budget:?} (deadline passed mid-drain)"
);
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(
started.elapsed() <= budget,
"deleted file should disappear from Explorer within {budget:?} (deadline passed at the last check)"
);
}
#[test]
fn drain_fs_events_polling_fallback_refreshes_tree_without_watcher_event() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.fs_watch.disable();
app.fs_watch.clear_dir_mtimes();
app.fs_watch.force_poll_due();
let new_file = tmp.path().join("new.txt");
std::fs::write(&new_file, "hi").unwrap();
assert!(app.drain_fs_events());
assert!(
app.tree.nodes.iter().any(|n| n.path == new_file),
"polling fallback should refresh the tree when no watcher event arrives"
);
}
#[test]
fn drain_fs_events_polling_fallback_reloads_clean_open_file_without_watcher_event() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("open.txt");
std::fs::write(&file, "old\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.sync_open_file_poll_mtime();
app.fs_watch.disable();
app.fs_watch.force_poll_due();
std::fs::write(&file, "new content\n").unwrap();
assert!(app.drain_fs_events());
assert_eq!(app.editor.lines, vec!["new content"]);
assert!(!app.editor.dirty);
}
/// The right cluster is painted over the left paragraph, but the diagnostics
/// hit rect was clipped only to the frame edge — never to where that cluster
/// starts. So on a narrow terminal the cells that visibly read "Ln 1, Col 1"
/// still answered to the diagnostics click and opened PROBLEMS, while the
/// counts they claimed to be were not on screen at all.
#[test]
fn clicking_the_position_readout_does_not_open_problems() {
use ratatui::{Terminal, backend::TestBackend};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// 56 cols: the right cluster (51 cells with its │ dividers) fits, but its
// left edge still lands inside the diagnostics cluster, so the clip below
// is exercised.
let mut term = Terminal::new(TestBackend::new(56, 20)).unwrap();
term.draw(|f| app.render(f)).unwrap();
// Find the status row and the column where the position readout paints.
let buf = term.backend().buffer();
let row = buf.area.height - 1;
let text: String = (0..buf.area.width)
.map(|x| buf[(x, row)].symbol().chars().next().unwrap_or(' '))
.collect();
let ln_col =
text.find("Ln ")
.unwrap_or_else(|| panic!("no position readout in status row {text:?}")) as u16;
// The right cluster begins with " Ln", so its left edge is one cell before.
let rx = ln_col.saturating_sub(1);
assert!(
app.status_diag_rect.right() <= rx,
"the diagnostics hit rect must stop where the right cluster starts \
(rect {:?} reaches {}, cluster starts at {}); row reads {text:?}",
app.status_diag_rect,
app.status_diag_rect.right(),
rx
);
// And concretely: the cells that visibly read "Col 1" must not be a
// diagnostics target.
let col_at = text.find("Col ").unwrap() as u16;
assert!(
!rect_contains(app.status_diag_rect, col_at, row),
"clicking the column readout opened PROBLEMS"
);
}
/// Inactive split groups render their editors, so their git gutters paint from
/// whatever baseline they hold. `sync_git_gutters` fetched baselines for the
/// ACTIVE group only, so a tab in the other pane painted bars against nothing
/// (or, after a commit, against a baseline that HEAD had moved past) and never
/// self-corrected: focusing it makes `git_baseline_for == path`, so the fetch
/// is skipped from then on.
#[test]
fn git_gutter_baselines_are_fetched_for_inactive_split_groups() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for args in [
vec!["init", "-q", "-b", "main"],
vec!["config", "user.email", "a@b"],
vec!["config", "user.name", "a"],
] {
let _ = std::process::Command::new("git")
.arg("-C")
.arg(root)
.args(&args)
.status();
}
let f = root.join("seed.txt");
std::fs::write(&f, "one\ntwo\n").unwrap();
for args in [vec!["add", "."], vec!["commit", "-m", "init", "--quiet"]] {
let _ = std::process::Command::new("git")
.arg("-C")
.arg(root)
.args(&args)
.status();
}
let mut app = App::new(root.to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.split_editor(); // both groups now hold seed.txt; right is focused
app.sync_git_gutters();
let inactive_baselines: Vec<Option<std::path::PathBuf>> = app
.editor_layout
.inactive_groups()
.into_iter()
.flat_map(|g| g.editors.iter())
.filter(|e| e.path.as_deref() == Some(f.as_path()))
.map(|e| e.git_baseline_for.clone())
.collect();
assert!(
!inactive_baselines.is_empty(),
"the inactive group holds a tab on seed.txt"
);
for baseline in inactive_baselines {
assert_eq!(
baseline.as_deref(),
Some(f.as_path()),
"a tab in an inactive split group needs its git baseline too"
);
}
}
/// "Reopen with Encoding" re-reads the file from disk over the buffer AND
/// clears both history stacks, so unsaved work was gone with no confirmation
/// and no way back through Cmd+Z. The status-bar encoding segment is a newly
/// clickable target sitting a few cells from the Ln/Col readout, so this is
/// easy to hit by accident — including by picking the encoding already in use,
/// which otherwise looks like a no-op.
#[test]
fn reopen_with_encoding_refuses_to_discard_unsaved_edits() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("notes.txt");
std::fs::write(&f, "keep me\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.editor.cursor_col = 0;
app.editor.insert_char('X');
assert!(app.editor.dirty, "the buffer has unsaved work");
app.dispatch_menu_action(
MenuAction::SetEncoding(encoding_rs::UTF_8),
tmp.path().to_path_buf(),
);
assert!(
app.editor.lines[0].starts_with('X'),
"the unsaved edit must survive, got {:?}",
app.editor.lines[0]
);
assert!(app.editor.dirty, "and the buffer is still dirty");
let msg = app.status.to_lowercase();
assert!(
msg.contains("undo"),
"the refusal must point at the non-destructive route, got {:?}",
app.status
);
// Never "save first": the buffer may be showing mojibake from a wrong
// decode, and saving writes those replacement chars over the real bytes.
assert!(
!msg.contains("save the file first") && !msg.contains("save first"),
"must not advise the destructive route, got {:?}",
app.status
);
}
/// A boundary dir (any repo root: it holds `.git`) gets NO FSEvents watch on
/// macOS, by the iron law that keeps the build-churn storm dead. An in-place
/// write does not move the parent dir's mtime either, so for a file sitting
/// directly in one, the poll's per-file stat is the ONLY thing that can notice
/// a change — and it tracked the ACTIVE tab alone, leaving a background tab on
/// stale text indefinitely.
#[test]
fn the_poll_notices_a_background_tab_whose_file_changed_in_place() {
let tmp = tempfile::tempdir().unwrap();
let bg = tmp.path().join("bg.txt");
let front = tmp.path().join("front.txt");
std::fs::write(&bg, "old\n").unwrap();
std::fs::write(&front, "front\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&bg).unwrap();
app.editor.open_pinned(&front).unwrap(); // front.txt is now the active tab
app.sync_open_file_poll_mtime();
app.fs_watch.disable();
// Baseline the dir mtimes so the sweep cannot be driven by `dirs_changed`.
app.fs_watch.force_poll_due();
let _ = app.drain_fs_events();
// Rewrite the BACKGROUND file in place: same directory entry, so the dir's
// own mtime does not move.
std::fs::write(&bg, "new content\n").unwrap();
app.fs_watch.force_poll_due();
let _ = app.drain_fs_events();
let reloaded = app
.editor
.editors
.iter()
.find(|e| e.path.as_deref() == Some(bg.as_path()))
.expect("the background tab is still open")
.lines
.clone();
assert_eq!(
reloaded,
vec!["new content"],
"a background tab must pick up an in-place external write"
);
}
/// The external-change sweep has to reach every editor GROUP, not just the
/// focused one. The poll stats each open tab exactly once and re-baselines its
/// stamp, so a change it reports and the sweep then misses is burned: no later
/// tick sees it again and the split pane keeps stale text forever.
#[test]
fn an_external_write_reloads_a_tab_in_an_inactive_split_group() {
let tmp = tempfile::tempdir().unwrap();
let side = tmp.path().join("side.txt");
let front = tmp.path().join("front.txt");
std::fs::write(&side, "old\n").unwrap();
std::fs::write(&front, "front\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&side).unwrap();
app.split_editor(); // side.txt is now open in BOTH groups; right is focused
app.editor.open_pinned(&front).unwrap(); // focused group moves to front.txt
app.sync_open_file_poll_mtime();
app.fs_watch.disable();
app.fs_watch.force_poll_due();
let _ = app.drain_fs_events();
std::fs::write(&side, "new content\n").unwrap();
app.fs_watch.force_poll_due();
let _ = app.drain_fs_events();
let stale: Vec<String> = app
.editor_layout
.inactive_groups()
.into_iter()
.flat_map(|g| g.editors.iter())
.filter(|e| e.path.as_deref() == Some(side.as_path()))
.map(|e| e.lines.join("\n"))
.collect();
assert!(
!stale.is_empty(),
"the inactive group still holds a tab on side.txt"
);
for text in stale {
assert_eq!(
text, "new content",
"a tab in an inactive split group must reload too"
);
}
}
/// Watcher backends on Linux fire `Access(...)` events when croft (or any
/// other process) reads the open file — the inotify subsystem does not
/// distinguish a benign read from a real content change. Treating those
/// as "external change" reloads the editor, which clears `selection` and
/// kills any in-flight Cmd+A / mouse-drag / Shift+Right gesture. The
/// reload must only fire for events that mutate content.
#[test]
fn drain_fs_events_preserves_editor_selection_on_access_only_event() {
use notify::Event as NotifyEvent;
use notify::event::{AccessKind, AccessMode, EventKind};
use notify_debouncer_full::DebouncedEvent;
use std::sync::mpsc;
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("readme.md");
std::fs::write(&file, "hello world\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.editor.select_all();
assert!(
app.editor.selection.is_some(),
"precondition: selection set after select_all"
);
let (tx, rx) = mpsc::channel();
app.fs_watch.set_test_events(rx);
app.sync_open_file_poll_mtime();
let access_event = NotifyEvent::new(EventKind::Access(AccessKind::Open(AccessMode::Read)))
.add_path(file.clone());
tx.send(Ok(vec![DebouncedEvent::new(
access_event,
std::time::Instant::now(),
)]))
.unwrap();
app.drain_fs_events();
assert!(
app.editor.selection.is_some(),
"Access(Read) on the open file must not clobber editor selection"
);
}
/// Same class of spurious wake-up as the Access event, via the other
/// notify branch: `chmod`, `touch -a`, ownership changes, and xattr
/// updates surface as `Modify(Metadata(_))`. None mutate file content,
/// so none should trigger an editor reload that wipes selection.
#[test]
fn drain_fs_events_preserves_editor_selection_on_metadata_event() {
use notify::Event as NotifyEvent;
use notify::event::{EventKind, MetadataKind, ModifyKind};
use notify_debouncer_full::DebouncedEvent;
use std::sync::mpsc;
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("readme.md");
std::fs::write(&file, "hello world\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.editor.select_all();
let (tx, rx) = mpsc::channel();
app.fs_watch.set_test_events(rx);
app.sync_open_file_poll_mtime();
let metadata_event = NotifyEvent::new(EventKind::Modify(ModifyKind::Metadata(
MetadataKind::AccessTime,
)))
.add_path(file.clone());
tx.send(Ok(vec![DebouncedEvent::new(
metadata_event,
std::time::Instant::now(),
)]))
.unwrap();
app.drain_fs_events();
assert!(
app.editor.selection.is_some(),
"Modify(Metadata(AccessTime)) on the open file must not clobber editor selection"
);
}
/// Companion to the access-event test: a real content change still has to
/// trigger the reload, otherwise external edits would never refresh the
/// buffer. Guards against an over-broad fix that drops legitimate events.
#[test]
fn drain_fs_events_reloads_on_modify_data_event() {
use notify::Event as NotifyEvent;
use notify::event::{DataChange, EventKind, ModifyKind};
use notify_debouncer_full::DebouncedEvent;
use std::sync::mpsc;
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("readme.md");
std::fs::write(&file, "old\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
let (tx, rx) = mpsc::channel();
app.fs_watch.set_test_events(rx);
app.sync_open_file_poll_mtime();
std::fs::write(&file, "new content\n").unwrap();
let modify_event = NotifyEvent::new(EventKind::Modify(ModifyKind::Data(DataChange::Content)))
.add_path(file.clone());
tx.send(Ok(vec![DebouncedEvent::new(
modify_event,
std::time::Instant::now(),
)]))
.unwrap();
app.drain_fs_events();
assert_eq!(app.editor.lines, vec!["new content"]);
}
/// The reported bug: a file open in a NON-active tab changed on disk and the
/// tab never reloaded, so it looked like another project's content had leaked
/// in. FS sync must cover every open tab, not just the focused one.
#[test]
fn drain_fs_events_reloads_background_tab_on_external_change() {
use notify::Event as NotifyEvent;
use notify::event::{DataChange, EventKind, ModifyKind};
use notify_debouncer_full::DebouncedEvent;
use std::sync::mpsc;
let tmp = tempfile::tempdir().unwrap();
let bg = tmp.path().join("background.txt");
let fg = tmp.path().join("foreground.txt");
std::fs::write(&bg, "bg old\n").unwrap();
std::fs::write(&fg, "fg old\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&bg).unwrap(); // background tab
app.editor.open_pinned(&fg).unwrap(); // active tab
let (tx, rx) = mpsc::channel();
app.fs_watch.set_test_events(rx);
app.sync_open_file_poll_mtime();
std::fs::write(&bg, "bg NEW\n").unwrap();
let ev = NotifyEvent::new(EventKind::Modify(ModifyKind::Data(DataChange::Content)))
.add_path(bg.clone());
tx.send(Ok(vec![DebouncedEvent::new(ev, std::time::Instant::now())]))
.unwrap();
app.drain_fs_events();
let bg_tab = app
.editor
.iter_tabs()
.find(|e| e.path.as_deref() == Some(bg.as_path()))
.unwrap();
assert_eq!(
bg_tab.lines,
vec!["bg NEW"],
"a background tab must reload when its file changes on disk"
);
assert_eq!(app.editor.lines, vec!["fg old"], "active tab untouched");
}
#[test]
fn rect_contains_basic() {
let r = Rect {
x: 5,
y: 5,
width: 10,
height: 10,
};
assert!(rect_contains(r, 5, 5));
assert!(rect_contains(r, 14, 14));
assert!(!rect_contains(r, 4, 5));
assert!(!rect_contains(r, 15, 5));
assert!(!rect_contains(r, 5, 15));
}
#[test]
fn rect_contains_zero_sized_is_empty() {
let r = Rect {
x: 0,
y: 0,
width: 0,
height: 0,
};
assert!(!rect_contains(r, 0, 0));
}
fn note_fixture(
kind: crate::release_notes::NoteKind,
summary: &'static str,
) -> crate::release_notes::ReleaseNote {
crate::release_notes::ReleaseNote { kind, summary }
}
#[test]
fn welcome_note_summary_wraps_long_lines() {
let n = note_fixture(
crate::release_notes::NoteKind::Feature,
"Code Actions and Quick Fix on Cmd+., aggregated across every running language server in the workspace",
);
let lines = wrapped_welcome_note_summary(&n, 42);
assert!(lines.len() > 1, "long highlight summaries should wrap");
for line in &lines {
assert!(line.chars().count() <= welcome_note_summary_width(42) as usize);
}
}
#[test]
fn welcome_recents_height_accounts_for_wrapped_note_rows() {
let n = note_fixture(
crate::release_notes::NoteKind::Fix,
"A reasonably long highlight summary that will certainly wrap to more than a single line in a narrow column",
);
let h = welcome_recents_height(&[n], 42);
// header + blank + at least two wrapped rows.
assert!(
h > 1 + 1 + 1,
"height must include wrapped continuation rows; got {h}"
);
}
#[test]
fn lerp_rgb_hits_endpoints_exactly() {
let a = (10u8, 20, 30);
let b = (100u8, 200, 250);
assert_eq!(lerp_rgb(a, b, 0.0), a);
assert_eq!(lerp_rgb(a, b, 1.0), b);
let mid = lerp_rgb(a, b, 0.5);
assert!(mid.0 > a.0 && mid.0 < b.0);
}
#[test]
fn paint_gradient_box_skips_when_rect_runs_off_buffer() {
// The panic that motivated the bounds clip: an 80x25 buffer asked
// to render a tall recents box that extended past row 25.
let buf_area = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
let mut buf = ratatui::buffer::Buffer::empty(buf_area);
let oversized = Rect {
x: 0,
y: 0,
width: 80,
height: 60,
};
// Must not panic; the no-op clip is the contract.
paint_gradient_box(&mut buf, oversized);
let off_top_left = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
// Sanity: a fitting rect still draws.
paint_gradient_box(&mut buf, off_top_left);
assert_eq!(buf[(0, 0)].symbol(), "\u{256d}");
}
#[test]
fn clicking_an_scm_entry_below_a_stale_tree_last_area_still_selects_and_opens() {
// User report: after the Source Control list got long enough to
// reach below where the file tree had last rendered, the rows in
// that lower band became unclickable. Root cause: the mouse
// handler gated all sidebar-view click branches on `rect_contains
// (self.tree.last_area, ...)`, but `tree.last_area` is only
// refreshed when the Explorer view renders — switching to
// Source Control freezes that rectangle, and any click below
// its bottom edge fell through even though it was inside the
// SCM panel.
use crate::git::{ChangeEntry, ChangeKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Pretend the Explorer view rendered into a tall pane; then the
// user opened the terminal which shrank the side area; then they
// switched to Source Control. Set tree.last_area to the OLD,
// taller rectangle so we can prove the SCM click-handler is no
// longer dependent on it.
app.tree.last_area = Rect {
x: 4,
y: 1,
width: 30,
height: 6,
};
app.set_sidebar_view(SidebarView::SourceControl);
// Set entries AFTER set_sidebar_view because that path calls
// refresh_source_control which overwrites entries with the live
// git query (empty in a non-repo temp dir).
app.source_control.status.in_repo = true;
app.source_control.status.branch = Some("main".into());
app.source_control.entries = (0..15)
.map(|i| ChangeEntry {
path: format!("file{i}.py"),
kind: ChangeKind::Untracked,
..Default::default()
})
.collect();
let backend = ratatui::backend::TestBackend::new(80, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
// Pick the y of a row that lives BELOW tree.last_area's bottom
// but inside the SCM list. Walk the rendered list area to find
// one.
let stale_bottom = app.tree.last_area.y + app.tree.last_area.height;
let list_area = app.source_control.last_list_area;
assert!(
list_area.y + list_area.height > stale_bottom,
"test setup must put SCM rows below the stale tree.last_area"
);
// Walk from stale_bottom down looking for a row that maps to an
// entry (skip section-header rows).
let target_row = (stale_bottom..list_area.y + list_area.height)
.find(|y| app.source_control.entry_at_y(*y).is_some())
.expect("at least one entry must render below the stale tree band");
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: list_area.x + 4,
row: target_row,
modifiers: KeyModifiers::NONE,
});
assert!(
app.source_control.selected_change.is_some(),
"click on an SCM entry below the stale tree.last_area must still select it"
);
}
#[test]
fn click_on_a_deleted_source_control_entry_opens_unified_diff_with_head_lines_all_removed() {
// A file that's tracked in HEAD but missing from the working
// tree (or staged for deletion) used to leave the editor empty
// when clicked, because `open_source_control_entry` fell into
// the generic open-from-disk branch and the path doesn't exist
// any more. New behaviour: clicking the row opens a one-pane
// unified diff that paints every line of the HEAD blob as a
// removed line — visually identical to `git diff` for a deletion.
use crate::git::{ChangeEntry, ChangeKind};
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let init = std::process::Command::new("git")
.args(["init", "-q", "-b", "main"])
.current_dir(root)
.status()
.unwrap();
assert!(init.success());
let _ = std::process::Command::new("git")
.args(["config", "user.email", "t@t"])
.current_dir(root)
.status();
let _ = std::process::Command::new("git")
.args(["config", "user.name", "t"])
.current_dir(root)
.status();
let f = root.join("doomed.txt");
std::fs::write(&f, b"alpha\nbeta\ngamma\n").unwrap();
let _ = std::process::Command::new("git")
.args(["add", "doomed.txt"])
.current_dir(root)
.status();
let _ = std::process::Command::new("git")
.args(["commit", "-q", "-m", "seed"])
.current_dir(root)
.status();
// Delete in the working tree but leave it tracked in HEAD/index
// — that's exactly the `Deleted` (unstaged) state.
std::fs::remove_file(&f).unwrap();
let mut app = App::new(root.to_path_buf()).unwrap();
app.source_control.entries = vec![ChangeEntry {
path: "doomed.txt".into(),
kind: ChangeKind::Deleted,
..Default::default()
}];
app.set_sidebar_view(SidebarView::SourceControl);
app.open_source_control_entry(0);
let diff = app
.editor
.diff
.as_ref()
.expect("clicking a Deleted entry must open a diff view, not a blank tab");
assert!(
diff.unified,
"the deletion view must be the single-column unified flavour, not side-by-side"
);
assert_eq!(diff.left_lines, vec!["alpha", "beta", "gamma"]);
assert!(
diff.rows
.iter()
.all(|r| matches!(r, crate::widgets::diff::DiffRow::Removed { .. })),
"every visible row must be Removed so the whole pane paints red"
);
}
#[test]
fn click_on_a_modified_source_control_entry_opens_a_diff_view_against_head() {
// VS Code surfaces the diff between the working-tree file and
// the HEAD version when the user clicks a Modified entry in the
// Source Control panel. Croft used to just open the working
// file as plain text — assert the new behaviour: the active
// editor tab carries a `diff: Some(...)` payload.
use crate::git::{ChangeEntry, ChangeKind};
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
// Init a real repo so git show HEAD:<path> returns content.
let init = std::process::Command::new("git")
.args(["init", "-q", "-b", "main"])
.current_dir(root)
.status()
.unwrap();
assert!(init.success());
let _ = std::process::Command::new("git")
.args(["config", "user.email", "t@t"])
.current_dir(root)
.status();
let _ = std::process::Command::new("git")
.args(["config", "user.name", "t"])
.current_dir(root)
.status();
let f = root.join("a.py");
std::fs::write(&f, b"print(1)\n").unwrap();
let _ = std::process::Command::new("git")
.args(["add", "a.py"])
.current_dir(root)
.status();
let _ = std::process::Command::new("git")
.args(["commit", "-q", "-m", "init"])
.current_dir(root)
.status();
std::fs::write(&f, b"print(2)\n").unwrap();
let mut app = App::new(root.to_path_buf()).unwrap();
app.source_control.entries = vec![ChangeEntry {
path: "a.py".into(),
kind: ChangeKind::Modified,
..Default::default()
}];
app.set_sidebar_view(SidebarView::SourceControl);
app.open_source_control_entry(0);
assert!(
app.editor.diff.is_some(),
"clicking a Modified entry must open the editor in diff-vs-HEAD mode, not as plain text"
);
}
/// Shared ritual for the hunk-staging tests: a real repo whose committed
/// 20-line file has been edited at line 2 and line 18, so the working
/// tree carries two well-separated hunks, opened as an SCM diff.
fn scm_two_hunk_app() -> (tempfile::TempDir, App) {
use crate::git::{ChangeEntry, ChangeKind};
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let git = |args: &[&str]| {
let ok = std::process::Command::new("git")
.args(args)
.current_dir(root)
.output()
.unwrap()
.status
.success();
assert!(ok, "git {args:?} failed");
};
git(&["init", "-q", "-b", "main"]);
git(&["config", "user.email", "t@t"]);
git(&["config", "user.name", "t"]);
let original: String = (1..=20).map(|i| format!("line{i}\n")).collect();
std::fs::write(root.join("f.txt"), original).unwrap();
git(&["add", "f.txt"]);
git(&["commit", "-q", "-m", "init"]);
let mut edited: Vec<String> = (1..=20).map(|i| format!("line{i}")).collect();
edited[1] = "LINE2".into();
edited[17] = "LINE18".into();
std::fs::write(root.join("f.txt"), edited.join("\n") + "\n").unwrap();
let mut app = App::new(root.to_path_buf()).unwrap();
app.source_control.entries = vec![ChangeEntry {
path: "f.txt".into(),
kind: ChangeKind::Modified,
..Default::default()
}];
app.set_sidebar_view(SidebarView::SourceControl);
app.open_source_control_entry(0);
assert!(app.editor.diff.is_some(), "the SCM diff must be open");
(tmp, app)
}
fn git_stdout_in(root: &std::path::Path, args: &[&str]) -> String {
let out = std::process::Command::new("git")
.args(args)
.current_dir(root)
.output()
.unwrap();
String::from_utf8_lossy(&out.stdout).to_string()
}
#[test]
fn pressing_s_in_a_scm_diff_stages_only_the_hunk_under_the_caret() {
let (tmp, mut app) = scm_two_hunk_app();
// Caret on the first hunk (row 1 = the line2 edit).
app.editor
.diff
.as_mut()
.unwrap()
.start_selection(crate::widgets::diff::DiffSide::Right, 1, 0);
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
let staged = git_stdout_in(tmp.path(), &["diff", "--cached"]);
assert!(
staged.contains("+LINE2"),
"hunk 1 must land in the index: {staged}"
);
assert!(
!staged.contains("LINE18"),
"hunk 2 must stay unstaged: {staged}"
);
let unstaged = git_stdout_in(tmp.path(), &["diff"]);
assert!(
unstaged.contains("+LINE18"),
"hunk 2 must remain a working-tree change: {unstaged}"
);
}
#[test]
fn pressing_s_with_no_caret_stages_the_first_visible_hunk() {
// Right after opening, the diff parks the first hunk in view; with no
// click yet, S must act on that hunk, not silently no-op.
let (tmp, mut app) = scm_two_hunk_app();
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
let staged = git_stdout_in(tmp.path(), &["diff", "--cached"]);
assert!(
staged.contains("+LINE2") && !staged.contains("LINE18"),
"the first hunk is the default target: {staged}"
);
}
#[test]
fn pressing_u_in_a_scm_diff_unstages_only_the_hunk_under_the_caret() {
let (tmp, mut app) = scm_two_hunk_app();
let ok = std::process::Command::new("git")
.args(["add", "f.txt"])
.current_dir(tmp.path())
.output()
.unwrap()
.status
.success();
assert!(ok);
app.editor
.diff
.as_mut()
.unwrap()
.start_selection(crate::widgets::diff::DiffSide::Right, 1, 0);
app.handle_key(key(KeyCode::Char('u'), KeyModifiers::NONE))
.unwrap();
let staged = git_stdout_in(tmp.path(), &["diff", "--cached"]);
assert!(
!staged.contains("LINE2"),
"hunk 1 must leave the index: {staged}"
);
assert!(
staged.contains("+LINE18"),
"hunk 2 must stay staged: {staged}"
);
}
#[test]
fn pressing_r_in_a_scm_diff_confirms_then_reverts_only_that_hunk() {
let (tmp, mut app) = scm_two_hunk_app();
app.editor
.diff
.as_mut()
.unwrap()
.start_selection(crate::widgets::diff::DiffSide::Right, 1, 0);
app.handle_key(key(KeyCode::Char('r'), KeyModifiers::NONE))
.unwrap();
// Destructive: nothing may change until the confirm.
let before = std::fs::read_to_string(tmp.path().join("f.txt")).unwrap();
assert!(
before.contains("LINE2"),
"revert must wait for the confirm popup"
);
app.handle_key(key(KeyCode::Char('y'), KeyModifiers::NONE))
.unwrap();
let after = std::fs::read_to_string(tmp.path().join("f.txt")).unwrap();
assert!(
after.contains("line2") && !after.contains("LINE2"),
"hunk 1 must be reverted: {after}"
);
assert!(
after.contains("LINE18"),
"hunk 2 must survive the revert: {after}"
);
}
#[test]
fn revert_hunk_confirm_cancels_on_n() {
let (tmp, mut app) = scm_two_hunk_app();
app.handle_key(key(KeyCode::Char('r'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('n'), KeyModifiers::NONE))
.unwrap();
let content = std::fs::read_to_string(tmp.path().join("f.txt")).unwrap();
assert!(
content.contains("LINE2") && content.contains("LINE18"),
"Esc/N must leave the working tree untouched"
);
}
/// The user dislikes underlined text in the welcome panel: it adds visual
/// noise. Assert the rendered buffer contains zero cells with the UNDERLINED
/// modifier so this preference is enforced by the test suite.
#[test]
fn welcome_panel_renders_without_any_underlined_cells() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.welcome.set_test_notes(vec![
note_fixture(crate::release_notes::NoteKind::Feature, "Did a new thing"),
note_fixture(crate::release_notes::NoteKind::Fix, "Fixed an old thing"),
]);
let area = Rect {
x: 0,
y: 0,
width: 120,
height: 30,
};
let backend = ratatui::backend::TestBackend::new(area.width, area.height);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render_welcome(f, area)).unwrap();
let buffer = term.backend().buffer();
for y in 0..area.height {
for x in 0..area.width {
let cell = &buffer[(x, y)];
assert!(
!cell.modifier.contains(Modifier::UNDERLINED),
"cell at ({x}, {y}) symbol={:?} has UNDERLINED set; the welcome panel must render no underlines",
cell.symbol()
);
}
}
}
#[test]
fn welcome_panel_does_not_paint_the_blazingly_fast_slogan_footer() {
// The user asked to drop the chevron-bracketed
// "Blazingly fast by design. Secure by default. Loved by developers."
// line. Render the welcome panel into a buffer and confirm none
// of the slogan fragments appear anywhere on the canvas.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let area = Rect {
x: 0,
y: 0,
width: 120,
height: 40,
};
let backend = ratatui::backend::TestBackend::new(area.width, area.height);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render_welcome(f, area)).unwrap();
let buffer = term.backend().buffer();
for y in 0..area.height {
let mut row = String::new();
for x in 0..area.width {
row.push_str(buffer[(x, y)].symbol());
}
for needle in [
"Blazingly fast by design",
"Secure by default",
"Loved by developers",
] {
assert!(
!row.contains(needle),
"welcome row {y} still carries removed slogan {needle:?}: {row:?}"
);
}
}
}
#[test]
fn render_welcome_does_not_panic_in_default_80x25_with_many_notes() {
// Repro for the index-(41,70) panic at startup: ratatui's initial
// backend size is 80x25 before the alt-screen reflow. With a long
// highlights list the box could compute taller than 25, run past the
// buffer, and panic inside set_string — so clamp to the area.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.welcome.set_test_notes(
(0..40)
.map(|_| {
note_fixture(
crate::release_notes::NoteKind::Feature,
"this is a long highlight summary that will wrap to multiple lines on a narrow column",
)
})
.collect(),
);
let area = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
let backend = ratatui::backend::TestBackend::new(area.width, area.height);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render_welcome(f, area)).unwrap();
}
/// The focused pane's box is drawn in HEAVY glyphs and an unfocused one
/// in light, so which pane owns the keyboard reads from weight and not
/// only from colour (#470). Both weights keep the rounded corners: there
/// is no heavy arc glyph, and the corners are the house look every other
/// caller of the gradient box shares.
#[test]
fn the_gradient_box_comes_in_two_weights() {
use ratatui::buffer::Buffer;
let area = ratatui::layout::Rect {
x: 0,
y: 0,
width: 8,
height: 4,
};
let sym = |b: &Buffer, x: u16, y: u16| b[(x, y)].symbol().to_string();
let mut light = Buffer::empty(area);
crate::gradient::paint_gradient_box(&mut light, area);
let mut heavy = Buffer::empty(area);
crate::gradient::paint_gradient_box_heavy(&mut heavy, area);
// All four edges, not just two: the bug this was written for replaced
// one horizontal edge and left the other light, so a test that reads
// only the top would miss its own inverse.
for (x, y, what) in [(3u16, 0u16, "top"), (3, 3, "bottom")] {
assert_eq!(sym(&light, x, y), "\u{2500}", "light {what} edge");
assert_eq!(sym(&heavy, x, y), "\u{2501}", "heavy {what} edge");
}
for (x, y, what) in [(0u16, 1u16, "left"), (7, 1, "right")] {
assert_eq!(sym(&light, x, y), "\u{2502}", "light {what} edge");
assert_eq!(sym(&heavy, x, y), "\u{2503}", "heavy {what} edge");
}
// The corners are shared, which is what keeps the two boxes the same
// shape rather than two different visual languages.
for (x, y) in [(0, 0), (7, 0), (0, 3), (7, 3)] {
assert_eq!(
sym(&light, x, y),
sym(&heavy, x, y),
"corner ({x},{y}) is the same arc in both weights"
);
}
}
#[test]
fn paint_gradient_box_draws_rounded_corners_with_corner_colours() {
let rect = Rect {
x: 0,
y: 0,
width: 8,
height: 4,
};
let mut buf = ratatui::buffer::Buffer::empty(rect);
paint_gradient_box(&mut buf, rect);
assert_eq!(buf[(0, 0)].symbol(), "\u{256d}", "top-left rounded");
assert_eq!(buf[(7, 0)].symbol(), "\u{256e}", "top-right rounded");
assert_eq!(buf[(0, 3)].symbol(), "\u{2570}", "bottom-left rounded");
assert_eq!(buf[(7, 3)].symbol(), "\u{256f}", "bottom-right rounded");
assert_eq!(buf[(3, 0)].symbol(), "\u{2500}", "top edge horizontal");
assert_eq!(buf[(0, 1)].symbol(), "\u{2502}", "left edge vertical");
// Top-left cell carries the GRAD_TL fg colour exactly.
let tl_fg = buf[(0, 0)].fg;
assert_eq!(tl_fg, rgb_color(GRAD_TL));
let tr_fg = buf[(7, 0)].fg;
assert_eq!(tr_fg, rgb_color(GRAD_TR));
}
#[test]
fn welcome_tagline_constant_is_present() {
assert!(WELCOME_TAGLINE.contains("LIGHTWEIGHT"));
assert!(WELCOME_TAGLINE.contains("BLAZINGLY FAST"));
assert!(WELCOME_TAGLINE.contains("DEVELOPERS"));
}
#[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~");
// Alt alone on Left/Right stays readline's word motion.
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"
);
}
/// DECCKM on: cursor keys switch to the SS3 form; keys outside the cursor
/// group are unaffected.
#[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 ctrl_s_is_save_key() {
assert!(is_save_key(key(KeyCode::Char('s'), KeyModifiers::CONTROL)));
}
#[test]
fn cmd_s_is_save_key() {
assert!(is_save_key(key(KeyCode::Char('s'), KeyModifiers::SUPER)));
}
#[test]
fn cmd_w_and_ctrl_shift_w_close_terminal_but_plain_ctrl_w_does_not() {
// Cmd+W is the primary terminal-close chord; Ctrl+Shift+W stays as a
// legacy fallback.
assert!(is_terminal_close_key(key(
KeyCode::Char('w'),
KeyModifiers::SUPER
)));
assert!(is_terminal_close_key(key(
KeyCode::Char('w'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT
)));
// Plain Ctrl+W must NOT close the terminal: it is the shell's
// delete-word-backward, and hijacking it would break readline editing.
assert!(!is_terminal_close_key(key(
KeyCode::Char('w'),
KeyModifiers::CONTROL
)));
}
#[test]
fn cmd_dot_and_ctrl_dot_are_quick_fix_key() {
// VS Code binds Quick Fix to Cmd+. on macOS (arrives as Char('.')+SUPER via
// the iTerm2/Ghostty CSI-u forwarder) and Ctrl+. on Linux/Termux.
assert!(is_quick_fix_key(key(
KeyCode::Char('.'),
KeyModifiers::SUPER
)));
assert!(is_quick_fix_key(key(
KeyCode::Char('.'),
KeyModifiers::CONTROL
)));
}
#[test]
fn plain_dot_and_modified_dot_are_not_quick_fix_key() {
assert!(!is_quick_fix_key(key(
KeyCode::Char('.'),
KeyModifiers::NONE
)));
// Shift+. is '>' territory and Alt+. is the shell's last-arg; neither is
// Quick Fix.
assert!(!is_quick_fix_key(key(
KeyCode::Char('.'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
assert!(!is_quick_fix_key(key(
KeyCode::Char('.'),
KeyModifiers::ALT
)));
}
#[test]
fn shift_ctrl_s_is_save_key() {
// Some terminals report capital S with Ctrl pressed.
let mods = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
assert!(is_save_key(key(KeyCode::Char('S'), mods)));
}
#[test]
fn plain_s_is_not_save_key() {
assert!(!is_save_key(key(KeyCode::Char('s'), KeyModifiers::NONE)));
}
#[test]
fn ctrl_q_is_not_save_key() {
assert!(!is_save_key(key(KeyCode::Char('q'), KeyModifiers::CONTROL)));
}
#[test]
fn alt_s_is_not_save_key() {
assert!(!is_save_key(key(KeyCode::Char('s'), KeyModifiers::ALT)));
}
#[test]
fn git_status_spans_empty_when_not_in_repo() {
let st = crate::git::GitStatus::default();
let spans = git_status_spans(&st);
assert!(spans.is_empty(), "no git pill outside a git repo");
}
#[test]
fn git_status_spans_clean_branch_is_green() {
// Agnoster convention: clean working tree → green pill.
let st = crate::git::GitStatus {
in_repo: true,
branch: Some("main".into()),
detached_hash: None,
dirty: false,
ahead: 0,
behind: 0,
head_oid: None,
ignored: std::sync::Arc::default(),
repo_root: None,
changed_count: 0,
};
let spans = git_status_spans(&st);
let main_span = spans
.iter()
.find(|s| s.content.contains("main"))
.expect("branch span");
assert_eq!(main_span.style.fg, Some(GIT_CLEAN_COLOR));
}
#[test]
fn git_status_spans_dirty_branch_is_yellow_not_red() {
// Agnoster convention: dirty working tree → yellow/orange pill.
// No red bullet either — colour alone carries the state.
let st = crate::git::GitStatus {
in_repo: true,
branch: Some("main".into()),
detached_hash: None,
dirty: true,
ahead: 0,
behind: 0,
head_oid: None,
ignored: std::sync::Arc::default(),
repo_root: None,
changed_count: 0,
};
let spans = git_status_spans(&st);
let joined: String = spans.iter().map(|s| s.content.as_ref()).collect();
assert!(
!joined.contains('●'),
"no red bullet — colour signals dirtiness"
);
let main_span = spans
.iter()
.find(|s| s.content.contains("main"))
.expect("branch span");
assert_eq!(main_span.style.fg, Some(GIT_DIRTY_COLOR));
}
#[test]
fn git_status_spans_renders_detached_hash_when_no_branch() {
let st = crate::git::GitStatus {
in_repo: true,
branch: None,
detached_hash: Some("abc1234".into()),
dirty: false,
ahead: 0,
behind: 0,
head_oid: None,
ignored: std::sync::Arc::default(),
repo_root: None,
changed_count: 0,
};
let spans = git_status_spans(&st);
let joined: String = spans.iter().map(|s| s.content.as_ref()).collect();
assert!(joined.contains("abc1234"));
}
#[test]
fn git_status_spans_renders_ahead_behind_counts() {
let st = crate::git::GitStatus {
in_repo: true,
branch: Some("main".into()),
detached_hash: None,
dirty: false,
ahead: 2,
behind: 1,
head_oid: None,
ignored: std::sync::Arc::default(),
repo_root: None,
changed_count: 0,
};
let spans = git_status_spans(&st);
let joined: String = spans.iter().map(|s| s.content.as_ref()).collect();
assert!(joined.contains("↑2"));
assert!(joined.contains("↓1"));
}
#[test]
fn ctrl_shift_f_jumps_to_search() {
let mods = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
assert!(is_search_jump_key(key(KeyCode::Char('F'), mods)));
}
#[test]
fn cmd_shift_f_jumps_to_search() {
let mods = KeyModifiers::SUPER | KeyModifiers::SHIFT;
assert!(is_search_jump_key(key(KeyCode::Char('F'), mods)));
}
#[test]
fn plain_f_does_not_jump_to_search() {
assert!(!is_search_jump_key(key(
KeyCode::Char('f'),
KeyModifiers::NONE
)));
}
#[test]
fn ctrl_c_is_editor_copy_key() {
assert!(is_editor_copy_key(key(
KeyCode::Char('c'),
KeyModifiers::CONTROL
)));
}
#[test]
fn cmd_c_is_editor_copy_key() {
assert!(is_editor_copy_key(key(
KeyCode::Char('c'),
KeyModifiers::SUPER
)));
}
#[test]
fn plain_c_is_not_editor_copy_key() {
assert!(!is_editor_copy_key(key(
KeyCode::Char('c'),
KeyModifiers::NONE
)));
}
#[test]
fn ctrl_x_is_editor_cut_key() {
assert!(is_editor_cut_key(key(
KeyCode::Char('x'),
KeyModifiers::CONTROL
)));
assert!(is_editor_cut_key(key(
KeyCode::Char('x'),
KeyModifiers::SUPER
)));
assert!(!is_editor_cut_key(key(
KeyCode::Char('x'),
KeyModifiers::NONE
)));
}
#[test]
fn ctrl_a_is_editor_select_all_key() {
assert!(is_editor_select_all_key(key(
KeyCode::Char('a'),
KeyModifiers::CONTROL
)));
assert!(is_editor_select_all_key(key(
KeyCode::Char('a'),
KeyModifiers::SUPER
)));
assert!(!is_editor_select_all_key(key(
KeyCode::Char('a'),
KeyModifiers::NONE
)));
}
#[test]
fn ctrl_z_is_editor_undo_key() {
assert!(is_editor_undo_key(key(
KeyCode::Char('z'),
KeyModifiers::CONTROL
)));
assert!(is_editor_undo_key(key(
KeyCode::Char('z'),
KeyModifiers::SUPER
)));
}
#[test]
fn plain_z_is_not_editor_undo_key() {
assert!(!is_editor_undo_key(key(
KeyCode::Char('z'),
KeyModifiers::NONE
)));
}
#[test]
fn shift_cmd_z_reserved_for_redo_not_undo() {
let mods = KeyModifiers::SUPER | KeyModifiers::SHIFT;
assert!(!is_editor_undo_key(key(KeyCode::Char('z'), mods)));
// The shifted chord is redo (both Cmd and Ctrl surfaces), and the plain
// command-modifier Z stays undo, not redo.
assert!(is_editor_redo_key(key(KeyCode::Char('z'), mods)));
assert!(is_editor_redo_key(key(
KeyCode::Char('z'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT
)));
assert!(!is_editor_redo_key(key(
KeyCode::Char('z'),
KeyModifiers::SUPER
)));
assert!(!is_editor_redo_key(key(
KeyCode::Char('z'),
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() {
// For terminals that pass Cmd via the kitty protocol; iTerm2 users
// can also remap ⌘C → Send Hex Code 0x03 for terminal-pane copies,
// but for keyboard-protocol-aware terminals we accept Super here.
assert!(is_terminal_copy_key(key(
KeyCode::Char('c'),
KeyModifiers::SUPER
)));
}
#[test]
fn plain_ctrl_c_is_not_terminal_copy() {
// Ctrl+C must remain SIGINT in the embedded shell; it must not be
// intercepted as the croft copy gesture.
assert!(!is_terminal_copy_key(key(
KeyCode::Char('c'),
KeyModifiers::CONTROL
)));
}
/// Cmd+C from the croft terminal pane must land the selection on the
/// real macOS clipboard. This is the user-visible regression test
/// for the long-standing "I copied from croft and pbpaste shows the
/// previous value" bug, where the old OSC 52 path was silently
/// dropped by the host terminal. The contract: writing through
/// `copy_to_clipboard` puts the text on the system pasteboard such
/// that `clipboard::read_string` (which is what Cmd+V uses) returns
/// the same bytes. If this ever fails again, copy/paste between
/// croft and other apps is broken and the test must catch it before
/// the binary ships.
#[cfg(target_os = "macos")]
#[test]
fn copy_to_clipboard_writes_text_to_the_macos_system_pasteboard() {
let _g = crate::clipboard::lock_clipboard_for_test();
let sentinel = format!(
"croft-copy-helper-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
);
let used_native = copy_to_clipboard(&sentinel);
assert!(
used_native,
"on macOS, copy_to_clipboard must succeed via NSPasteboard and return true so the call site can skip the OSC 52 fallback (and the host terminal's quirks can't silently drop the write)"
);
let got = crate::clipboard::read_string().expect("read_string must see what we just wrote");
assert_eq!(
got, sentinel,
"round-trip through the system pasteboard must be byte-exact - if this ever drifts, every Cmd+C from croft is silently lossy"
);
}
/// Tighter regression: a real `App` with a real `PtyTerminal`, a
/// terminal-pane selection, and `App::copy_terminal_selection` must
/// land the text on the macOS system clipboard. Exercises the full
/// wire from PTY bytes → alacritty grid → `selection_text` →
/// `copy_to_clipboard` → `NSPasteboard.setString:forType:` → what
/// `pbpaste` / `NSPasteboard.stringForType:` returns. A refactor
/// that reintroduces an OSC-52-only path in the terminal copy
/// handler would fail this test even if `copy_to_clipboard` itself
/// still resolved to the native path elsewhere.
#[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();
// Render once so `terminal.last_inner` is populated and the
// `start_selection_at` / `extend_selection_to` chord can map
// viewport coordinates to cell coordinates the way the live
// input handler does on a real keystroke.
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);
// Re-render to refresh `last_inner` after the grid has grown.
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 cmd_shift_b_runs_the_projects_build_task_in_a_named_pane() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("Makefile"), "build:\n\ttrue\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let before = app.terminals.len();
app.handle_key(key(
KeyCode::Char('B'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(
app.terminals.len(),
before + 1,
"the build task gets its own pane"
);
assert_eq!(
app.terminals[app.active_terminal].label(),
"Task: make build",
"the pane is named after the task"
);
assert!(app.show_terminal, "the panel reveals");
assert!(
matches!(app.focus, Pane::Terminal),
"focus follows the task"
);
}
#[test]
fn rerunning_a_task_reuses_its_pane_instead_of_stacking_new_ones() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("Makefile"), "build:\n\ttrue\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let chord = key(
KeyCode::Char('B'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
);
app.handle_key(chord).unwrap();
// Wait for the pane's shell to come back to its prompt so the rerun
// path sees an idle pane (a busy pane legitimately gets a new one).
// Load-scaled and LOUD (#397): the fixed 5000ms loop broke out silently
// on timeout, so under suite load the next step met a pane still busy
// and the assertion after it misreported the timeout as its own failure.
crate::test_budget::await_spawned(
crate::test_budget::tests::TASK_PANE_PROMPT_BASE,
"the task pane's shell to return to its prompt",
|| app.terminals[app.active_terminal].foreground_is_shell(),
);
let after_first = app.terminals.len();
app.handle_key(chord).unwrap();
assert_eq!(
app.terminals.len(),
after_first,
"rerunning the same task must reuse its idle pane"
);
assert_eq!(
app.terminals
.iter()
.filter(|t| t.label() == "Task: make build")
.count(),
1,
"exactly one pane carries the task's name"
);
}
#[test]
fn a_reused_task_pane_clears_a_half_typed_prompt_line_first() {
// A shell sitting at its prompt can hold unsubmitted text in the line
// editor; writing the task command raw would concatenate with it (the
// `format_cd_command` test pins the same rule for cd).
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("Makefile"), "build:\n\ttrue\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let chord = key(
KeyCode::Char('B'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
);
app.handle_key(chord).unwrap();
// Load-scaled and LOUD (#397): the fixed 5000ms loop broke out silently
// on timeout, so under suite load the next step met a pane still busy
// and the assertion after it misreported the timeout as its own failure.
crate::test_budget::await_spawned(
crate::test_budget::tests::TASK_PANE_PROMPT_BASE,
"the task pane's shell to return to its prompt",
|| app.terminals[app.active_terminal].foreground_is_shell(),
);
app.handle_key(chord).unwrap();
let bytes = app.terminals[app.active_terminal].written_bytes_for_test();
let needle = b"\x05\x15make build\r";
assert!(
bytes.windows(needle.len()).any(|w| w == needle),
"the reused-pane write must clear the line editor first (Ctrl-E Ctrl-U)"
);
}
#[test]
fn a_task_pane_from_the_old_workspace_is_not_reused_after_a_re_root() {
// The pane's shell still sits in workspace A; running B's build task
// must not execute it there.
let a = tempfile::tempdir().unwrap();
let b = tempfile::tempdir().unwrap();
std::fs::write(a.path().join("Makefile"), "build:\n\ttrue\n").unwrap();
std::fs::write(b.path().join("Makefile"), "build:\n\ttrue\n").unwrap();
let mut app = App::new(a.path().to_path_buf()).unwrap();
let chord = key(
KeyCode::Char('B'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
);
app.handle_key(chord).unwrap();
// Load-scaled and LOUD (#397). The fixed 5000ms loop broke out silently
// on timeout, and here a still-busy pane passes the assertion below for
// the wrong reason: a busy pane always gets a sibling, so `after + 1`
// held without the cwd guard ever being exercised. Failing loudly makes
// the guard the thing under test.
crate::test_budget::await_spawned(
crate::test_budget::tests::TASK_PANE_PROMPT_BASE,
"the task pane's shell to return to its prompt",
|| app.terminals[app.active_terminal].foreground_is_shell(),
);
// Focus another pane so the re-root's active-pane `cd` cannot move the
// task pane along (the reviewer's scenario: it is NOT cd'd).
app.active_terminal = 0;
app.change_workspace_root(b.path().to_path_buf());
assert!(
app.last_task.is_none(),
"Rerun Last Task must not carry a task across a re-root"
);
let after = app.terminals.len();
app.handle_key(chord).unwrap();
assert_eq!(
app.terminals.len(),
after + 1,
"a task pane whose shell still sits in the old workspace must not be reused"
);
}
#[test]
fn hunk_actions_refuse_a_timeline_snapshot_diff() {
// A local-history snapshot diff is built by the same opener as the
// Source Control diff; staging from it would apply snapshot-derived
// patches to the git index from a view that never mentions git.
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("a.txt");
std::fs::write(&path, "new\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor
.open_head_diff_with_text(
PathBuf::from("a.txt (local snapshot)"),
"old\n",
&path,
false,
)
.unwrap();
app.stage_hunk_at_caret();
assert_eq!(
app.status, "Hunk actions need a working-tree diff from Source Control",
"a snapshot diff must refuse hunk actions"
);
}
#[test]
fn workspace_symbol_queries_debounce_instead_of_firing_per_keystroke() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_workspace_symbols("");
if let Some(p) = app.workspace_symbols.as_mut() {
p.query.push('a');
}
app.workspace_symbols_requery();
assert!(
app.ws_symbols_request_id.is_none(),
"a keystroke must not dispatch workspace/symbol synchronously"
);
std::thread::sleep(std::time::Duration::from_millis(250));
app.workspace_symbols_dispatch_due();
assert!(
app.ws_symbols_request_id.is_some() || app.workspace_symbols.as_ref().unwrap().unsupported,
"the settled query must dispatch (or surface no-LSP) after the window"
);
}
#[test]
fn a_reply_to_a_superseded_workspace_symbol_query_is_dropped() {
// Type, let the request dispatch, then type again: the in-flight
// reply answers a query the user has edited away from and must not
// render (workspace/symbol on a big project outlives the debounce).
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_workspace_symbols("");
if let Some(p) = app.workspace_symbols.as_mut() {
p.query.push('a');
}
app.workspace_symbols_requery();
std::thread::sleep(std::time::Duration::from_millis(250));
app.workspace_symbols_dispatch_due();
let id = app
.ws_symbols_request_id
.expect("the settled query dispatched");
if let Some(p) = app.workspace_symbols.as_mut() {
p.query.push('b');
}
app.workspace_symbols_requery();
assert!(
!app.apply_workspace_symbols(id, Vec::new(), false),
"a reply for the superseded query must be dropped, not rendered"
);
}
#[test]
fn clearing_the_workspace_symbol_query_clears_the_unsupported_notice() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_workspace_symbols("");
if let Some(p) = app.workspace_symbols.as_mut() {
p.unsupported = true;
p.query.clear();
}
app.workspace_symbols_requery();
assert!(
!app.workspace_symbols.as_ref().unwrap().unsupported,
"an emptied query shows the type-to-search hint, not a stale notice"
);
}
#[test]
fn run_task_palette_command_opens_the_task_picker() {
use crate::widgets::list_picker::ListPurpose;
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("Makefile"),
"build:\n\ttrue\ntest:\n\ttrue\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(crate::widgets::command_palette::Command::RunTask);
let picker = app
.list_picker
.as_ref()
.expect("Tasks: Run Task must open the picker");
assert_eq!(picker.purpose, ListPurpose::RunTask);
assert!(
picker.rows.iter().any(|r| r.label.contains("make build")),
"discovered tasks appear as rows: {:?}",
picker.rows.iter().map(|r| &r.label).collect::<Vec<_>>()
);
}
#[test]
fn run_build_task_key_predicate_accepts_the_chord_and_rejects_neighbours() {
assert!(is_run_build_task_key(key(
KeyCode::Char('b'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
assert!(is_run_build_task_key(key(
KeyCode::Char('B'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT
)));
// Bare Cmd+B is Toggle Side Bar, not Run Build Task.
assert!(!is_run_build_task_key(key(
KeyCode::Char('b'),
KeyModifiers::SUPER
)));
assert!(!is_run_build_task_key(key(
KeyCode::Char('b'),
KeyModifiers::SUPER | KeyModifiers::SHIFT | KeyModifiers::ALT
)));
}
#[test]
fn cmd_click_on_a_file_line_reference_in_the_terminal_opens_the_file_there() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
std::fs::write(tmp.path().join("src/probe.rs"), "one\ntwo\nthree\nfour\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Render once so `terminal.last_inner` / `last_area` are populated and
// mouse coordinates map to grid cells like on a live click.
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 reference = "src/probe.rs:3:2";
app.terminal_mut()
.write_input(format!("printf 'ref {reference}\\n'\r").as_bytes());
// The echoed command line also contains the reference; wait for the
// OUTPUT line (the one starting with "ref "), then click that one.
let is_output_line = |l: &str| l.trim_start().starts_with("ref src/probe.rs");
// A pure liveness backstop, generous on purpose (#44): the shell does
// its full interactive startup on a box the parallel suite saturates,
// and a tight ceiling here measured the scheduler, not croft — the
// one observed failure had the echoed command on screen but the
// output line not yet flushed. A genuine delivery failure still trips
// this, just later.
let started = std::time::Instant::now();
while started.elapsed() < std::time::Duration::from_secs(30) {
if app.terminal().visible_text().lines().any(is_output_line) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
term.draw(|f| app.render(f)).unwrap();
let snapshot = app.terminal().visible_text();
let row_idx = snapshot
.lines()
.position(is_output_line)
.unwrap_or_else(|| panic!("shell must print the reference; got:\n{snapshot}"));
let line = snapshot.lines().nth(row_idx).unwrap();
let col = line.find("probe.rs").unwrap() + 2;
let inner = app.terminal().last_inner;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: inner.x + col as u16,
row: inner.y + row_idx as u16,
modifiers: KeyModifiers::SUPER,
});
// Canonicalize both sides: on macOS the pane cwd resolves through the
// /var → /private/var symlink while tempdir reports the alias.
let opened = app
.editor
.path
.as_deref()
.map(|p| p.canonicalize().unwrap_or_else(|_| p.to_path_buf()));
assert_eq!(
opened,
Some(
tmp.path()
.join("src/probe.rs")
.canonicalize()
.expect("probe file exists")
),
"Cmd+click on path:line:col must open the file (status: {})",
app.status
);
assert_eq!(app.editor.cursor_row, 2, "line 3 is 0-based row 2");
assert_eq!(app.editor.cursor_col, 1, "col 2 is 0-based col 1");
assert!(
matches!(app.focus, Pane::Editor),
"the jump must focus the editor"
);
}
/// An OSC 8 hyperlink's URI is invisible: the pane shows "CLICK-ME" while
/// the cell carries whatever the printing program chose — including a
/// file:// or custom-scheme URI that `open`/`xdg-open` would hand to an
/// arbitrary application. Only web links may open; anything else is
/// refused with the REAL destination surfaced in the status line.
#[test]
fn cmd_clicking_a_non_web_hyperlink_refuses_instead_of_opening() {
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 script = "printf 'ref \\033]8;;file:///nonexistent-croft-probe\\033\\\\CLICK-ME\\033]8;;\\033\\\\\\n'";
app.terminal_mut()
.write_input(format!("{script}\r").as_bytes());
// Locate the linked cell in the click's own coordinate space
// (`hyperlink_at` viewport rows), not via `visible_text`, whose
// logical-line joining shifts row indices past any soft wrap.
let linked_cell = |app: &App| -> Option<(usize, usize)> {
(0..40usize).find_map(|r| {
(0..120usize)
.find(|&c| {
app.terminal().hyperlink_at(r, c).as_deref()
== Some("file:///nonexistent-croft-probe")
})
.map(|c| (r, c))
})
};
// Load-scaled rather than a fresh constant (#307): this budget was raised
// 5s -> 8s once already, which is the shape of a number that cannot be
// guessed from inside one test. The 1000ms literal that first replaced
// it was under-calibrated against its own siblings and still lost on a
// loaded box, so it now shares `SHELL_PAINT_BASE` with the other
// wait-for-the-shell-to-paint test (#397).
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the shell to paint the linked cell",
|| linked_cell(&app).is_some(),
);
term.draw(|f| app.render(f)).unwrap();
let (row_idx, col) = linked_cell(&app).expect("shell must print the linked text");
let inner = app.terminal().last_inner;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: inner.x + col as u16,
row: inner.y + row_idx as u16,
modifiers: KeyModifiers::SUPER,
});
assert!(
!app.status.starts_with("Opened"),
"a file:// hyperlink must never reach the system opener (status: {})",
app.status
);
assert!(
app.status.contains("file:///nonexistent-croft-probe"),
"the refusal must surface the real destination (status: {})",
app.status
);
}
// Cross-platform: asserts via `clipboard::read_string()`, so the per-thread
// test mock covers the diff-selection → Cmd+C → clipboard wiring on every OS.
// The macOS NSPasteboard FFI is verified separately by the cfg(macos) tests in
// `clipboard.rs` and `cmd_c_on_terminal_selection_lands_text_on_macos_clipboard`.
#[test]
fn cmd_c_on_side_by_side_diff_selection_copies_selected_text() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f1 = tmp.path().join("a.txt");
let f2 = tmp.path().join("b.txt");
std::fs::write(&f1, "alpha\nbravo\ncharlie\n").unwrap();
std::fs::write(&f2, "alpha\nBRAVO\ncharlie\n").unwrap();
app.editor.open_diff(&f1, &f2).unwrap();
app.focus = Pane::Editor;
let backend = ratatui::backend::TestBackend::new(120, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let diff = app.editor.diff.as_ref().unwrap();
let l_gutter = (diff.left_lines.len() + 1).to_string().len() as u16 + 1;
let l_text_x = app.editor.last_inner.x + l_gutter + 2;
let body_top = app.editor.last_inner.y + 1;
// Row 1 in the diff (after the @@/header rows) holds "bravo" on the
// left. Click at col 0, drag to col 5 to select all five chars.
let click_y = body_top + 1;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
column: l_text_x,
row: click_y,
modifiers: KeyModifiers::NONE,
});
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Drag(MouseButton::Left),
column: l_text_x + 5,
row: click_y,
modifiers: KeyModifiers::NONE,
});
let sel = app
.editor
.diff
.as_ref()
.unwrap()
.selection
.expect("drag must have produced a diff selection");
assert!(
sel.has_area(),
"drag must produce a non-zero-area selection"
);
// Drive the actual Cmd+C keystroke through handle_key. This is the
// path the live app takes when the user presses Cmd+C; the
// editor's main key handler short-circuits to handle_diff_key when
// a diff is open, so a copy keybinding must be wired explicitly
// INSIDE handle_diff_key. Without that branch, this assertion
// fails — which is exactly the regression the user just reported:
// selecting text in a diff and pressing Cmd+C did nothing,
// leaving stale test sentinels on the system clipboard for the
// next paste to surface.
let _ = app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER));
let got = crate::clipboard::read_string()
.expect("Cmd+C on a diff selection must put text on the clipboard");
assert_eq!(
got, "bravo",
"selecting cols 0..5 of the left column of row 1 and pressing Cmd+C must copy the exact left-side text via handle_diff_key's copy branch"
);
}
#[test]
fn cmd_w_closes_a_diff_tab() {
// Repro: Cmd+W did nothing on a diff view. handle_editor_key
// short-circuits to handle_diff_key when a diff is open and returns
// before the close-tab branch, so the close-tab key was swallowed.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f1 = tmp.path().join("a.txt");
let f2 = tmp.path().join("b.txt");
std::fs::write(&f1, "alpha\nbravo\n").unwrap();
std::fs::write(&f2, "alpha\nBRAVO\n").unwrap();
app.editor.open_diff(&f1, &f2).unwrap();
app.focus = Pane::Editor;
assert!(app.editor.diff.is_some(), "setup: diff must be open");
app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
.unwrap();
assert!(
app.editor.diff.is_none(),
"Cmd+W on a diff view must close the tab (resetting the last tab to blank), not be swallowed by handle_diff_key"
);
}
#[test]
fn cmd_w_closes_a_sheet_tab() {
// Same swallow bug, sheet branch: handle_sheet_key returned before
// the close-tab handler so Cmd+W never reached close_active.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let csv = tmp.path().join("data.csv");
std::fs::write(&csv, "name,age\nAlice,30\n").unwrap();
app.editor.open(&csv).unwrap();
app.focus = Pane::Editor;
assert!(app.editor.sheet.is_some(), "setup: sheet must be open");
app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
.unwrap();
assert!(
app.editor.sheet.is_none(),
"Cmd+W on a sheet view must close the tab, not be swallowed by handle_sheet_key"
);
}
#[test]
fn cmd_w_closes_an_image_tab() {
// Same swallow bug, image branch: the read-only image guard returned
// before the close-tab handler so Cmd+W could never close a PNG tab.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let png = tmp.path().join("pic.png");
image::RgbaImage::new(2, 2).save(&png).unwrap();
app.editor.open(&png).unwrap();
app.focus = Pane::Editor;
assert!(app.editor.image.is_some(), "setup: image must be open");
app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
.unwrap();
assert!(
app.editor.image.is_none(),
"Cmd+W on an image view must close the tab, not be swallowed by the read-only image guard"
);
}
#[test]
fn enter_in_diff_view_opens_the_file_under_the_caret_at_its_line() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f1 = tmp.path().join("a.txt");
let f2 = tmp.path().join("b.txt");
std::fs::write(&f1, "alpha\nbravo\n").unwrap();
std::fs::write(&f2, "alpha\nBRAVO\ncharlie\n").unwrap();
app.editor.open_diff(&f1, &f2).unwrap();
app.focus = Pane::Editor;
// Row 2 is the Added "charlie" row on the right side: new-file line 3.
app.editor
.diff
.as_mut()
.unwrap()
.start_selection(crate::widgets::diff::DiffSide::Right, 2, 0);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(
app.editor.diff.is_none(),
"Enter must leave the diff and land in a real editable file tab"
);
assert_eq!(
app.editor.path.as_deref(),
Some(f2.as_path()),
"the caret was on the right (working-tree) side, so Enter opens b.txt"
);
assert_eq!(
app.editor.cursor_row, 2,
"goto_line(3) puts the zero-based cursor on row 2 (the 'charlie' line)"
);
}
#[test]
fn enter_on_a_removed_line_in_a_source_control_diff_opens_the_working_file() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let foo = tmp.path().join("foo.txt");
// Working tree dropped "bravo"; HEAD still has it.
std::fs::write(&foo, "alpha\ncharlie\n").unwrap();
// Mirror open_source_control_entry's Modified branch: synthetic HEAD
// label on the left, the real working file on the right.
let label = std::path::PathBuf::from("foo.txt (HEAD)");
app.editor
.open_head_diff_with_text(label, "alpha\nbravo\ncharlie\n", &foo, true)
.unwrap();
app.focus = Pane::Editor;
// Rows: 0 Equal alpha, 1 Removed bravo, 2 Equal charlie. Click row 1.
app.editor
.diff
.as_mut()
.unwrap()
.start_selection(crate::widgets::diff::DiffSide::Left, 1, 0);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(
app.editor.diff.is_none(),
"Enter on a removed line must leave the diff for the real working \
file, not stay parked on the diff tab; status was {:?}",
app.status
);
assert_eq!(app.editor.path.as_deref(), Some(foo.as_path()));
}
#[test]
fn enter_in_multifile_git_diff_opens_the_real_file_under_the_caret() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let src_dir = tmp.path().join("src");
std::fs::create_dir_all(&src_dir).unwrap();
let foo = src_dir.join("foo.rs");
std::fs::write(&foo, "keep1\nold\nkeep2\n").unwrap();
let raw = concat!(
"diff --git a/src/foo.rs b/src/foo.rs\n",
"index 1111111..2222222 100644\n",
"--- a/src/foo.rs\n",
"+++ b/src/foo.rs\n",
"@@ -1,3 +1,4 @@\n",
" keep1\n",
"-old\n",
"+new1\n",
"+new2\n",
" keep2\n",
);
let label = std::path::PathBuf::from("git diff --staged");
app.editor.open_git_diff_side_by_side(&label, raw).unwrap();
app.focus = Pane::Editor;
// Row 3 is "+new1" on the right side (new-file line 2).
app.editor
.diff
.as_mut()
.unwrap()
.start_selection(crate::widgets::diff::DiffSide::Right, 3, 0);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.path.as_deref(),
Some(foo.as_path()),
"Enter on a row in the multi-file git diff must open the real file the \
`diff --git` header names, resolved against the workspace root; status was {:?}",
app.status
);
assert_eq!(app.editor.cursor_row, 1, "+new1 is new-file line 2");
}
#[test]
fn editor_find_in_side_by_side_diff_counts_matches_in_diff_content() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f1 = tmp.path().join("a.txt");
let f2 = tmp.path().join("b.txt");
std::fs::write(&f1, "alpha\nbravo\ncharlie\n").unwrap();
std::fs::write(&f2, "alpha\nbravo\ncharlie\nlogger.info here\n").unwrap();
app.editor.open_diff(&f1, &f2).unwrap();
app.focus = Pane::Editor;
let backend = ratatui::backend::TestBackend::new(120, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
app.open_editor_find();
app.editor_find_set_query(String::from("logger"));
let count = app.editor_find.as_ref().map(|s| s.match_count).unwrap_or(0);
assert!(
count >= 1,
"Find must search the content rendered in a diff tab: 'logger' is visible in the right column yet match_count={count}"
);
let active = app
.editor
.diff
.as_ref()
.and_then(|d| d.find.active)
.expect("a match in a diff must set an active find position for highlighting");
assert_eq!(
active.side,
crate::widgets::diff::DiffSide::Right,
"the 'logger' match lives on the added (right) side and must be selected as active"
);
}
#[test]
fn editor_find_in_diff_next_prev_cycle_through_both_columns() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f1 = tmp.path().join("a.txt");
let f2 = tmp.path().join("b.txt");
std::fs::write(&f1, "needle one\nplain\n").unwrap();
std::fs::write(&f2, "needle one\nplain\nneedle two\n").unwrap();
app.editor.open_diff(&f1, &f2).unwrap();
app.focus = Pane::Editor;
let backend = ratatui::backend::TestBackend::new(120, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
app.open_editor_find();
app.editor_find_set_query(String::from("needle"));
let count = app.editor_find.as_ref().map(|s| s.match_count).unwrap_or(0);
assert!(
count >= 2,
"an equal line counts on both columns plus the added line: expected >=2, got {count}"
);
let first = app.editor_find.as_ref().and_then(|s| s.match_index);
assert_eq!(first, Some(1), "opening find selects the first match");
app.editor_find_jump_next();
let second = app.editor_find.as_ref().and_then(|s| s.match_index);
assert_eq!(second, Some(2), "Enter advances to the second match");
app.editor_find_jump_prev();
let back = app.editor_find.as_ref().and_then(|s| s.match_index);
assert_eq!(back, Some(1), "Shift+Enter walks back to the first match");
}
#[test]
fn diff_word_selection_highlights_every_other_occurrence() {
// Highlight-all parity with the plain editor: selecting a word in the
// diff must paint a muted-blue box over EVERY other occurrence of that
// word on screen (VS Code's `editor.selectionHighlight`), exactly like
// the regular editor does. The diff renderer used to only paint the
// active selection band, leaving the other occurrences un-highlighted.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f1 = tmp.path().join("a.txt");
let f2 = tmp.path().join("b.txt");
// "alpha" appears on every equal row's left AND right column, so a single
// word selection has many other occurrences visible at once.
std::fs::write(&f1, "alpha one\nalpha two\nalpha three\n").unwrap();
std::fs::write(&f2, "alpha one\nalpha two\nalpha three\nalpha four\n").unwrap();
app.editor.open_diff(&f1, &f2).unwrap();
app.focus = Pane::Editor;
let _ = render_buf(&mut app);
// Select the word "alpha" (cols 0..5) on the left column of the first row.
{
let diff = app.editor.diff.as_mut().unwrap();
diff.select_word_at(crate::widgets::diff::DiffSide::Left, 0, 0);
assert_eq!(
diff.selection_text().as_deref(),
Some("alpha"),
"fixture: word click must select exactly 'alpha'"
);
}
let buf = render_buf(&mut app);
let occurrence = Color::Rgb(0x37, 0x61, 0x8e);
let occ_cells = count_bg(&buf, occurrence);
// The selected word itself is overpainted by the brighter selection band,
// so every occurrence we count here is a *different* one. Two equal rows
// still on screen carry "alpha" on both columns -> at least four more
// 5-char spans = 20 cells, well over this floor.
assert!(
occ_cells >= 10,
"selecting 'alpha' in the diff must highlight all other occurrences in \
the muted-blue selection-highlight colour, mirroring the plain editor; \
got only {occ_cells} highlighted cells"
);
}
#[test]
fn double_click_in_diff_selects_word_and_cmd_c_copies_it() {
// End-to-end: two left-clicks in quick succession on a word in
// the left column must snap a word-bounded selection (same UX
// as VS Code / standard text editors), and the very next Cmd+C
// keystroke must put exactly that word on the clipboard.
// Cross-platform: asserts via `clipboard::read_string()`, so the
// per-thread test mock exercises this on every OS (no real-clipboard
// opt-in needed — the OS pasteboard path is covered elsewhere).
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f1 = tmp.path().join("a.txt");
let f2 = tmp.path().join("b.txt");
std::fs::write(&f1, "alpha bravo charlie\nsecond\n").unwrap();
std::fs::write(&f2, "alpha BRAVO charlie\nsecond\n").unwrap();
app.editor.open_diff(&f1, &f2).unwrap();
app.focus = Pane::Editor;
let backend = ratatui::backend::TestBackend::new(120, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let diff = app.editor.diff.as_ref().unwrap();
let l_gutter = (diff.left_lines.len() + 1).to_string().len() as u16 + 1;
let l_text_x = app.editor.last_inner.x + l_gutter + 2;
let body_top = app.editor.last_inner.y + 1;
// "alpha bravo charlie" — "bravo" starts at char col 6.
let bravo_x = l_text_x + 8;
let click_y = body_top;
let first = crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
column: bravo_x,
row: click_y,
modifiers: KeyModifiers::NONE,
};
app.handle_mouse(first);
let second = crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
column: bravo_x,
row: click_y,
modifiers: KeyModifiers::NONE,
};
app.handle_mouse(second);
let sel = app
.editor
.diff
.as_ref()
.unwrap()
.selection
.expect("double-click must produce a word selection");
assert!(sel.has_area(), "word selection must span >0 chars");
let _ = app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER));
let got = crate::clipboard::read_string()
.expect("Cmd+C after double-click must put the word on the clipboard");
assert_eq!(
got, "bravo",
"double-click word selection + Cmd+C must copy exactly the clicked word"
);
}
// Exercises the macOS-native NSPasteboard backend (`clipboard::macos`), which
// only exists on macOS — gate it like the sibling native tests in
// `clipboard.rs` so the Linux/Android test binaries still compile and run
// everything else (an ungated macOS-only test fails to *compile* off-macOS,
// poisoning the whole test target rather than just skipping).
#[cfg(target_os = "macos")]
#[test]
fn lock_clipboard_for_test_restores_prior_clipboard_text_on_drop() {
// Tests that hit the real NSPasteboard must never leave their
// sentinels behind. This test simulates a user already having
// text on the clipboard, runs a guarded section that writes a
// sentinel, drops the guard, and asserts the clipboard now
// reads back the simulated "user" text rather than the test
// sentinel.
//
// To avoid leaking the simulated text into the developer's real
// clipboard, capture the genuine pre-test contents first and
// restore them at the very end via a Drop guard so even a panic
// in the middle leaves the host clipboard untouched.
struct RestoreClip(Option<String>);
impl Drop for RestoreClip {
fn drop(&mut self) {
match self.0.take() {
Some(s) => {
crate::clipboard::macos::write_string_native(&s);
}
None => crate::clipboard::macos::clear_native(),
}
}
}
let _restore = RestoreClip(crate::clipboard::macos::read_string_native());
let pre = format!("user-preexisting-clip-{}", std::process::id());
crate::clipboard::macos::write_string_native(&pre);
{
let _g = crate::clipboard::lock_clipboard_for_test();
let sentinel = "test-sentinel-should-not-leak";
assert!(
crate::clipboard::write_string(sentinel),
"guard-held write must hit the real NSPasteboard"
);
assert_eq!(
crate::clipboard::read_string().as_deref(),
Some(sentinel),
"while the guard is held the test reads what it just wrote"
);
}
let after = crate::clipboard::macos::read_string_native();
assert_eq!(
after.as_deref(),
Some(pre.as_str()),
"dropping the guard MUST restore the pre-test clipboard so a cargo test run never leaves a test sentinel on the developer's system clipboard for the next paste to surface"
);
}
#[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() {
// Ctrl+Shift+J is now reserved for the terminal-maximize chord, so
// the terminal-toggle matcher must reject it. Ctrl+J alone (with no
// shift) still toggles.
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");
}
/// User-visible regression: with the terminal maximised via
/// Ctrl+Shift+J, a mouse drag inside the (now fullscreen) terminal
/// pane must reach `PtyTerminal::extend_selection_to` so the user
/// can highlight terminal text. Before this fix `EditorTabs::render`
/// returned early on `area.height == 0` without zeroing the active
/// editor's `last_area`, so `handle_mouse`'s `in_editor` hit-test
/// (`rect_contains(self.editor.last_area, ...)`) still matched the
/// pre-maximise rectangle and the dispatch at app.rs:7229 / 7336
/// routed the click into `editor.mouse_down` / `editor.mouse_drag`.
/// The user saw the file caret jump instead of a selection
/// appearing in the terminal — symptom: "the cursor is jumping up
/// and down as I go back and forth."
#[test]
fn maximised_terminal_owns_mouse_drag_for_selection_not_the_collapsed_editor() {
let tmp = tempfile::tempdir().unwrap();
// Seed a real file and open it so the editor actually claims a
// non-empty rectangle on the first render (the blank-initial
// branch zeroes `last_area.height` to skip welcome-pane
// overdraw, which would mask the bug we're probing).
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();
// Render once in split layout so the editor's `last_area` ends
// up pointing at the right-hand pane — the exact stale
// rectangle the bug would later read from.
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let editor_area_before_maximise = app.editor.last_area;
assert!(
editor_area_before_maximise.width > 0 && editor_area_before_maximise.height > 0,
"precondition: in split layout with an open file the editor must claim a real rectangle, otherwise the bug we're testing for can't manifest"
);
// Trigger the maximize chord.
let chord = key(
KeyCode::Char('J'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
);
app.handle_key(chord).unwrap();
assert!(app.terminal_maximized);
// Re-render in the maximised layout — this is the frame that
// used to leave `editor.last_area` stale.
term.draw(|f| app.render(f)).unwrap();
assert_eq!(
app.editor.last_area.height, 0,
"after maximise, the editor's hit-test rectangle must have height 0 so `in_editor` cannot match a click that lands on the maximised terminal"
);
// Drive a real Left-Drag through the production key/mouse
// dispatch: anywhere inside the maximised terminal pane. With
// the fix in place the drag must end up extending the terminal
// selection, not poking the editor caret.
let term_area = app.terminal().last_area;
assert!(
term_area.width > 4 && term_area.height > 4,
"precondition: the maximised terminal must own a real rect for the drag to land in"
);
let click_col = term_area.x + 2;
let click_row = term_area.y + 2;
let drag_col = click_col + 5;
let drag_row = click_row;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: click_col,
row: click_row,
modifiers: KeyModifiers::NONE,
});
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
column: drag_col,
row: drag_row,
modifiers: KeyModifiers::NONE,
});
let sel = app.terminal().selection();
assert!(
sel.is_some_and(|s| s.has_area()),
"drag inside the maximised terminal must seed a non-empty selection on the PtyTerminal - if this is None or zero-area the click was eaten by the stale editor hit-test"
);
}
/// User-visible regression (issue #23): on mobile (Termux) a
/// multiline drag-selection that begins inside the terminal pane and
/// then travels *up* past the terminal's top edge into the editor
/// region must stay local to the terminal. The terminal sits below the
/// editor in the split layout, so a drag headed upward crosses into the
/// editor's rectangle. Before the fix, the editor pane reacted to the
/// out-of-bounds drag and started its own selection, so the user saw
/// text highlighted in BOTH the terminal and the left editor pane. The
/// drag must only ever extend the terminal's own selection (clamped to
/// the terminal grid) and never seed an editor selection.
#[test]
fn multiline_terminal_drag_above_the_pane_does_not_bleed_into_the_editor() {
let tmp = tempfile::tempdir().unwrap();
// Seed and open a real file so the editor claims a non-empty rect
// directly above the terminal — the region the upward drag enters.
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();
// Render once in the split layout (editor on top, terminal on the
// bottom, sharing the same column band).
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"
);
// The user first has an active selection in the editor pane (e.g. left
// over from editing). Seed it so the editor owns a real selection band
// that would render alongside any new terminal selection.
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"
);
// Down inside the terminal, a couple of rows below its top edge so
// there is vertical room to drag upward out of the pane.
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,
});
// Drag UP into the editor region (row above the terminal's top edge)
// and toward the left — the gesture that used to overflow the pane.
let drag_col = term_inner.x + 1;
let drag_row = editor_area.y + 1; // well inside the editor's rectangle
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,
});
// The editor must NOT have started a selection of its own.
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"
);
// The terminal's selection head must be clamped to the terminal's
// own grid: with no scrollback the topmost reachable viewport line
// is 0 and the column stays within the inner width.
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
);
}
/// Cross-pane paste matrix. In production, Cmd+V on macOS does NOT
/// arrive as a key event — `setup-iterm2` deliberately leaves Cmd+V
/// unbound (src/iterm2.rs:225-235) so iTerm2's native Paste action
/// fires and emits a bracketed-paste sequence carrying the OS
/// clipboard into the PTY. crossterm surfaces that as
/// `Event::Paste(s)`, dispatched by `main_loop` to
/// `App::handle_paste(&s)` (src/app.rs:17131).
///
/// This matrix therefore drives `handle_paste` directly with the
/// payload that iTerm2 would have delivered. Every destination
/// (editor, editor-find, search query, file-finder query,
/// terminal, source-control commit box) must consume the payload
/// in BOTH terminal layouts (split + maximised). If a case
/// silently fails here, that's the exact production symptom the
/// user described: "I copied from one place, pasted in another,
/// nothing happened."
#[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)
}
fn render(app: &mut App) -> ratatui::Terminal<ratatui::backend::TestBackend> {
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
term
}
// Drive a bracketed paste from a non-path token, which is what
// iTerm2 emits when the user presses Cmd+V with terminal text
// on the clipboard. Non-path so the drop-handler branches in
// handle_paste don't divert us into "import into Explorer / scp
// to Remote / fetch via drop-relay".
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";
// -- Case 1: paste into the editor while terminal is split.
{
let (_tmp, mut app) = seed_app();
let _draw = render(&mut app);
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
);
}
// -- Case 2: paste into the editor while terminal is maximised.
{
let (_tmp, mut app) = seed_app();
let _draw = render(&mut app);
app.toggle_terminal_maximize();
let _draw = render(&mut app);
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
);
}
// -- Case 3: paste into the editor-find bar while terminal is
// split. The user explicitly named this as broken.
{
let (_tmp, mut app) = seed_app();
let _draw = render(&mut app);
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:?}"
);
}
// -- Case 4: paste into the editor-find bar while terminal is
// maximised.
{
let (_tmp, mut app) = seed_app();
let _draw = render(&mut app);
app.toggle_terminal_maximize();
let _draw = render(&mut app);
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:?}"
);
}
// -- Case 5: paste into the Search sidebar query while
// terminal is split.
{
let (_tmp, mut app) = seed_app();
let _draw = render(&mut app);
app.set_sidebar_view(SidebarView::Search);
let _draw = render(&mut app);
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
);
}
// -- Case 6: paste into Search sidebar while terminal is
// maximised. The user explicitly named the split layout as
// failing while maximised worked; both must succeed.
{
let (_tmp, mut app) = seed_app();
let _draw = render(&mut app);
app.toggle_terminal_maximize();
let _draw = render(&mut app);
app.set_sidebar_view(SidebarView::Search);
let _draw = render(&mut app);
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
);
}
// -- Case 7: paste into the embedded terminal while it is
// split. The terminal pane consumes the bracketed paste by
// writing the bytes back into the PTY.
{
let (_tmp, mut app) = seed_app();
let _draw = render(&mut app);
app.focus_pane(Pane::Terminal);
// No panic + handler completes is enough. Verifying the
// PTY received the bytes requires polling the shell which
// is too timing-fragile for CI.
app.handle_paste("clip-into-terminal-split");
}
// -- Case 8: paste into the embedded terminal while
// maximised.
{
let (_tmp, mut app) = seed_app();
let _draw = render(&mut app);
app.toggle_terminal_maximize();
let _draw = render(&mut app);
app.focus_pane(Pane::Terminal);
app.handle_paste("clip-into-terminal-maximised");
}
// -- Case 9: paste into the Source Control commit message
// box while terminal split. NOTE: at the time of writing,
// handle_paste has no SourceControl branch — this case
// will FAIL until handle_paste learns to route into the
// commit message when sidebar_view == SourceControl.
{
let (_tmp, mut app) = seed_app();
let _draw = render(&mut app);
app.set_sidebar_view(SidebarView::SourceControl);
let _draw = render(&mut app);
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
);
}
// -- Case 10: paste into the file-finder (Cmd+P quick-open).
{
let (_tmp, mut app) = seed_app();
let _draw = render(&mut app);
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:?}"
);
}
}
/// Double-clicking a word in the terminal pane must word-select
/// in BOTH terminal layouts. The user reported that double-click
/// "doesn't auto-select" in some state. The detection logic in
/// `handle_mouse` keys off `last_terminal_left_down` + window;
/// the test sends two consecutive Down events on the same cell
/// within DOUBLE_CLICK_WINDOW and asserts a non-empty word
/// selection appears.
#[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;
// Two clicks within the DOUBLE_CLICK_WINDOW on the same
// cell — same path a real macOS double-click takes.
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" }
);
}
}
/// #317, the reported gesture end to end: a ctrl+click that matches no link
/// falls past the URL and file arms into the built-in selection path. That
/// path used to arm the double-click tracker regardless of modifiers, so the
/// user's NEXT ordinary click at the same cell classified as a double and
/// word-selected text they never double-clicked.
///
/// The probe word is deliberately link-free and path-free, so the ctrl+click
/// genuinely reaches the fall-through arm rather than being consumed above it
/// - a click that IS consumed would make this test pass without the fix.
#[test]
fn a_ctrl_click_that_opens_nothing_does_not_arm_the_terminal_double_click() {
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.focus_pane(Pane::Terminal);
let probe = format!("croftmodclick{}", 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;
let click = |app: &mut App, modifiers| {
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: screen_x,
row: screen_y,
modifiers,
});
};
// The ctrl+click must actually fall through: nothing on this word is a
// URL or an existing file, so no link opens and no selection is made yet.
click(&mut app, KeyModifiers::CONTROL);
// The user's next ordinary click, at the same cell.
click(&mut app, KeyModifiers::NONE);
let sel = app.terminal().selection_text();
assert!(
!sel.contains(&probe),
"a plain click after an unmatched ctrl+click must not word-select: the \
ctrl+click must not have armed the double-click tracker, but selection was {sel:?}"
);
// The guard must not have cost the real gesture: two plain clicks still
// word-select at the same cell.
click(&mut app, KeyModifiers::NONE);
let sel = app.terminal().selection_text();
assert!(
sel.contains(&probe) || probe.contains(&sel),
"two ordinary clicks must still word-select; got {sel:?}"
);
}
/// End-to-end variant of the matrix that exercises the user's
/// exact gesture chain: text on screen in the embedded terminal →
/// real Cmd+C through the terminal pane handler → switch to the
/// destination pane → paste. The clipboard is the per-thread mock
/// (see `crate::clipboard::test_clip`) so both ends ride the same
/// transport every croft Cmd+C / Cmd+V hits in production. Every
/// pair below must succeed in BOTH terminal layouts because the
/// user explicitly demands identical behaviour ("the terminal
/// size should not matter").
#[test]
fn terminal_copy_paste_into_other_panes_works_in_split_and_maximised_layout() {
// Seed a PtyTerminal grid with a known string, set a selection
// over it, and trigger the production Cmd+C path so the mock
// clipboard ends up with the payload. Returns the payload that
// landed on the clipboard.
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
}
// Drive every destination/layout pair. The clipboard lives on
// the test thread, so cross-pane wiring is the only thing
// that can fail here.
let layouts: &[bool] = &[false, true]; // false = split, true = maximised
for &maximise in layouts {
// ---- Destination: Search sidebar ----
{
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);
// Switch to Search like a real user would (Cmd+Shift+F
// through the production key path).
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();
// Simulate the bracketed paste iTerm2 would send on
// Cmd+V (production path with setup-iterm2 applied).
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
);
}
// ---- Destination: editor-find ----
{
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);
// Switch back to editor + open find.
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" }
);
}
// ---- Destination: editor body ----
{
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
);
}
// ---- Destination: source-control commit box ----
{
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
);
}
}
}
/// Issue #226: the probe command must not spell the probe out, or the
/// shell's echo of it becomes a second row that matches the grid search
/// (and wins the race under load). Pins both halves of `probe_command`:
/// the echoed text can't contain the probe, and running it still puts the
/// probe on screen.
#[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();
// Runs the very command asserted on above, on the same budget every other
// probe site uses.
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"
);
}
/// User-reported root cause: with the Search sidebar open, Cmd+C /
/// Cmd+V in the terminal silently no-op because the search-editing
/// shortcut guard fired on `focus != Editor`, swallowing the keys
/// into the (empty) search query instead of the focused terminal.
/// Copying from the terminal must work regardless of which sidebar
/// view is showing.
#[test]
fn terminal_cmd_c_copies_even_when_search_sidebar_is_open() {
// Cross-platform: the assertion reads back via `clipboard::read_string()`,
// so the per-thread mock validates the Cmd+C-routing logic on every OS.
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 ctrl_j_clears_maximize_when_hiding_terminal() {
// Mental contract: Ctrl+J means "give me my normal layout back."
// Hiding the terminal must clear the maximize flag so the next
// Ctrl+J reopen restores the editor+terminal split, not a stuck
// maximized terminal.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let max_chord = key(
KeyCode::Char('J'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
);
let toggle_chord = key(KeyCode::Char('j'), KeyModifiers::CONTROL);
app.handle_key(max_chord).unwrap();
assert!(app.terminal_maximized);
app.handle_key(toggle_chord).unwrap();
assert!(!app.show_terminal, "Ctrl+J hides the terminal");
assert!(
!app.terminal_maximized,
"hiding the terminal also clears maximize"
);
app.handle_key(toggle_chord).unwrap();
assert!(app.show_terminal, "Ctrl+J reshows the terminal");
assert!(
!app.terminal_maximized,
"reopened terminal stays in normal split, not maximized"
);
}
#[test]
fn maximized_terminal_collapses_editor_in_render_layout() {
// Drive an actual frame and assert the editor pane received zero
// height while the terminal occupies the full right column. This
// pins the user-visible behavior, not just the flag.
use ratatui::{Terminal, backend::TestBackend};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let max_chord = key(
KeyCode::Char('J'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
);
app.handle_key(max_chord).unwrap();
let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert_eq!(
app.editor.last_area.height, 0,
"maximized terminal must collapse editor to zero rows"
);
assert!(
app.editor.last_full_area.width > 0,
"editor still tracks its column for hit-testing"
);
}
#[test]
fn maximizing_terminal_requests_welcome_image_clear_when_image_was_displayed() {
// Repro for "wordmark + icon bleed through the maximized terminal":
// the welcome OSC-1337 image was painted at the editor pane's cells
// before maximize. Maximizing collapses the editor to zero height
// and the terminal pane now covers those cells, but iTerm2 still
// has the image cached at the old cell positions. ratatui's text
// writes do NOT evict that cache - only a one-shot terminal.clear()
// does, gated by consume_welcome_image_clear().
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() {
// No prior emit means iTerm has no cached cells to evict; the clear
// chain must stay silent so the main loop doesn't pointlessly
// CSI-2J the screen every time the user toggles maximize before
// they ever land on the welcome panel.
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() {
// After a clear, the post-draw emitter re-paints the welcome only
// when welcome_overlay_dirty is true. render_welcome only sets it
// when the layout *changes*, so if the restored editor area is
// bit-identical to the pre-maximize area the dirty flag would
// stay false and the wordmark would never come back. Exit must
// arm it explicitly.
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 delete_key_is_recognized_as_delete_node() {
assert!(is_delete_node_key(key(KeyCode::Delete, KeyModifiers::NONE)));
}
#[test]
fn cmd_backspace_is_recognized_as_delete_node() {
// macOS Finder convention: ⌘⌫ moves the selection to the Trash.
assert!(is_delete_node_key(key(
KeyCode::Backspace,
KeyModifiers::SUPER
)));
}
#[test]
fn plain_backspace_is_delete_node_on_mac_layouts() {
// On Mac keyboards the key labeled "delete" reports as Backspace; in
// the tree pane (the only context this helper is called from) it must
// trigger deletion to match the user's expectation.
assert!(is_delete_node_key(key(
KeyCode::Backspace,
KeyModifiers::NONE
)));
}
#[test]
fn ctrl_d_is_not_delete_node() {
assert!(!is_delete_node_key(key(
KeyCode::Char('d'),
KeyModifiers::CONTROL
)));
}
#[test]
fn open_create_prompt_populates_state() {
// We can't easily build a full App in a test (PtyTerminal spawns a real
// shell), so we exercise the Prompt struct directly via the public
// helpers it relies on. This guards the data the prompt carries.
use crate::widgets::file_tree::{create_file_in, create_folder_in, validate_new_name};
use tempfile::TempDir;
let tmp = TempDir::new().unwrap();
// commit_prompt path: validate → create → returns path on success.
assert!(validate_new_name("hello.rs").is_ok());
let p = create_file_in(tmp.path(), "hello.rs").unwrap();
assert!(p.is_file());
let d = create_folder_in(tmp.path(), "newdir").unwrap();
assert!(d.is_dir());
}
#[test]
fn set_title_seq_wraps_with_osc0_and_bel() {
let bytes = set_title_seq("croft");
assert_eq!(bytes, b"\x1b]0;croft\x07");
}
#[test]
fn set_title_seq_handles_empty_title() {
let bytes = set_title_seq("");
assert_eq!(bytes, b"\x1b]0;\x07");
}
#[test]
fn set_title_seq_passes_through_unicode() {
let bytes = set_title_seq("croft README.md");
assert_eq!(bytes, "\x1b]0;croft README.md\x07".as_bytes());
}
#[test]
fn set_title_seq_strips_control_bytes_that_would_break_the_escape() {
// BEL terminates the OSC, ESC starts a new sequence — both must be filtered.
let bytes = set_title_seq("evil\x07file");
assert_eq!(bytes, b"\x1b]0;evilfile\x07");
let bytes = set_title_seq("evil\x1bfile");
assert_eq!(bytes, b"\x1b]0;evilfile\x07");
let bytes = set_title_seq("evil\nfile");
assert_eq!(bytes, b"\x1b]0;evilfile\x07");
}
#[test]
fn app_name_constant_is_croft() {
assert_eq!(APP_NAME, "croft");
}
#[test]
fn set_session_bg_srgb_seq_uses_iterm_osc1337_and_srgb_prefix() {
// iTerm2 must read the bg as sRGB so the OSC-1337 PNG canvas (also
// sRGB) matches pixel-for-pixel. Locking in the exact bytes catches
// any future refactor that drops the `srgb:` prefix or the iTerm2
// OSC introducer.
let seq = set_session_bg_srgb_seq(crate::theme::Theme::DARK_BLUE.editor_bg_rgb());
assert_eq!(seq, "\x1b]1337;SetColors=bg=srgb:1e222e\x07");
}
#[test]
fn reset_session_bg_seq_restores_profile_default() {
// On exit we must revert iTerm2's session bg so the user's shell
// doesn't keep croft's forced bg colour.
assert_eq!(reset_session_bg_seq(), "\x1b]1337;SetColors=bg=default\x07");
}
#[test]
fn welcome_logo_png_asset_is_present_and_decodable() {
// Regression guard for the welcome screen: the bundled logo asset
// must remain a valid PNG so the OSC-1337 path can bake it. If
// someone replaces it with a half-block fallback or empties the
// asset, this catches it on every CI run.
let bytes = crate::iterm2_inline::WELCOME_LOGO_PNG;
assert!(bytes.len() > 1024, "welcome logo asset suspiciously small");
assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n", "not a PNG file");
let img = image::load_from_memory_with_format(bytes, image::ImageFormat::Png)
.expect("welcome logo PNG must decode");
assert!(img.width() > 0 && img.height() > 0);
}
#[test]
fn welcome_image_bake_produces_osc1337_carrying_logo_pixels() {
// End-to-end regression for the welcome render path: feeding the
// bundled logo PNG through the same `fit_image` + `build_inline_image_osc`
// pipeline `render_welcome` uses must yield an OSC-1337 sequence
// that (a) starts with the iTerm2 introducer, (b) advertises the
// requested cell dimensions, and (c) carries an opaque canvas
// filled with `EDITOR_BG_RGB`. If anyone swaps OSC-1337 for a
// half-block or text fallback, this test will refuse to compile
// or fail the byte assertions.
let canvas_w = 48u32 * 8; // approx welcome cell w * cell pixel w
let canvas_h = 14u32 * 16;
let bg_rgb = crate::theme::Theme::DARK_BLUE.editor_bg_rgb();
let bg = image::Rgba([bg_rgb.0, bg_rgb.1, bg_rgb.2, 0xff]);
let baked = crate::iterm2_inline::fit_image(
crate::iterm2_inline::WELCOME_LOGO_PNG,
canvas_w,
canvas_h,
bg,
)
.expect("baked welcome PNG");
assert_eq!(
&baked[..8],
b"\x89PNG\r\n\x1a\n",
"fit_image must emit a PNG"
);
let osc = crate::iterm2_inline::build_inline_image_osc(&baked, 48, 14, false);
assert!(osc.starts_with("\x1b]1337;File=inline=1"));
assert!(osc.ends_with('\x07'));
assert!(osc.contains("width=48"));
assert!(osc.contains("height=14"));
// Verify the canvas corner pixels are exactly the dark-blue theme bg so
// the welcome image bg matches the sRGB-decoded session bg.
let img = image::load_from_memory_with_format(&baked, image::ImageFormat::Png)
.unwrap()
.to_rgba8();
for &(x, y) in &[
(0u32, 0u32),
(canvas_w - 1, 0),
(0, canvas_h - 1),
(canvas_w - 1, canvas_h - 1),
] {
let p = img.get_pixel(x, y);
assert_eq!(
(p.0[0], p.0[1], p.0[2], p.0[3]),
(bg_rgb.0, bg_rgb.1, bg_rgb.2, 0xff),
"canvas corner ({x}, {y}) must be opaque editor bg"
);
}
}
#[test]
fn brand_spans_render_the_cr_ft_wordmark_with_orange_brackets() {
let spans = brand_spans(crate::theme::Theme::default());
let text: String = spans.iter().map(|s| s.content.as_ref()).collect();
assert_eq!(text, " cr<>ft ");
// The "<>" (the stylised "o") carries the logo orange; letters stay white.
let bracket = spans.iter().find(|s| s.content == "<>").unwrap();
assert_eq!(bracket.style.fg, Some(BRAND_ORANGE));
assert_eq!(spans[0].style.fg, Some(Color::White));
}
#[test]
fn dtach_reattach_mode_reassert_reenables_mouse_tracking() {
// dtach `-r winch` delivers only a SIGWINCH on reattach: the newly
// attached terminal never received the startup DECSETs, so without a
// re-assert the mouse is dead after every reconnect to a persisted
// session (0.1.610 bug on `various`). The Resize-time sequence must
// re-enable the alt screen, mouse tracking with SGR encoding, and
// bracketed paste, and must SET (not push) the kitty keyboard flags so
// repeated WINCHes don't leak stack entries the single exit pop can't
// unwind.
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:?}");
}
// Structural guarantee, not just spot checks: the re-assert embeds the
// startup takeover block verbatim, so a mode added at startup (via
// takeover_mode_seq) can never be missing from the reattach path.
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 keyboard_enhancement_flags_request_disambiguate_escape_codes() {
let f = keyboard_enhancement_flags();
assert!(
f.contains(crossterm::event::KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES),
"Cmd / modifier delivery requires DISAMBIGUATE_ESCAPE_CODES"
);
}
#[test]
fn keyboard_enhancement_flags_do_not_force_all_keys_as_escapes() {
// REPORT_ALL_KEYS_AS_ESCAPE_CODES rewrites plain printable input.
// We only need the disambiguation bit, not the all-keys bit.
let f = keyboard_enhancement_flags();
assert!(
!f.contains(crossterm::event::KeyboardEnhancementFlags::REPORT_ALL_KEYS_AS_ESCAPE_CODES),
"we should not opt into REPORT_ALL_KEYS_AS_ESCAPE_CODES"
);
}
#[test]
fn status_bar_shows_document_facts_not_a_keyboard_cheat_sheet() {
// The redesigned bar drops the `^q Quit / ^j Term / …` cheat-sheet for a
// VS Code-style right cluster of document facts.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.path = Some(std::path::PathBuf::from("x.rs"));
app.editor
.set_language(Some(crate::highlight::LangKind::Rust));
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let last_y = buf.area.height - 1;
let row: String = (0..buf.area.width)
.map(|x| buf[(x, last_y)].symbol())
.collect();
assert!(
row.contains("Ln 1, Col 1"),
"status bar shows cursor position: {row:?}"
);
assert!(
row.contains("Rust"),
"status bar shows language mode: {row:?}"
);
assert!(
!row.contains("Cycle pane") && !row.contains("Quit"),
"the keyboard cheat-sheet must be gone: {row:?}"
);
}
#[test]
fn no_stale_tcode_pill_literal_in_source() {
let src = include_str!("mod.rs");
assert!(
!src.contains("\" tcode \""),
"stale ` tcode ` pill literal still present in src/app/mod.rs"
);
}
#[test]
fn build_title_uses_basename_and_app_name() {
let p = std::path::Path::new("/Users/somebody/projects/croft");
assert_eq!(build_title(p), "croft croft");
let p = std::path::Path::new("/");
assert_eq!(build_title(p), "croft /");
}
fn file_node(path: &Path) -> crate::widgets::file_tree::Node {
crate::widgets::file_tree::Node {
path: path.to_path_buf(),
depth: 1,
is_dir: false,
expanded: false,
loaded: false,
}
}
fn dir_node(path: &Path) -> crate::widgets::file_tree::Node {
crate::widgets::file_tree::Node {
path: path.to_path_buf(),
depth: 1,
is_dir: true,
expanded: false,
loaded: false,
}
}
#[test]
fn tree_context_menu_on_file_offers_new_file_new_folder_then_cut_copy_rename_delete() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("hello.txt");
std::fs::write(&f, "hi").unwrap();
let n = file_node(&f);
let target = f.parent().unwrap().to_path_buf();
let items = build_tree_context_menu_items(
Some(&n),
tmp.path(),
std::slice::from_ref(&f),
&target,
None,
None,
);
let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
assert_eq!(
labels,
[
"New File",
"New Folder",
"Cut",
"Copy",
"Rename",
"Select for Compare",
"Delete",
],
);
assert!(matches!(&items[0].1, MenuAction::Create(CreateKind::File)));
assert!(matches!(
&items[1].1,
MenuAction::Create(CreateKind::Folder)
));
assert!(matches!(&items[2].1, MenuAction::Cut(ps) if ps == &vec![f.clone()]));
assert!(matches!(&items[3].1, MenuAction::Copy(ps) if ps == &vec![f.clone()]));
assert!(matches!(&items[4].1, MenuAction::Rename(p) if p == &f));
assert!(matches!(&items[5].1, MenuAction::SelectForCompare(p) if p == &f));
assert!(matches!(&items[6].1, MenuAction::Delete { paths } if paths == &vec![f.clone()]));
}
#[test]
fn tree_context_menu_adds_reveal_in_finder_when_local_macos() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("hello.txt");
std::fs::write(&f, "hi").unwrap();
let n = file_node(&f);
let target = f.parent().unwrap().to_path_buf();
let mut items = build_tree_context_menu_items(
Some(&n),
tmp.path(),
std::slice::from_ref(&f),
&target,
None,
None,
);
maybe_add_reveal_in_finder(&mut items, Some(f.as_path()), true);
// Lands directly beneath the New File / New Folder block, mirroring VS
// Code's top "reveal" placement.
assert!(matches!(
&items[2].1,
MenuAction::RevealInFinder(p) if p == &f
));
assert_eq!(items[2].0, "Reveal in Finder");
}
#[test]
fn tree_context_menu_omits_reveal_in_finder_when_remote() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("hello.txt");
std::fs::write(&f, "hi").unwrap();
let n = file_node(&f);
let target = f.parent().unwrap().to_path_buf();
let mut items = build_tree_context_menu_items(
Some(&n),
tmp.path(),
std::slice::from_ref(&f),
&target,
None,
None,
);
// A remote SSH session disables Finder: the entry must not appear at all,
// not even as a disabled no-op.
maybe_add_reveal_in_finder(&mut items, Some(f.as_path()), false);
assert!(
!items
.iter()
.any(|(_, a)| matches!(a, MenuAction::RevealInFinder(_)))
);
}
#[test]
fn tree_context_menu_omits_reveal_in_finder_when_no_entry_clicked() {
let tmp = tempfile::tempdir().unwrap();
let mut items = build_tree_context_menu_items(None, tmp.path(), &[], tmp.path(), None, None);
// Right-clicking empty tree space has no path to reveal even on local macOS.
maybe_add_reveal_in_finder(&mut items, None, true);
assert!(
!items
.iter()
.any(|(_, a)| matches!(a, MenuAction::RevealInFinder(_)))
);
}
#[test]
fn reveal_in_finder_shortcut_hint_is_opt_cmd_r() {
let action = MenuAction::RevealInFinder(PathBuf::from("/tmp/x"));
assert_eq!(shortcut_for(&action), Some("⌥⌘R"));
}
#[test]
fn reveal_in_finder_key_is_opt_cmd_r_and_disjoint_from_rename() {
// Cmd+Opt+R (and Ctrl+Opt+R) reveal in Finder.
assert!(is_reveal_in_finder_key(key(
KeyCode::Char('r'),
KeyModifiers::SUPER | KeyModifiers::ALT
)));
assert!(is_reveal_in_finder_key(key(
KeyCode::Char('r'),
KeyModifiers::CONTROL | KeyModifiers::ALT
)));
// Plain Cmd+R must NOT trigger reveal - that chord is Rename.
assert!(!is_reveal_in_finder_key(key(
KeyCode::Char('r'),
KeyModifiers::SUPER
)));
// And Cmd+Opt+R must NOT trigger Rename, so the two R chords never collide.
assert!(!is_tree_rename_key(key(
KeyCode::Char('r'),
KeyModifiers::SUPER | KeyModifiers::ALT
)));
}
#[test]
fn explorer_shortcut_predicates_recognise_expected_keys() {
assert!(is_tree_new_file_key(key(
KeyCode::Char('f'),
KeyModifiers::SUPER
)));
assert!(is_tree_new_file_key(key(
KeyCode::Char('F'),
KeyModifiers::CONTROL
)));
assert!(!is_tree_new_file_key(key(
KeyCode::Char('f'),
KeyModifiers::NONE
)));
// Shift+Super disqualifies New File so Cmd+Shift+F can fall through to
// the global Search jump (New Folder now lives on Cmd+Shift+N).
assert!(!is_tree_new_file_key(key(
KeyCode::Char('F'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
assert!(is_tree_new_folder_key(key(
KeyCode::Char('N'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
assert!(is_tree_new_folder_key(key(
KeyCode::Char('N'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT
)));
assert!(!is_tree_new_folder_key(key(
KeyCode::Char('n'),
KeyModifiers::SUPER
)));
assert!(
!is_tree_new_folder_key(key(
KeyCode::Char('F'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)),
"Cmd+Shift+F is no longer the New Folder chord — it must fall through to the global Search jump"
);
assert!(is_tree_rename_key(key(
KeyCode::Char('r'),
KeyModifiers::SUPER
)));
assert!(is_tree_rename_key(key(KeyCode::F(2), KeyModifiers::NONE)));
assert!(!is_tree_rename_key(key(
KeyCode::Char('r'),
KeyModifiers::NONE
)));
assert!(is_tree_make_root_key(key(
KeyCode::Char('/'),
KeyModifiers::SUPER
)));
assert!(is_tree_make_root_key(key(
KeyCode::Char('/'),
KeyModifiers::CONTROL
)));
assert!(!is_tree_make_root_key(key(
KeyCode::Char('/'),
KeyModifiers::NONE
)));
let cmd_shift = KeyModifiers::SUPER | KeyModifiers::SHIFT;
let ctrl_shift = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
assert!(is_tree_make_parent_root_key(key(
KeyCode::Char('/'),
cmd_shift
)));
assert!(is_tree_make_parent_root_key(key(
KeyCode::Char('/'),
ctrl_shift
)));
assert!(is_tree_make_parent_root_key(key(
KeyCode::Char('?'),
KeyModifiers::SUPER
)));
assert!(is_tree_make_parent_root_key(key(
KeyCode::Char('?'),
KeyModifiers::CONTROL
)));
assert!(is_tree_make_parent_root_key(key(
KeyCode::Char('?'),
cmd_shift
)));
assert!(!is_tree_make_parent_root_key(key(
KeyCode::Char('/'),
KeyModifiers::SUPER
)));
assert!(!is_tree_make_parent_root_key(key(
KeyCode::Char('/'),
KeyModifiers::NONE
)));
assert!(!is_tree_make_parent_root_key(key(
KeyCode::Char('?'),
KeyModifiers::NONE
)));
assert!(!is_tree_make_root_key(key(KeyCode::Char('/'), cmd_shift)));
}
#[test]
fn tree_typeahead_first_keystroke_jumps_to_first_matching_visible_node() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join("apple")).unwrap();
std::fs::write(tmp.path().join("banana.txt"), "").unwrap();
std::fs::write(tmp.path().join("cherry.txt"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.apply_tree_typeahead('b', std::time::Instant::now());
let picked = app.tree.nodes[app.tree.selected]
.path
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
assert_eq!(picked, "banana.txt", "typing 'b' must select banana.txt");
}
#[test]
fn tree_typeahead_accumulates_prefix_within_window() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join("test")).unwrap();
std::fs::create_dir(tmp.path().join("toolbox")).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let t0 = std::time::Instant::now();
app.apply_tree_typeahead('t', t0);
app.apply_tree_typeahead('e', t0 + std::time::Duration::from_millis(100));
let name = app.tree.nodes[app.tree.selected]
.path
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
assert_eq!(
name, "test",
"'te' typed within the window must land on 'test', not 'toolbox'"
);
}
#[test]
fn tree_typeahead_resets_after_window_expires_and_cycles() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join("test")).unwrap();
std::fs::create_dir(tmp.path().join("toolbox")).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let t0 = std::time::Instant::now();
app.apply_tree_typeahead('t', t0);
let first = app.tree.selected;
let first_name = app.tree.nodes[first]
.path
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
app.apply_tree_typeahead('t', t0 + std::time::Duration::from_millis(1000));
let second = app.tree.selected;
let second_name = app.tree.nodes[second]
.path
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
assert_ne!(
first, second,
"the second 't' after the window expires must cycle to the next 't' match"
);
assert!(
first_name.starts_with('t') && second_name.starts_with('t'),
"both cycle stops must start with 't'"
);
}
#[test]
fn tree_typeahead_is_case_insensitive() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("README.md"), "").unwrap();
std::fs::write(tmp.path().join("zzz.txt"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.apply_tree_typeahead('r', std::time::Instant::now());
let picked = app.tree.nodes[app.tree.selected]
.path
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
assert_eq!(picked, "README.md");
}
#[test]
fn tree_typeahead_via_handle_tree_key_jumps_selection() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join("apple")).unwrap();
std::fs::write(tmp.path().join("banana.txt"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Tree);
app.sidebar_view = SidebarView::Explorer;
app.handle_tree_key(key(KeyCode::Char('b'), KeyModifiers::NONE));
let picked = app.tree.nodes[app.tree.selected]
.path
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
assert_eq!(
picked, "banana.txt",
"a plain letter routed through handle_tree_key must drive typeahead"
);
}
#[test]
fn tree_typeahead_does_not_fire_when_modifier_held() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("banana.txt"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let before = app.tree.selected;
app.focus_pane(Pane::Tree);
app.sidebar_view = SidebarView::Explorer;
app.handle_tree_key(key(KeyCode::Char('b'), KeyModifiers::CONTROL));
assert_eq!(
app.tree.selected, before,
"Ctrl+letter must not be consumed as typeahead"
);
assert!(
app.tree_typeahead.is_none(),
"Ctrl-modified keys must not seed the typeahead buffer"
);
}
#[test]
fn cmd_shift_n_in_explorer_pane_creates_a_new_folder() {
// With Explorer focused, Cmd+Shift+N opens the New Folder prompt
// (the user-requested binding, moved off Cmd+Shift+F so that chord
// can always reach the global Search jump).
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Tree);
app.sidebar_view = SidebarView::Explorer;
app.handle_key(key(
KeyCode::Char('N'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert!(
matches!(
app.prompt.as_ref(),
Some(Prompt {
kind: PromptKind::Create(CreateKind::Folder),
..
})
),
"Explorer-focused Cmd+Shift+N must open a New Folder prompt"
);
assert_eq!(
app.sidebar_view,
SidebarView::Explorer,
"must NOT jump to Search"
);
}
#[test]
fn cmd_shift_f_in_explorer_pane_jumps_to_search_not_new_folder() {
// Cmd+Shift+F is no longer the Explorer's New Folder chord — it
// now always jumps to the Search sidebar, even when Explorer is
// focused. New Folder lives on Cmd+Shift+N.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Tree);
app.sidebar_view = SidebarView::Explorer;
app.handle_key(key(
KeyCode::Char('F'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert!(
app.prompt.is_none(),
"Cmd+Shift+F must NOT open the New Folder prompt anymore"
);
assert_eq!(app.sidebar_view, SidebarView::Search);
}
#[test]
fn cmd_shift_f_outside_explorer_still_jumps_to_search() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.sidebar_view = SidebarView::Explorer;
app.handle_key(key(
KeyCode::Char('F'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(app.sidebar_view, SidebarView::Search);
}
#[test]
fn shortcut_for_returns_expected_shortcuts_for_each_explorer_action() {
let p = std::path::PathBuf::from("/x");
assert_eq!(
shortcut_for(&MenuAction::Create(CreateKind::File)),
Some("⌘F")
);
assert_eq!(
shortcut_for(&MenuAction::Create(CreateKind::Folder)),
Some("⌘⇧N")
);
assert_eq!(shortcut_for(&MenuAction::Cut(vec![p.clone()])), Some("⌘X"));
assert_eq!(shortcut_for(&MenuAction::Copy(vec![p.clone()])), Some("⌘C"));
assert_eq!(shortcut_for(&MenuAction::Paste(p.clone())), Some("⌘V"));
assert_eq!(shortcut_for(&MenuAction::Rename(p.clone())), Some("⌘R"));
assert_eq!(shortcut_for(&MenuAction::MakeRoot(p.clone())), Some("⌘/"));
assert_eq!(
shortcut_for(&MenuAction::Delete {
paths: vec![p.clone()]
}),
Some("⌫")
);
// Every menu row carries an accelerator (croft tenet: no blank column).
// Color Theme, Close to the Right, and the compare actions are Cmd+K chords.
assert_eq!(shortcut_for(&MenuAction::OpenThemePicker), Some("⌘K ⌘T"));
assert_eq!(shortcut_for(&MenuAction::CloseTabsToRight(0)), Some("⌘K →"));
assert_eq!(
shortcut_for(&MenuAction::SelectForCompare(p.clone())),
Some("⌘K S")
);
assert_eq!(
shortcut_for(&MenuAction::CompareWithSelected {
anchor: p.clone(),
other: p.clone()
}),
Some("⌘K C")
);
assert_eq!(
shortcut_for(&MenuAction::EditBreakpointConditionAt { line: 0 }),
Some("⇧F9")
);
// Editor tab-menu actions: Close Saved and Reveal in Explorer View are
// Cmd+K chords; Copy Path is a standalone Cmd+Opt chord.
assert_eq!(shortcut_for(&MenuAction::CloseSavedTabs), Some("⌘K U"));
assert_eq!(
shortcut_for(&MenuAction::CopyTabPath(p.clone())),
Some("⌥⌘C")
);
assert_eq!(
shortcut_for(&MenuAction::RevealInExplorer(p.clone())),
Some("⌘K E")
);
}
#[test]
fn tree_context_menu_on_subfolder_offers_make_root_between_rename_and_delete() {
// "Make root" should appear on folder right-click so the user can
// re-root the workspace into that folder (e.g., a nested git repo).
// It must NOT appear on file right-clicks - files can't be a
// workspace root.
let tmp = tempfile::tempdir().unwrap();
let d = tmp.path().join("project_a");
std::fs::create_dir(&d).unwrap();
let n = dir_node(&d);
let items = build_tree_context_menu_items(
Some(&n),
tmp.path(),
std::slice::from_ref(&d),
&d,
None,
None,
);
let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
assert!(
labels.contains(&"Make root"),
"folder right-click must include Make root, got {labels:?}"
);
let mr = items
.iter()
.find_map(|(_, a)| match a {
MenuAction::MakeRoot(p) => Some(p),
_ => None,
})
.expect("Make root action must carry the folder path");
assert_eq!(mr, &d);
}
#[test]
fn tree_context_menu_on_file_does_not_offer_make_root() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("hello.txt");
std::fs::write(&f, "hi").unwrap();
let n = file_node(&f);
let target = f.parent().unwrap().to_path_buf();
let items = build_tree_context_menu_items(
Some(&n),
tmp.path(),
std::slice::from_ref(&f),
&target,
None,
None,
);
let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
assert!(
!labels.contains(&"Make root"),
"files cannot be roots; Make root must be hidden for files: {labels:?}"
);
}
#[test]
fn cmd_shift_slash_on_a_file_changes_workspace_root_to_the_file_s_parent_dir() {
let tmp = tempfile::tempdir().unwrap();
let inner = tmp.path().join("inner");
std::fs::create_dir(&inner).unwrap();
let file = inner.join("note.txt");
std::fs::write(&file, "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let target_idx = app
.tree
.nodes
.iter()
.position(|n| n.path == file)
.or_else(|| {
let i = app.tree.nodes.iter().position(|n| n.path == inner).unwrap();
app.tree.selected = i;
app.tree.expand_selected();
app.tree.nodes.iter().position(|n| n.path == file)
})
.expect("file node must be visible after expanding inner/");
app.tree.selected = target_idx;
app.focus = Pane::Tree;
app.sidebar_view = SidebarView::Explorer;
let handled = app.handle_explorer_shortcut(key(
KeyCode::Char('/'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
));
assert!(
handled,
"Cmd+Shift+/ must be handled by the Explorer dispatcher"
);
assert_eq!(app.workspace_root(), inner);
assert_eq!(app.tree.root, inner);
}
#[test]
fn changing_workspace_root_retargets_search_at_the_new_explorer_root() {
let tmp = tempfile::tempdir().unwrap();
let inner = tmp.path().join("inner");
std::fs::create_dir_all(&inner).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.search.hits.push(crate::widgets::search::SearchHit {
path: tmp.path().join("stale.txt"),
line_no: 1,
line_text: String::from("stale"),
});
app.change_workspace_root(inner.clone());
assert_eq!(
app.search.root, inner,
"the search panel must point at the Explorer's new root so its target and the path-stripping match"
);
assert!(
app.search.hits.is_empty(),
"hits from the previous root must be dropped when the Explorer root changes"
);
}
#[test]
fn changing_workspace_root_rebinds_the_test_worker_to_the_new_root() {
let tmp = tempfile::tempdir().unwrap();
let inner = tmp.path().join("inner");
std::fs::create_dir_all(&inner).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert_eq!(app.test_worker.root(), tmp.path());
app.change_workspace_root(inner.clone());
assert_eq!(
app.test_worker.root(),
inner,
"the test runner must follow the Explorer root; left at the launch dir (e.g. ~/Documents, no Cargo.toml) `cargo test -- --list` errors and the Testing view stays empty"
);
}
#[test]
fn changing_workspace_root_resets_the_testing_panel() {
let tmp = tempfile::tempdir().unwrap();
let inner = tmp.path().join("inner");
std::fs::create_dir_all(&inner).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// The old project's tree (e.g. pytest cases from a Python repo).
app.testing.apply_case(crate::testing::model::TestCase {
name: String::from("tests/test_x.py::test_a"),
status: crate::testing::model::TestStatus::Failed,
});
assert!(!app.testing.is_empty());
app.change_workspace_root(inner.clone());
assert!(
app.testing.is_empty(),
"a workspace re-root must drop the old project's tests; a stale tree also blocks open_testing_view's discover-on-empty, so the new project is never discovered"
);
assert_eq!(
app.testing.failed_count(),
0,
"the beaker badge must not keep counting the old project's failures"
);
}
#[test]
fn changing_workspace_root_rebinds_the_lsp_manager_to_the_new_root() {
let tmp = tempfile::tempdir().unwrap();
let inner = tmp.path().join("inner");
std::fs::create_dir_all(&inner).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Pretend a file from the old root is already open with the LSP so we can
// prove the seen-map is reset (otherwise sync_lsp would never re-open it
// against the new server).
app.lsp_last_seen.insert(tmp.path().join("stale.rs"), 7);
app.change_workspace_root(inner.clone());
assert_eq!(
app.lsp.as_ref().unwrap().workspace_root(),
inner,
"rust-analyzer's workspace folder must follow the Explorer root; left at the launch dir (e.g. ~/Documents, which has no Cargo.toml) every opened .rs comes back as an unlinked-file with no IDE services"
);
assert!(
app.lsp_last_seen.is_empty(),
"the LSP seen-map must be cleared on re-root so the next sync_lsp re-opens every live editor tab against the freshly-rooted server"
);
}
#[test]
fn cmd_shift_slash_on_a_folder_changes_workspace_root_to_that_folder_s_parent() {
let tmp = tempfile::tempdir().unwrap();
let mid = tmp.path().join("mid");
let leaf = mid.join("leaf");
std::fs::create_dir_all(&leaf).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mid_idx = app.tree.nodes.iter().position(|n| n.path == mid).unwrap();
app.tree.selected = mid_idx;
app.tree.expand_selected();
let leaf_idx = app
.tree
.nodes
.iter()
.position(|n| n.path == leaf)
.expect("leaf must be visible after expanding mid/");
app.tree.selected = leaf_idx;
app.focus = Pane::Tree;
app.sidebar_view = SidebarView::Explorer;
let handled = app.handle_explorer_shortcut(key(KeyCode::Char('?'), KeyModifiers::SUPER));
assert!(handled);
assert_eq!(app.workspace_root(), mid);
assert_eq!(app.tree.root, mid);
}
#[test]
fn cmd_shift_slash_on_the_tree_root_walks_up_one_filesystem_level() {
let tmp = tempfile::tempdir().unwrap();
let inner = tmp.path().join("inner");
std::fs::create_dir(&inner).unwrap();
let mut app = App::new(inner.clone()).unwrap();
app.tree.selected = 0;
app.focus = Pane::Tree;
app.sidebar_view = SidebarView::Explorer;
let handled = app.handle_explorer_shortcut(key(
KeyCode::Char('/'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
));
assert!(handled);
assert_eq!(app.workspace_root(), tmp.path());
assert_eq!(app.tree.root, tmp.path());
}
#[test]
fn status_bar_indent_menu_action_pins_the_editor_indent_style() {
use crate::widgets::editor::IndentStyle;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Default is spaces; the pill click routes through SetIndentStyle to tabs.
app.dispatch_menu_action(
MenuAction::SetIndentStyle(IndentStyle {
width: 4,
use_spaces: false,
}),
tmp.path().to_path_buf(),
);
assert_eq!(
app.editor.indent_style(),
IndentStyle {
width: 4,
use_spaces: false,
}
);
assert_eq!(app.editor.indent_style().label(), "Tab Size: 4");
}
#[test]
fn dispatch_make_root_changes_tree_root_and_workspace_root() {
let tmp = tempfile::tempdir().unwrap();
let project = tmp.path().join("project_b");
std::fs::create_dir(&project).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let original_root = app.tree.root.clone();
app.dispatch_menu_action(MenuAction::MakeRoot(project.clone()), project.clone());
assert_ne!(app.tree.root, original_root);
assert_eq!(app.tree.root, project);
assert_eq!(app.workspace_root(), project);
// The tree's root node must reflect the new path.
assert_eq!(app.tree.nodes[0].path, project);
}
#[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();
// Clear the freshly-spawned shell's "first paint" dirty bit so
// the next take_dirty() exclusively reflects bytes written by
// change_workspace_root itself. change_workspace_root performs
// no other write_input on the terminal, so a dirty flag after
// the call can only have come from the change_cwd seed.
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 xlsx_grid_editing_saves_cells_and_holds_formulas_for_consent() {
// #178 end-to-end: xlsx cells edit like CSV, Cmd+S applies exactly
// the touched cells through umya, and a formula cell needs the
// second (forced) save to be overwritten.
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("book.xlsx");
let mut book = umya_spreadsheet::new_file();
let ws = book.sheet_mut(0).unwrap();
ws.cell_mut((1u32, 1u32)).set_value("name");
ws.cell_mut((2u32, 1u32)).set_value("qty");
ws.cell_mut((1u32, 2u32)).set_value("apples");
ws.cell_mut((2u32, 2u32)).set_value_number(3);
ws.cell_mut((2u32, 3u32)).set_formula("SUM(B2)");
umya_spreadsheet::writer::xlsx::write(&book, &p).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&p).unwrap();
assert!(app.editor.sheet.is_some());
// Edit qty (0,1) to 42.
app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
app.handle_sheet_key(key(KeyCode::Char('4'), KeyModifiers::NONE));
app.handle_sheet_key(key(KeyCode::Char('2'), KeyModifiers::NONE));
app.handle_sheet_key(key(KeyCode::Enter, KeyModifiers::NONE));
assert!(app.editor.dirty);
// And overwrite the formula cell (1,1).
app.handle_sheet_key(key(KeyCode::Char('8'), KeyModifiers::NONE));
app.handle_sheet_key(key(KeyCode::Enter, KeyModifiers::NONE));
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
.unwrap();
assert!(
app.editor.dirty,
"the formula cell is held back, so the tab stays dirty: {}",
app.status
);
assert!(
app.status.contains("formula"),
"status names it: {}",
app.status
);
let book2 = umya_spreadsheet::reader::xlsx::read(&p).unwrap();
let ws2 = book2.sheet_by_name("Sheet1").unwrap();
assert_eq!(
ws2.cell((2u32, 2u32)).unwrap().value(),
"42",
"the plain cell landed on the first save"
);
assert!(ws2.cell((2u32, 3u32)).unwrap().is_formula());
// Second Cmd+S consents to the formula overwrite.
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
.unwrap();
assert!(!app.editor.dirty, "everything saved: {}", app.status);
let book3 = umya_spreadsheet::reader::xlsx::read(&p).unwrap();
let ws3 = book3.sheet_by_name("Sheet1").unwrap();
assert!(!ws3.cell((2u32, 3u32)).unwrap().is_formula());
assert_eq!(ws3.cell((2u32, 3u32)).unwrap().value(), "8");
}
#[test]
fn sheet_grid_editing_types_commits_and_saves_with_the_delimiter() {
// #177 end-to-end: cell cursor, type-to-replace, commit-and-advance,
// dirty mirroring, the serialisation save path, and a structure op.
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("data.csv");
std::fs::write(&p, "a,b\n1,2\n3,4\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&p).unwrap();
assert!(app.editor.sheet.is_some());
app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
app.handle_sheet_key(key(KeyCode::Char('9'), KeyModifiers::NONE));
assert!(
app.editor.sheet.as_ref().unwrap().editing.is_some(),
"typing opens the in-grid editor, replacing the value"
);
app.handle_sheet_key(key(KeyCode::Char('!'), KeyModifiers::NONE));
app.handle_sheet_key(key(KeyCode::Enter, KeyModifiers::NONE));
let view = app.editor.sheet.as_ref().unwrap();
assert_eq!(view.sheets[0].cell(0, 1), "9!", "Enter commits");
assert_eq!(view.sheets[0].cur_row, 1, "and advances down");
assert!(view.dirty && app.editor.dirty);
app.save();
assert!(!app.editor.dirty);
assert_eq!(std::fs::read_to_string(&p).unwrap(), "a,b\n1,9!\n3,4\n");
// Structure op on the selected row (row index 1: "3,4").
app.sheet_structure_op(crate::widgets::command_palette::Command::SheetDeleteRow);
assert!(app.editor.dirty);
app.save();
assert_eq!(std::fs::read_to_string(&p).unwrap(), "a,b\n1,9!\n");
// Esc cancels an edit without committing.
app.handle_sheet_key(key(KeyCode::Char('x'), KeyModifiers::NONE));
app.handle_sheet_key(key(KeyCode::Esc, KeyModifiers::NONE));
assert!(app.editor.sheet.as_ref().unwrap().editing.is_none());
assert_eq!(
app.editor.sheet.as_ref().unwrap().sheets[0].cell(0, 1),
"9!"
);
}
#[test]
fn hex_typing_edits_bytes_and_cmd_s_writes_them_in_place() {
// #173 end-to-end: hex-pane nibble typing, Tab to the ASCII pane,
// dirty tracking, undo, and the byte save path (never the text
// choke point, which #185 makes refuse preview tabs).
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("blob.bin");
std::fs::write(&p, vec![0u8; 16]).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&p).unwrap();
assert!(app.editor.hex.is_some());
// "4" then "1" completes 0x41 at offset 0 and advances the cursor.
app.handle_hex_key(key(KeyCode::Char('4'), KeyModifiers::NONE));
assert_eq!(
app.editor.hex.as_ref().unwrap().pending_nibble,
Some(4),
"first nibble latches"
);
app.handle_hex_key(key(KeyCode::Char('1'), KeyModifiers::NONE));
let v = app.editor.hex.as_ref().unwrap();
assert_eq!(v.effective_byte(0), Some(0x41));
assert_eq!(v.cursor, 1, "completed byte advances");
assert!(app.editor.dirty, "pending edits mark the tab dirty");
// Tab switches panes; a typed character lands as its byte.
app.handle_hex_key(key(KeyCode::Tab, KeyModifiers::NONE));
app.handle_hex_key(key(KeyCode::Char('Z'), KeyModifiers::NONE));
let v = app.editor.hex.as_ref().unwrap();
assert_eq!(v.effective_byte(1), Some(b'Z'));
assert_eq!(v.cursor, 2);
// Undo removes the last byte; redo restores it.
app.handle_hex_key(key(KeyCode::Char('z'), KeyModifiers::SUPER));
assert_eq!(
app.editor.hex.as_ref().unwrap().effective_byte(1),
Some(0),
"undo reverts to the disk byte"
);
app.handle_hex_key(key(
KeyCode::Char('z'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
));
assert_eq!(
app.editor.hex.as_ref().unwrap().effective_byte(1),
Some(b'Z')
);
// Cmd+S through the REAL key dispatch writes the bytes in place
// and cleans the tab (#191 review: app.save() directly would keep
// passing if the chord routing broke).
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
.unwrap();
assert!(!app.editor.dirty);
let disk = std::fs::read(&p).unwrap();
assert_eq!(disk[0], 0x41);
assert_eq!(disk[1], b'Z');
assert_eq!(disk.len(), 16, "in-place write, length untouched");
assert!(
app.status.starts_with("Wrote 2 bytes"),
"status reports the write: {}",
app.status
);
}
#[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();
// Put the active terminal into a long-lived foreground command.
// 60s, not 10 (#169): under a loaded suite this test thread can be
// descheduled >10s between the busy precondition and the re-root —
// the sleep then exits and the shell GENUINELY reclaims the tty, so
// the seed was correct and the assert wrong. Pane Drop kills the
// shell tree, so nothing outlives the test.
//
// Proving the sleep is REALLY the foreground command needs more than
// pgrp samples (#186): rc-startup children also own the tty, so a
// resolved non-shell reading can be rc — the input above then sits as
// type-ahead and the re-root races the first prompt. The marker's
// OUTPUT is the proof: quote-split so the echoed command line cannot
// match, it can only be printed by the shell's MAIN loop executing
// the line — rc is done, and the very next resolved non-shell sample
// can only be the sleep.
app.terminal_mut()
.write_input(b"echo GO''-MARKER; sleep 60\n");
// Load-scaled (#397): the hand-rolled 8000ms loop this replaced did not
// stretch under load at all, and its failure said only "marker output
// never arrived" — true of a starved shell and a broken one alike.
// `await_spawned` names what it waited for and how long it actually had.
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"))
},
);
// `Some(false)` is a kernel-confirmed foreign foreground group, and
// with rc ruled out above it can only be the sleep. The fail-closed
// retry inside `foreground_is_shell` can answer false on an
// UNRESOLVED sample, so poll the strict accessor, not the policy one.
// Retain the loop's own sample for the assert: re-sampling could see
// a transient `None` (a failed tcgetpgrp) after the loop already
// observed the confirmed reading.
// Load-scaled like the marker wait above (#397): a shell that wins the
// marker race inside a stretched budget could still lose a fixed 4000ms
// here, and this one does not assert on timeout — it falls through to
// the precondition assert below, which then reads as a broken
// foreground-group check rather than a starved box. Captured from
// inside the closure so the assert keeps the sample the wait observed.
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)
},
);
// `await_spawned` panics rather than returning on timeout, so this can
// only be `Some(false)`; it pins the sample the wait observed rather
// than guarding the wait. Same shape as `wait_for_conflicted_entry`.
assert_eq!(
foreground,
Some(false),
"await_spawned returns only once the kernel reports the foreign group"
);
app.change_workspace_root(target_dir.clone());
// The "terminal busy" status is set by the very branch that skips
// change_cwd, so it is a deterministic proxy for "no cd was injected"
// - far more reliable than the async PTY dirty bit, which the running
// sleep and residual echo can flip independently of any cd seed.
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();
// Reproduce the #94 window deterministically: a shell whose rc startup
// holds the tty's foreground process group before the first prompt.
// `set -m` turns job control on, so the foreground `sleep` gets its own
// process group and the tty — exactly the state an rc-startup child
// leaves the pane in under full-suite load.
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(),
);
// await_spawned panics on timeout, so this pins the state the rest of
// the test reads rather than guarding the wait, the same shape as
// wait_for_conflicted_entry.
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 tree_context_menu_on_subfolder_offers_new_file_new_folder_then_cut_copy_rename_delete() {
let tmp = tempfile::tempdir().unwrap();
let d = tmp.path().join("sub");
std::fs::create_dir(&d).unwrap();
let n = dir_node(&d);
let target = d.clone();
let items = build_tree_context_menu_items(
Some(&n),
tmp.path(),
std::slice::from_ref(&d),
&target,
None,
None,
);
let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
assert_eq!(
labels,
[
"New File",
"New Folder",
"Cut",
"Copy",
"Rename",
"Make root",
"Delete"
],
);
}
#[test]
fn tree_context_menu_with_clipboard_offers_paste_on_directory() {
let tmp = tempfile::tempdir().unwrap();
let d = tmp.path().join("sub");
std::fs::create_dir(&d).unwrap();
let n = dir_node(&d);
let clip = ExplorerClipboard {
mode: ExplorerClipMode::Cut,
paths: vec![tmp.path().join("a.txt")],
};
let items = build_tree_context_menu_items(
Some(&n),
tmp.path(),
std::slice::from_ref(&d),
&d,
Some(&clip),
None,
);
let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
assert_eq!(
labels,
[
"New File",
"New Folder",
"Cut",
"Copy",
"Paste",
"Rename",
"Make root",
"Delete"
],
);
}
#[test]
fn tree_context_menu_on_a_deeply_nested_folder_creates_inside_that_folder() {
// Regression for the user-reported "right-click on nested
// folders only shows Cut/Copy/Rename/Delete; I cannot create a
// new file or folder inside the folder I clicked". The menu
// must surface New File / New Folder, and the resolved
// target_dir must be the right-clicked folder itself so the
// create lands inside it (not at the workspace root).
let tmp = tempfile::tempdir().unwrap();
let nested = tmp.path().join("a").join("b").join("c");
std::fs::create_dir_all(&nested).unwrap();
let n = dir_node(&nested);
let resolved_target = crate::widgets::file_tree::create_target_dir_for(Some(&n), tmp.path());
assert_eq!(
resolved_target, nested,
"right-click on a nested folder must target the folder itself, not the workspace root",
);
let items = build_tree_context_menu_items(
Some(&n),
tmp.path(),
std::slice::from_ref(&nested),
&resolved_target,
None,
None,
);
let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
assert!(
labels.contains(&"New File"),
"nested-folder right-click must offer New File; labels = {labels:?}",
);
assert!(
labels.contains(&"New Folder"),
"nested-folder right-click must offer New Folder; labels = {labels:?}",
);
}
#[test]
fn arrow_and_pageup_pagedown_scroll_the_diff_view() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f1 = tmp.path().join("a.txt");
let f2 = tmp.path().join("b.txt");
// 30 distinct lines so the diff has plenty of rows to scroll.
let left: String = (0..30).map(|i| format!("left-{i}\n")).collect();
let right: String = (0..30).map(|i| format!("right-{i}\n")).collect();
std::fs::write(&f1, left).unwrap();
std::fs::write(&f2, right).unwrap();
app.editor.open_diff(&f1, &f2).unwrap();
// Pretend the editor inner is 12 rows tall (page = 10 after the
// header + footer reservation).
app.editor.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 12,
};
app.focus_pane(Pane::Editor);
// Down once → +1.
app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.diff.as_ref().unwrap().scroll, 1);
// PageDown → +page (10).
app.handle_key(key(KeyCode::PageDown, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.diff.as_ref().unwrap().scroll, 11);
// Up once → -1.
app.handle_key(key(KeyCode::Up, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.diff.as_ref().unwrap().scroll, 10);
// PageUp → -page.
app.handle_key(key(KeyCode::PageUp, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.diff.as_ref().unwrap().scroll, 0);
// Home / End.
app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
.unwrap();
let total = app.editor.diff.as_ref().unwrap().rows.len();
assert_eq!(app.editor.diff.as_ref().unwrap().scroll, total);
app.handle_key(key(KeyCode::Home, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.diff.as_ref().unwrap().scroll, 0);
}
#[test]
fn ctrl_d_with_no_anchor_stashes_selected_file() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("a.txt");
std::fs::write(&f, "v1").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let idx = app
.tree
.nodes
.iter()
.position(|n| n.path == f)
.expect("file must appear in tree");
app.tree.selected = idx;
app.handle_key(key(KeyCode::Char('d'), KeyModifiers::CONTROL))
.unwrap();
assert_eq!(app.compare_anchor.as_deref(), Some(f.as_path()));
}
/// Issue #210: Go Forward. After Go Back (Ctrl+-), Ctrl+Shift+- must
/// return to where the user came from, at the same cursor position.
#[test]
fn ctrl_shift_minus_goes_forward_after_back() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.rs");
let b = tmp.path().join("b.rs");
std::fs::write(&a, "fn a() {}\n").unwrap();
std::fs::write(
&b,
"fn b() {}\nfn b2() {}\nfn b3() {}\nfn b4() {}\nfn b5() {}\nfn b6() {}\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.focus_pane(Pane::Editor);
// Jump (records a.rs:0 on the back stack, like go-to-definition).
app.go_to_definition(b.clone(), 5, 0);
assert_eq!(app.editor.path.as_deref(), Some(b.as_path()));
assert_eq!(app.editor.cursor_row, 5);
// Back returns to a.rs.
app.handle_key(key(KeyCode::Char('-'), KeyModifiers::CONTROL))
.unwrap();
assert_eq!(app.editor.path.as_deref(), Some(a.as_path()));
// Forward must return to b.rs:5.
app.handle_key(key(
KeyCode::Char('-'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(
app.editor.path.as_deref(),
Some(b.as_path()),
"Ctrl+Shift+- must go forward to the jump target"
);
assert_eq!(app.editor.cursor_row, 5, "forward restores the position");
}
/// Legacy encodings fold Ctrl+- into 0x1F (`_` + CONTROL, no SHIFT); that
/// spelling must stay Go BACK, never forward.
#[test]
fn legacy_ctrl_underscore_without_shift_stays_go_back() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.rs");
let b = tmp.path().join("b.rs");
std::fs::write(&a, "fn a() {}\n").unwrap();
std::fs::write(&b, "fn b() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.focus_pane(Pane::Editor);
app.go_to_definition(b.clone(), 0, 0);
app.handle_key(key(KeyCode::Char('_'), KeyModifiers::CONTROL))
.unwrap();
assert_eq!(
app.editor.path.as_deref(),
Some(a.as_path()),
"bare Ctrl+_ (legacy Ctrl+-) must still go back"
);
}
/// Issue #210: Go to Last Edit Location (Cmd+K Cmd+Q). After editing one
/// file and navigating elsewhere, the chord returns to the edit point.
#[test]
fn cmd_k_cmd_q_jumps_to_the_last_edit_location() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.rs");
let b = tmp.path().join("b.rs");
std::fs::write(&a, "fn a() {}\nfn a2() {}\nfn a3() {}\n").unwrap();
std::fs::write(&b, "fn b() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.focus_pane(Pane::Editor);
// Edit a.rs at row 2.
app.editor.cursor_row = 2;
app.editor.cursor_col = 0;
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
// Navigate away.
app.editor.open_pinned(&b).unwrap();
assert_eq!(app.editor.path.as_deref(), Some(b.as_path()));
// Cmd+K Cmd+Q returns to the edit point in a.rs.
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('q'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(
app.editor.path.as_deref(),
Some(a.as_path()),
"Cmd+K Cmd+Q must return to the last edited file"
);
assert_eq!(app.editor.cursor_row, 2, "and to the edited row");
}
/// Issue #209: VS Code's Reopen Closed Editor. Closing a tab records it;
/// Cmd+K Shift+W restores the most recently closed tab with its cursor
/// position, LIFO across multiple closes.
#[test]
fn cmd_k_shift_w_reopens_the_last_closed_tab_with_its_cursor() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.rs");
let b = tmp.path().join("b.rs");
std::fs::write(&a, "fn a() {}\nfn a2() {}\n").unwrap();
std::fs::write(&b, "fn b() {}\nfn b2() {}\nfn b3() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.editor.open_pinned(&b).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 2;
// Close b.rs (active), then a.rs, both through the keyboard path.
app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(app.editor.path.as_deref(), Some(a.as_path()));
app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
.unwrap();
// Reopen walks the closes in reverse order: a.rs first, then b.rs
// with its remembered cursor row.
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('W'), KeyModifiers::SHIFT))
.unwrap();
assert_eq!(
app.editor.path.as_deref(),
Some(a.as_path()),
"the first reopen restores the most recent close"
);
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('W'), KeyModifiers::SHIFT))
.unwrap();
assert_eq!(
app.editor.path.as_deref(),
Some(b.as_path()),
"the second reopen walks back to the earlier close"
);
assert_eq!(
app.editor.cursor_row, 2,
"the reopened tab must restore its cursor row"
);
}
/// A closed tab whose file has since vanished is skipped, falling through
/// to the next reopenable entry rather than failing.
#[test]
fn reopen_closed_tab_skips_files_deleted_since_the_close() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.rs");
let b = tmp.path().join("b.rs");
std::fs::write(&a, "fn a() {}\n").unwrap();
std::fs::write(&b, "fn b() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.editor.open_pinned(&b).unwrap();
app.focus_pane(Pane::Editor);
// Close b.rs then a.rs; both are recorded (a.rs closes down to the
// blank buffer, which still counts as closing the tab).
app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
.unwrap();
// The stack top is a.rs (the last close); deleting IT forces the
// missing-file skip down to b.rs.
std::fs::remove_file(&a).unwrap();
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('W'), KeyModifiers::SHIFT))
.unwrap();
assert_eq!(
app.editor.path.as_deref(),
Some(b.as_path()),
"a vanished top entry is skipped and the next closed tab reopens"
);
}
/// Close Others records every unpinned tab it drops, so each can be
/// reopened in most-recent-first order.
#[test]
fn close_others_records_the_dropped_tabs_for_reopen() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.rs");
let b = tmp.path().join("b.rs");
let c = tmp.path().join("c.rs");
for f in [&a, &b, &c] {
std::fs::write(f, "x\n").unwrap();
}
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.editor.open_pinned(&b).unwrap();
app.editor.open_pinned(&c).unwrap();
let keep = app.editor.active_index();
app.dispatch_menu_action(MenuAction::CloseOtherTabs(keep), tmp.path().to_path_buf());
assert_eq!(app.editor.tab_count(), 1, "only c.rs survives");
app.reopen_closed_tab();
assert_eq!(
app.editor.path.as_deref(),
Some(b.as_path()),
"the last-recorded dropped tab reopens first"
);
app.reopen_closed_tab();
assert_eq!(app.editor.path.as_deref(), Some(a.as_path()));
}
/// Tab context "Close All" must close the tabs in EVERY split group, not
/// just the clicked one. With files open side by side (e.g. `cgr
/// duplicates`), it used to empty only the focused group, whose blank pane
/// then collapsed away and promoted the other group — so it looked like a
/// single tab closed.
#[test]
fn close_all_closes_every_split_group() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.rs");
let b = tmp.path().join("b.rs");
for f in [&a, &b] {
std::fs::write(f, "x\n").unwrap();
}
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.split_editor(); // right group (focused) duplicates a.rs
app.editor.open_pinned(&b).unwrap();
assert!(app.editor_layout.is_split(), "two groups before Close All");
let total: usize = std::iter::once(&app.editor)
.chain(app.editor_layout.inactive_groups())
.map(|g| g.editors.len())
.sum();
assert!(total >= 2, "tabs are spread over both groups");
app.dispatch_menu_action(MenuAction::CloseAllTabs, tmp.path().to_path_buf());
assert!(
!app.editor_layout.is_split(),
"Close All collapses the split back to a single group"
);
assert_eq!(app.editor.tab_count(), 1, "a single blank pane remains");
assert_eq!(app.editor.path, None, "no file stays open in any group");
assert_eq!(app.status, format!("Closed {total} tabs"));
}
#[test]
fn cmd_k_arms_leader_then_unmatched_second_key_clears_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
assert!(app.cmd_k_leader.is_some(), "Cmd+K arms the chord leader");
// A key that completes no Cmd+K chord clears the leader and falls through
// to its normal meaning.
app.handle_key(key(KeyCode::Char('q'), KeyModifiers::NONE))
.unwrap();
assert!(
app.cmd_k_leader.is_none(),
"an unmatched second key clears the leader"
);
}
#[test]
fn cmd_k_leader_is_super_only_off_termux_so_ctrl_k_stays_kill_to_eol() {
// The Cmd+K chord leader must arm on SUPER (macOS / forwarded), but NOT on
// a bare Ctrl+K off Termux — Ctrl+K is the editor's kill-to-end-of-line and
// must not be shadowed by the leader. (On Termux, Ctrl is the documented
// cmd surrogate, so the leader does claim Ctrl+K there.)
assert!(is_cmd_k_leader_key(key(
KeyCode::Char('k'),
KeyModifiers::SUPER
)));
assert!(
!is_cmd_k_leader_key(key(KeyCode::Char('k'), KeyModifiers::CONTROL)),
"bare Ctrl+K off Termux must fall through to kill-to-end-of-line, not arm the leader"
);
}
#[test]
fn cmd_k_then_s_selects_active_file_for_compare() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("a.txt");
std::fs::write(&f, "v1").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.path = Some(f.clone());
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
assert!(
app.cmd_k_leader.is_none(),
"the chord consumes the armed leader"
);
assert_eq!(app.compare_anchor.as_deref(), Some(f.as_path()));
}
#[test]
fn ctrl_d_again_on_same_file_clears_the_anchor() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("a.txt");
std::fs::write(&f, "v1").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let idx = app.tree.nodes.iter().position(|n| n.path == f).unwrap();
app.tree.selected = idx;
app.handle_key(key(KeyCode::Char('d'), KeyModifiers::CONTROL))
.unwrap();
app.handle_key(key(KeyCode::Char('d'), KeyModifiers::CONTROL))
.unwrap();
assert!(app.compare_anchor.is_none(), "second press toggles off");
}
#[test]
fn ctrl_d_with_anchor_on_other_file_opens_a_diff_tab() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
let b = tmp.path().join("b.txt");
std::fs::write(&a, "alpha\nbravo\n").unwrap();
std::fs::write(&b, "alpha\nBRAVO\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let a_idx = app.tree.nodes.iter().position(|n| n.path == a).unwrap();
let b_idx = app.tree.nodes.iter().position(|n| n.path == b).unwrap();
// Anchor a.txt.
app.tree.selected = a_idx;
app.handle_key(key(KeyCode::Char('d'), KeyModifiers::CONTROL))
.unwrap();
// Move to b.txt and press again.
app.tree.selected = b_idx;
app.handle_key(key(KeyCode::Char('d'), KeyModifiers::CONTROL))
.unwrap();
assert!(app.compare_anchor.is_none(), "anchor consumed by compare");
assert!(app.editor.diff.is_some(), "editor must now hold a diff tab");
}
#[test]
fn left_right_arrows_pan_diff_horizontally() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f1 = tmp.path().join("a.txt");
let f2 = tmp.path().join("b.txt");
let long_line: String = std::iter::repeat_n('x', 200).collect();
std::fs::write(&f1, format!("{long_line}\n")).unwrap();
std::fs::write(&f2, format!("{long_line}y\n")).unwrap();
app.editor.open_diff(&f1, &f2).unwrap();
app.editor.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 12,
};
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.diff.as_ref().unwrap().scroll_x, 4);
app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.diff.as_ref().unwrap().scroll_x, 8);
app.handle_key(key(KeyCode::Left, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.diff.as_ref().unwrap().scroll_x, 4);
// Vertical Up/Down still go to diff.scroll, not scroll_x.
let before_y = app.editor.diff.as_ref().unwrap().scroll;
app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
.unwrap();
assert!(app.editor.diff.as_ref().unwrap().scroll >= before_y);
}
#[test]
fn mouse_horizontal_wheel_over_diff_pans_horizontally() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f1 = tmp.path().join("a.txt");
let f2 = tmp.path().join("b.txt");
let long: String = std::iter::repeat_n('z', 120).collect();
std::fs::write(&f1, format!("{long}\n")).unwrap();
std::fs::write(&f2, format!("{long}\n")).unwrap();
app.editor.open_diff(&f1, &f2).unwrap();
app.editor.last_area = Rect {
x: 0,
y: 0,
width: 80,
height: 20,
};
app.editor.last_full_area = app.editor.last_area;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::ScrollRight,
column: 5,
row: 5,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.editor.diff.as_ref().unwrap().scroll_x, 4);
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::ScrollLeft,
column: 5,
row: 5,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.editor.diff.as_ref().unwrap().scroll_x, 0);
}
#[test]
fn dragging_editor_horizontal_scrollbar_pans_the_buffer() {
// The editor paints a horizontal scrollbar on its bottom row when the
// longest line overflows the text column. Clicking and dragging its thumb
// must move scroll_col, and releasing must end the drag.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f = tmp.path().join("long.txt");
let long: String = std::iter::repeat_n('z', 500).collect();
std::fs::write(&f, format!("{long}\n")).unwrap();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
let backend = ratatui::backend::TestBackend::new(80, 24);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let bar = app.editor.last_hscrollbar;
assert!(
bar.width > 0 && bar.height == 1,
"an overflowing line must paint a horizontal scrollbar"
);
// Click-drag the thumb to the far-right end of the track.
let right_x = bar.x + bar.width - 1;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: right_x,
row: bar.y,
modifiers: KeyModifiers::NONE,
});
assert!(
app.editor.scroll_col > 0,
"clicking the right of the track must pan right"
);
let after_down = app.editor.scroll_col;
// Dragging back to the left edge pans back to column 0.
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
column: bar.x,
row: bar.y,
modifiers: KeyModifiers::NONE,
});
assert_eq!(
app.editor.scroll_col, 0,
"dragging to the left edge pans home"
);
assert_ne!(after_down, app.editor.scroll_col);
// Release ends the drag so later moves don't keep panning.
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
column: bar.x,
row: bar.y,
modifiers: KeyModifiers::NONE,
});
assert!(
!app.editor_hscrollbar_drag,
"releasing must clear the drag flag"
);
}
#[test]
fn mouse_wheel_over_search_panel_scrolls_the_results_list() {
// User report: search shows thousands of matches piling up but
// the panel can't be scrolled with the wheel - the user is stuck
// at the top. The result list must respond to ScrollUp/ScrollDown
// when the cursor is over the side panel and Search is the
// active view.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_view = SidebarView::Search;
app.show_tree = true;
// Pretend a render captured the search panel at this rect.
app.search.last_area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
app.search.last_inner = Rect {
x: 1,
y: 1,
width: 58,
height: 28,
};
// 1000 hits, well past anything that can fit in 30 rows.
app.search.hits = (0..1000)
.map(|i| crate::widgets::search::SearchHit {
path: tmp.path().join("a.txt"),
line_no: i + 1,
line_text: format!("line {i}"),
})
.collect();
app.search.scroll = 0;
app.search.selected = 0;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::ScrollDown,
column: 30,
row: 15,
modifiers: KeyModifiers::NONE,
});
assert!(
app.search.scroll > 0,
"wheel-down on the search panel must advance the result list scroll"
);
let after_down = app.search.scroll;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::ScrollUp,
column: 30,
row: 15,
modifiers: KeyModifiers::NONE,
});
assert!(
app.search.scroll < after_down,
"wheel-up must reduce the scroll back toward the top"
);
}
/// `diff_worktree_lane` refuses rather than diffing the wrong thing, and
/// each refusal names its own reason (#348).
///
/// The three arms are separate because they need separate answers: the
/// primary folder is not a lane at all, a lane pane may not be open for
/// this root, and a lane made before the base was recorded has nothing to
/// diff against. Collapsing them would tell the user to fix the wrong
/// thing.
#[test]
fn diffing_a_lane_refuses_when_there_is_no_base_to_diff_against() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// The primary folder is not a lane.
app.diff_worktree_lane();
assert_eq!(app.graph_revspec, None, "no diff was set up");
assert!(
app.status.contains("not a lane"),
"the primary folder says so: {}",
app.status
);
// A non-primary root with no lane pane recorded for it.
let lane_dir = tmp.path().join("lane");
std::fs::create_dir_all(&lane_dir).unwrap();
app.active_scm_root = lane_dir.clone();
app.diff_worktree_lane();
assert_eq!(app.graph_revspec, None);
assert!(
app.status.contains("No lane is open"),
"an unrecorded root says so: {}",
app.status
);
// A lane whose base was never recorded (made before #348, or cut from a
// detached HEAD).
app.lane_panes.insert(
1,
crate::terminal_session::LaneRecord {
path: lane_dir.to_string_lossy().into_owned(),
branch: String::from("agent/fix"),
agent: None,
base: None,
},
);
app.diff_worktree_lane();
assert_eq!(
app.graph_revspec, None,
"no base means no diff, not a diff against something else"
);
assert!(
app.status.contains("no base branch"),
"a baseless lane says so: {}",
app.status
);
// With a base recorded, the range is the lane against what it was cut
// from - the positive control that the refusals above are refusals and
// not just an inert function.
app.lane_panes.insert(
1,
crate::terminal_session::LaneRecord {
path: lane_dir.to_string_lossy().into_owned(),
branch: String::from("agent/fix"),
agent: None,
base: Some(String::from("main")),
},
);
app.diff_worktree_lane();
assert_eq!(
app.graph_revspec,
Some(String::from("main..agent/fix")),
"the range is base..lane"
);
}
/// The lane diff belongs to the root it was asked for, and does not outlive
/// it (#348).
///
/// `branch_history_range` answers an unresolvable range with an EMPTY vec
/// rather than an error, so a revspec carried into another repo - or kept
/// after the lane is gone - renders a repo with commits as having none,
/// with nothing on screen saying why.
#[test]
fn switching_roots_drops_the_lane_diff() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let other = tmp.path().join("other");
std::fs::create_dir_all(&other).unwrap();
app.graph_revspec = Some(String::from("main..agent/fix"));
app.seed_active_scm(other);
assert_eq!(
app.graph_revspec, None,
"a lane diff must not follow the user into another repository"
);
}
/// A background history refresh must not replace a lane diff (#348).
///
/// The reply tag carries the revspec as well as the root, because both
/// views are for the SAME root and the root alone cannot tell them apart.
/// Pinned against a positive value: the panel starts holding the lane
/// diff's own row, so a dropped reply and an accepted one differ in what
/// is on screen, not merely in timing.
#[test]
fn a_history_reply_does_not_replace_the_lane_diff() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
while app.graph_fetch_inflight {
app.sync_explorer_panels();
assert!(
std::time::Instant::now() < deadline,
"startup graph fetch must settle"
);
std::thread::sleep(std::time::Duration::from_millis(10));
}
let row = |hash: &str, summary: &str| crate::git::GraphCommit {
hash: String::from(hash),
short_hash: hash[..7.min(hash.len())].to_string(),
parents: Vec::new(),
refs: Vec::new(),
summary: String::from(summary),
author: String::from("t"),
age_secs: 0,
};
app.sidebar_view = SidebarView::SourceControl;
app.show_tree = true;
app.source_control.status.in_repo = true;
// The lane diff is up and showing its own commit.
app.graph_revspec = Some(String::from("main..lane"));
app.commit_graph
.set_rows(crate::widgets::commit_graph::layout_graph(vec![row(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"the lane commit",
)]));
// `commit_at` is a click hit-test and needs rendered geometry, so read
// the top row the way a click would - after a draw.
let backend = ratatui::backend::TestBackend::new(100, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
let shown = |app: &mut App, term: &mut ratatui::Terminal<ratatui::backend::TestBackend>| {
term.draw(|frame| app.render(frame)).unwrap();
let area = app.commit_graph.last_area;
app.commit_graph
.commit_at(area.y + 2)
.map(|c| c.hash.clone())
};
let lane_hash = shown(&mut app, &mut term);
assert_eq!(
lane_hash,
Some(String::from("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")),
"the lane diff must be on screen first"
);
// A plain history reply for the SAME root arrives (revspec None) carrying
// a DIFFERENT commit. Same root, different view: the tag must drop it.
app.graph_tx
.send((
app.active_scm_root.clone(),
None,
crate::widgets::commit_graph::layout_graph(vec![row(
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"a background history refresh",
)]),
))
.unwrap();
app.sync_explorer_panels();
assert_eq!(
shown(&mut app, &mut term),
lane_hash,
"a history reply must not replace the lane diff the user asked for"
);
// The matching reply IS taken, so the drop above is the tag working
// rather than the channel being dead.
app.graph_tx
.send((
app.active_scm_root.clone(),
Some(String::from("main..lane")),
crate::widgets::commit_graph::layout_graph(vec![row(
"cccccccccccccccccccccccccccccccccccccccc",
"the refreshed lane diff",
)]),
))
.unwrap();
app.sync_explorer_panels();
assert_eq!(
shown(&mut app, &mut term),
Some(String::from("cccccccccccccccccccccccccccccccccccccccc")),
"a reply for the view that IS up must land"
);
}
#[test]
fn mouse_wheel_over_the_commits_graph_scrolls_it() {
// Codeberg #41: the COMMITS section cannot be scrolled. The graph
// renders BELOW the change list in its own strip, outside
// source_control.last_area, so the sidebar hit-test (`in_tree`)
// never matched and wheel events over the graph fell through.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_view = SidebarView::SourceControl;
app.show_tree = true;
app.source_control.status.in_repo = true;
let commits: Vec<crate::git::GraphCommit> = (0..100)
.map(|i| crate::git::GraphCommit {
hash: format!("{i:040x}"),
short_hash: format!("{i:07x}"),
parents: vec![format!("{:040x}", i + 1)],
refs: Vec::new(),
summary: format!("commit {i}"),
author: String::from("t"),
age_secs: 0,
})
.collect();
app.commit_graph
.set_rows(crate::widgets::commit_graph::layout_graph(commits));
let backend = ratatui::backend::TestBackend::new(100, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let area = app.commit_graph.last_area;
assert!(area.height > 3, "the COMMITS section must render");
let (col, row) = (area.x + 2, area.y + 2);
assert!(
!rect_contains(app.source_control.last_area, col, row),
"the probe cell must sit in the graph strip, below the change list"
);
let before = app
.commit_graph
.commit_at(row)
.expect("probe row must land on a commit")
.hash
.clone();
app.handle_mouse(mouse(
crossterm::event::MouseEventKind::ScrollDown,
col,
row,
));
let after = app
.commit_graph
.commit_at(row)
.expect("scrolled probe row must still land on a commit")
.hash
.clone();
assert_ne!(
before, after,
"wheel-down over the COMMITS section must scroll the graph"
);
app.handle_mouse(mouse(crossterm::event::MouseEventKind::ScrollUp, col, row));
assert_eq!(
app.commit_graph.commit_at(row).map(|c| c.hash.clone()),
Some(before),
"wheel-up must scroll the graph back to the top"
);
}
#[test]
fn a_graph_refresh_swallowed_by_an_inflight_fetch_refires_when_the_reply_drains() {
// Make Root during an in-flight COMMITS fetch: set_root clears the
// panel and triggers a refresh, but the inflight latch swallows it,
// and the old root's reply is then dropped by the drain's root tag.
// Without a queued re-fire nothing refetches until HEAD next moves,
// so the panel sits on "Loading" indefinitely.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Settle any startup fetch so the latch state is ours alone.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
while app.graph_fetch_inflight {
app.sync_explorer_panels();
assert!(
std::time::Instant::now() < deadline,
"startup graph fetch must settle"
);
std::thread::sleep(std::time::Duration::from_millis(10));
}
// A fetch is mid-flight for the old root when the trigger arrives; the
// root change has cleared the panel back to "Loading".
app.commit_graph.clear();
app.graph_fetch_inflight = true;
app.refresh_commit_graph();
// The stale reply lands: dropped by the root tag.
app.graph_tx
.send((
std::path::PathBuf::from("/since-left/root"),
None,
Vec::new(),
))
.unwrap();
// The re-fire is the contract, but the inflight latch is transient: the
// drain that re-fires can also drain the re-fired worker's reply in the
// SAME call (an empty root answers in microseconds), legitimately
// clearing the latch again. Poll the resolved outcome instead: the
// cleared panel must leave "Loading" with rows for the CURRENT root.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
while !app.commit_graph.is_loaded() {
app.sync_explorer_panels();
assert!(
std::time::Instant::now() < deadline,
"the trigger swallowed during flight must re-fire once the stale reply drains"
);
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
#[test]
fn commits_graph_scrollbar_thumb_drag_follows_the_pointer() {
// Codeberg #41 companion: every other sidebar section's scrollbar
// supports a thumb drag (outline, timeline, testing, …); the COMMITS
// graph's must too, not just a single jump-click.
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_view = SidebarView::SourceControl;
app.show_tree = true;
app.source_control.status.in_repo = true;
let commits: Vec<crate::git::GraphCommit> = (0..100)
.map(|i| crate::git::GraphCommit {
hash: format!("{i:040x}"),
short_hash: format!("{i:07x}"),
parents: vec![format!("{:040x}", i + 1)],
refs: Vec::new(),
summary: format!("commit {i}"),
author: String::from("t"),
age_secs: 0,
})
.collect();
app.commit_graph
.set_rows(crate::widgets::commit_graph::layout_graph(commits));
let backend = ratatui::backend::TestBackend::new(100, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let bar = app.commit_graph.last_scrollbar;
assert!(
bar.width > 0 && bar.height > 2,
"100 commits in a capped strip must draw a scrollbar"
);
let body_row = app.commit_graph.last_area.y + 2;
let top = app
.commit_graph
.commit_at(body_row)
.expect("probe row must land on a commit")
.hash
.clone();
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), bar.x, bar.y));
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
bar.x,
bar.y + bar.height - 1,
));
assert_ne!(
app.commit_graph.commit_at(body_row).map(|c| c.hash.clone()),
Some(top),
"dragging the thumb to the lane's bottom must scroll the graph"
);
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), bar.x, bar.y));
}
#[test]
fn search_panel_paints_a_scrollbar_when_hits_exceed_visible_rows() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_view = SidebarView::Search;
app.show_tree = true;
app.search.hits = (0..500)
.map(|i| crate::widgets::search::SearchHit {
path: tmp.path().join("a.txt"),
line_no: i + 1,
line_text: format!("line {i}"),
})
.collect();
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut app.search, area, &mut buf);
assert!(
app.search.last_scrollbar.width > 0 && app.search.last_scrollbar.height > 0,
"scrollbar rect must be tracked when results overflow the viewport"
);
}
#[test]
fn mouse_wheel_over_diff_scrolls_the_diff_not_the_text_buffer() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f1 = tmp.path().join("a.txt");
let f2 = tmp.path().join("b.txt");
std::fs::write(&f1, "1\n2\n3\n4\n5\n6\n").unwrap();
std::fs::write(&f2, "1\n2\n3\n4\n5\n6\n").unwrap();
app.editor.open_diff(&f1, &f2).unwrap();
// Place the editor pane somewhere the mouse can hit it.
app.editor.last_area = Rect {
x: 0,
y: 0,
width: 80,
height: 20,
};
app.editor.last_full_area = app.editor.last_area;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::ScrollDown,
column: 5,
row: 5,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.editor.diff.as_ref().unwrap().scroll, 3);
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::ScrollUp,
column: 5,
row: 5,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.editor.diff.as_ref().unwrap().scroll, 0);
}
#[test]
fn menu_item_at_handles_clipped_menu_so_clicks_dispatch_the_visible_row() {
// Repro: with a 5-item menu (Cut, Copy, Rename…, Select for
// Compare, Delete), if the user right-clicks low enough that
// the menu must shift up by 1 to fit on screen, a click on the
// visible "Select for Compare" row used to map to "Rename"
// because hit-testing used the unclipped rect while rendering
// used the clipped one.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Frame is 60 wide, 12 tall. Menu has 7 items + 2 borders = 9
// rows. Origin at y=6 would make the menu run from row 6 to row
// 14 (off-screen). The renderer (and hit-test) clamp y to
// 12 - 9 = 3.
app.last_frame_area = Rect {
x: 0,
y: 0,
width: 60,
height: 12,
};
let f = tmp.path().join("file.txt");
std::fs::write(&f, "x").unwrap();
let n = crate::widgets::file_tree::Node {
path: f.clone(),
depth: 1,
is_dir: false,
expanded: false,
loaded: true,
};
let target = f.parent().unwrap().to_path_buf();
let items = build_tree_context_menu_items(
Some(&n),
tmp.path(),
std::slice::from_ref(&f),
&target,
None,
None,
);
// Sanity: items[5] is "Select for Compare" after the New
// File… / New Folder prefix lifted everything down by two.
assert!(matches!(&items[5].1, MenuAction::SelectForCompare(_)));
app.context_menu = Some(ContextMenu::flat((10, 6), items, target));
// The visible "Select for Compare" row sits at clipped.y + 1
// (top border) + 5 (item index) = 3 + 1 + 5 = 9.
let idx = app
.menu_item_at(11, 9)
.expect("hit must land inside the menu");
assert_eq!(
idx, 5,
"click on visible row 9 must map to item 5 (Select for Compare)"
);
}
#[test]
fn tree_context_menu_offers_compare_with_selected_when_anchor_is_present() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
std::fs::write(&a, "v1").unwrap();
let b = tmp.path().join("b.txt");
std::fs::write(&b, "v2").unwrap();
let n = file_node(&b);
let items = build_tree_context_menu_items(
Some(&n),
tmp.path(),
std::slice::from_ref(&b),
tmp.path(),
None,
Some(a.as_path()),
);
let kinds: Vec<&MenuAction> = items.iter().map(|(_, a)| a).collect();
assert!(
kinds
.iter()
.any(|a| matches!(a, MenuAction::CompareWithSelected { .. })),
"Compare with Selected must be offered when an anchor is set"
);
assert!(
kinds
.iter()
.any(|a| matches!(a, MenuAction::SelectForCompare(_))),
"Select for Compare must always be offered for single files"
);
}
#[test]
fn tree_context_menu_hides_compare_when_anchor_is_the_same_file() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
std::fs::write(&a, "v1").unwrap();
let n = file_node(&a);
let items = build_tree_context_menu_items(
Some(&n),
tmp.path(),
std::slice::from_ref(&a),
tmp.path(),
None,
Some(a.as_path()),
);
let kinds: Vec<&MenuAction> = items.iter().map(|(_, a)| a).collect();
assert!(
!kinds
.iter()
.any(|a| matches!(a, MenuAction::CompareWithSelected { .. })),
"Compare with Selected must not appear against itself"
);
}
#[test]
fn tree_context_menu_with_two_files_offers_compare_selected() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
std::fs::write(&a, "v1").unwrap();
let b = tmp.path().join("b.txt");
std::fs::write(&b, "v2").unwrap();
let n = file_node(&a);
let items = build_tree_context_menu_items(
Some(&n),
tmp.path(),
&[a.clone(), b.clone()],
tmp.path(),
None,
None,
);
let compare = items
.iter()
.find(|(s, _)| s == "Compare Selected")
.expect("Compare Selected must be offered for a two-file selection");
assert!(matches!(
compare.1,
MenuAction::CompareWithSelected { ref anchor, ref other }
if anchor == &a && other == &b
));
}
#[test]
fn tree_context_menu_hides_compare_selected_when_a_folder_is_selected() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
std::fs::write(&a, "v1").unwrap();
let d = tmp.path().join("dir");
std::fs::create_dir(&d).unwrap();
let n = file_node(&a);
let items = build_tree_context_menu_items(
Some(&n),
tmp.path(),
&[a.clone(), d.clone()],
tmp.path(),
None,
None,
);
assert!(
!items.iter().any(|(s, _)| s == "Compare Selected"),
"Compare Selected must not appear when the selection includes a folder"
);
}
#[test]
fn tree_context_menu_with_multi_selection_promotes_delete_count() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("hello.txt");
std::fs::write(&f, "hi").unwrap();
let f2 = tmp.path().join("bye.txt");
std::fs::write(&f2, "bye").unwrap();
let n = file_node(&f);
let target = f.parent().unwrap().to_path_buf();
let items = build_tree_context_menu_items(
Some(&n),
tmp.path(),
&[f.clone(), f2.clone()],
&target,
None,
None,
);
let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
assert_eq!(
labels,
[
"New File",
"New Folder",
"Cut",
"Copy",
"Compare Selected",
"Delete 2 items"
],
);
}
#[test]
fn tree_context_menu_on_empty_space_offers_new_file_and_new_folder_only() {
let tmp = tempfile::tempdir().unwrap();
let items = build_tree_context_menu_items(None, tmp.path(), &[], tmp.path(), None, None);
let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
assert_eq!(labels, ["New File", "New Folder"]);
assert!(matches!(items[0].1, MenuAction::Create(CreateKind::File)));
assert!(matches!(items[1].1, MenuAction::Create(CreateKind::Folder)));
}
#[test]
fn tree_context_menu_on_empty_space_includes_paste_when_clipboard_set() {
let tmp = tempfile::tempdir().unwrap();
let clip = ExplorerClipboard {
mode: ExplorerClipMode::Copy,
paths: vec![tmp.path().join("x.txt")],
};
let items = build_tree_context_menu_items(None, tmp.path(), &[], tmp.path(), Some(&clip), None);
let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
assert_eq!(labels, ["New File", "New Folder", "Paste"]);
}
#[test]
fn consume_welcome_image_clear_fires_once_when_editor_opens_a_file() {
// Repro for the "logo bleeds through under an open file" bug:
// after the welcome OSC-1337 has been written to iTerm, opening a
// file must signal a one-shot screen clear so ratatui repaints
// every cell on the next draw and iTerm's image cache for those
// cells is wiped.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.welcome.set_displayed(true);
let f = tmp.path().join("hi.txt");
std::fs::write(&f, "hi").unwrap();
app.editor.open_pinned(&f).unwrap();
assert!(app.consume_welcome_image_clear(), "first call must fire");
assert!(
!app.overlays.welcome.is_displayed(),
"flag must reset after consume"
);
assert!(
!app.consume_welcome_image_clear(),
"second call must be a no-op until welcome is re-shown"
);
}
#[test]
fn consume_welcome_image_clear_is_noop_while_editor_pane_is_blank() {
// The image is still meant to be visible, so don't clear.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.welcome.set_displayed(true);
assert!(!app.consume_welcome_image_clear());
assert!(
app.overlays.welcome.is_displayed(),
"flag must NOT reset while image is still meant to show"
);
}
#[test]
fn consume_welcome_image_clear_handles_reposition_request_while_blank() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.welcome.set_displayed(true);
app.overlays.welcome.request_clear();
assert!(app.consume_welcome_image_clear());
assert!(!app.overlays.welcome.is_displayed());
assert!(!app.overlays.welcome.clear_requested());
}
#[test]
fn consume_welcome_image_clear_is_noop_when_image_was_never_shown() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.welcome.set_displayed(false);
let f = tmp.path().join("hi.txt");
std::fs::write(&f, "hi").unwrap();
app.editor.open_pinned(&f).unwrap();
assert!(!app.consume_welcome_image_clear());
}
#[test]
fn clicking_source_control_does_not_block_on_git_and_posts_a_changes_request() {
// Regression for the user-reported "Source Control click feels
// sluggish vs the other sidebar icons" bug. The cause was a
// synchronous `git status --porcelain` shell-out from
// `refresh_source_control` running on the UI thread, costing
// 15-50 ms per click on a small repo and 100-300 ms on a large
// one. The fix routes every git status query through a
// background worker; the click path now does a single
// non-blocking `mpsc::Sender::send` and returns within the
// microsecond range.
let tmp = tempfile::tempdir().unwrap();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(tmp.path())
.args(["init", "-q", "-b", "main"])
.output();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(tmp.path())
.args(["config", "user.email", "a@b"])
.status();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(tmp.path())
.args(["config", "user.name", "a"])
.status();
std::fs::write(tmp.path().join("dirty.txt"), "x").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Pretend the worker is idle by draining its initial Status
// response (App::new posts one to seed the badge). This isn't
// strictly required for the assertion but keeps the test from
// racing with that startup reply.
std::thread::sleep(std::time::Duration::from_millis(150));
let _ = app.drain_git_responses();
// The synchronous shell-out used to take 15-50 ms minimum on
// any real machine; an order of magnitude headroom catches the
// regression even on a fast CI box. A single wall-clock sample
// measures the scheduler as much as the code under suite load
// (#57): one preemption between the clock reads adds milliseconds
// with no regression present. The MINIMUM of several attempts is
// immune — a preemption doesn't repeat on every try, while a
// genuine synchronous shell-out fails all of them.
let mut fastest = std::time::Duration::MAX;
for _ in 0..5 {
let started = std::time::Instant::now();
app.set_sidebar_view(SidebarView::SourceControl);
fastest = fastest.min(started.elapsed());
}
assert!(
fastest < std::time::Duration::from_millis(5),
"Source Control click must not block on git; fastest of 5 took {fastest:?}",
);
// The Changes request must have landed on the worker — give it
// up to 2 s to respond, then drain. The response carries the
// single untracked file we wrote above.
let mut got_changes = false;
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
while std::time::Instant::now() < deadline {
if app.drain_git_responses() && !app.source_control.entries.is_empty() {
got_changes = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert!(
got_changes,
"the worker must reply with the dirty file's Changes entry; entries = {:?}",
app.source_control.entries,
);
}
#[test]
fn git_worker_status_response_feeds_the_explorer_ignored_set() {
// End-to-end wiring for the greyed-out gitignored Explorer rows: the
// worker's Status reply carries the ignored set and drain must push it
// into the file tree, where descendants of a collapsed ignored dir
// resolve via the ancestor walk.
let tmp = tempfile::tempdir().unwrap();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(tmp.path())
.args(["init", "-q", "-b", "main"])
.output();
std::fs::write(tmp.path().join(".gitignore"), "build/\n").unwrap();
std::fs::create_dir(tmp.path().join("build")).unwrap();
std::fs::write(tmp.path().join("build/out.txt"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// App::new seeds one Status request; wait for its reply to land.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
while app.tree.ignored.is_empty() && std::time::Instant::now() < deadline {
let _ = app.drain_git_responses();
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert!(
app.tree.is_ignored(&tmp.path().join("build")),
"ignored dir must reach the tree; set = {:?}",
app.tree.ignored,
);
assert!(
app.tree.is_ignored(&tmp.path().join("build/out.txt")),
"descendants of the collapsed ignored dir dim too"
);
assert!(!app.tree.is_ignored(&tmp.path().join(".gitignore")));
}
#[test]
fn resize_arms_a_one_shot_terminal_clear_to_evict_stale_activity_icons() {
// Regression for the activity-bar icon ghosting after a pane reshape.
// iTerm2 keeps OSC-1337 image cells in a layer that survives plain SGR
// overwrites, so on resize the previously-painted icon bitmaps linger and
// the re-emit stamps a second copy on top (the doubled Run/Debug icon).
// A resize must arm the same one-shot `terminal.clear()` the view-change
// path uses, so iTerm2 drops the stale layer before the icons re-emit.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Pretend init_graphics baked the activity-bar icon images — images mode
// is the only state in which the stale layer can exist.
app.overlays.activity.set_images(ActivityBarImages {
explorer_active: String::new(),
explorer_inactive: String::new(),
explorer_hovered: String::new(),
search_active: String::new(),
search_inactive: String::new(),
search_hovered: String::new(),
source_control_active: String::new(),
source_control_inactive: String::new(),
source_control_hovered: String::new(),
remote_active: String::new(),
remote_inactive: String::new(),
remote_hovered: String::new(),
run_debug_active: String::new(),
run_debug_inactive: String::new(),
run_debug_hovered: String::new(),
extensions_active: String::new(),
extensions_inactive: String::new(),
extensions_hovered: String::new(),
testing_active: String::new(),
testing_inactive: String::new(),
testing_hovered: String::new(),
codeql_active: String::new(),
codeql_inactive: String::new(),
codeql_hovered: String::new(),
settings_active: String::new(),
settings_inactive: String::new(),
settings_hovered: String::new(),
layout_sidebar_on: String::new(),
layout_sidebar_on_hover: String::new(),
layout_sidebar_off: String::new(),
layout_sidebar_off_hover: String::new(),
layout_panel_on: String::new(),
layout_panel_on_hover: String::new(),
layout_panel_off: String::new(),
layout_panel_off_hover: String::new(),
layout_customize: String::new(),
layout_customize_hover: String::new(),
});
app.on_resize();
assert!(
app.consume_activity_image_clear(),
"a pane resize must arm exactly one terminal.clear() so iTerm2 evicts the stale OSC-1337 activity-bar image layer",
);
assert!(
!app.consume_activity_image_clear(),
"the clear request must be one-shot — consuming twice in a row returns false",
);
assert!(
app.overlays.activity.dirty(),
"resize must also re-mark the icons dirty so the post-draw flush re-emits them after the clear",
);
}
#[test]
fn activity_bar_icons_moving_within_the_flush_arms_a_one_shot_terminal_clear() {
// Same emit-time move-detection the run-debug headline icon uses, applied
// to the activity bar: when the icon cells shift since the last emit, the
// post-draw flush must arm one terminal.clear() to evict iTerm2's stale
// OSC-1337 image layer instead of stacking a fresh copy on top (the
// doubled-icon ghost). This is trigger-agnostic — it fires for any layout
// shift, not only the Event::Resize path that on_resize covers.
use ratatui::layout::Rect;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.activity.set_images(ActivityBarImages {
explorer_active: String::new(),
explorer_inactive: String::new(),
explorer_hovered: String::new(),
search_active: String::new(),
search_inactive: String::new(),
search_hovered: String::new(),
source_control_active: String::new(),
source_control_inactive: String::new(),
source_control_hovered: String::new(),
remote_active: String::new(),
remote_inactive: String::new(),
remote_hovered: String::new(),
run_debug_active: String::new(),
run_debug_inactive: String::new(),
run_debug_hovered: String::new(),
extensions_active: String::new(),
extensions_inactive: String::new(),
extensions_hovered: String::new(),
testing_active: String::new(),
testing_inactive: String::new(),
testing_hovered: String::new(),
codeql_active: String::new(),
codeql_inactive: String::new(),
codeql_hovered: String::new(),
settings_active: String::new(),
settings_inactive: String::new(),
settings_hovered: String::new(),
layout_sidebar_on: String::new(),
layout_sidebar_on_hover: String::new(),
layout_sidebar_off: String::new(),
layout_sidebar_off_hover: String::new(),
layout_panel_on: String::new(),
layout_panel_on_hover: String::new(),
layout_panel_off: String::new(),
layout_panel_off_hover: String::new(),
layout_customize: String::new(),
layout_customize_hover: String::new(),
});
let place = |app: &mut App, base: u16| {
app.sidebar_areas.explorer_icon = Rect::new(0, base, 2, 1);
app.sidebar_areas.search_icon = Rect::new(0, base + 2, 2, 1);
app.sidebar_areas.source_control_icon = Rect::new(0, base + 4, 2, 1);
app.sidebar_areas.remote_icon = Rect::new(0, base + 6, 2, 1);
app.sidebar_areas.run_debug_icon = Rect::new(0, base + 8, 2, 1);
app.sidebar_areas.extensions_icon = Rect::new(0, base + 10, 2, 1);
app.sidebar_areas.testing_icon = Rect::new(0, base + 12, 2, 1);
};
// First emit at one layout: records the positions, arms no clear.
place(&mut app, 2);
app.overlays.activity.mark_dirty();
app.flush_activity_image_overlays(&[]);
assert!(
!app.consume_activity_image_clear(),
"the first emit has no prior positions to compare, so it must not arm a clear",
);
// A resize recenters the bar — every icon row shifts by one.
place(&mut app, 3);
app.overlays.activity.mark_dirty();
app.flush_activity_image_overlays(&[]);
assert!(
app.consume_activity_image_clear(),
"icons that moved since the last emit must arm one terminal.clear() to evict the stale image layer",
);
assert!(
!app.consume_activity_image_clear(),
"the clear request must be one-shot",
);
}
#[test]
fn leaving_run_debug_after_emitting_the_icon_arms_a_one_shot_terminal_clear() {
// Regression for the bug+play headline icon ghosting on top of
// whichever sidebar replaced Run-Debug. iTerm2's OSC-1337 image
// cells survive plain SGR overwrites, so the welcome / editor
// pipelines arm a `terminal.clear()` on the next render to evict
// them. Run-Debug needs the same gate.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Pretend init_graphics succeeded and the panel emitted the icon
// while the user was on Run-Debug.
app.overlays
.run_debug
.set_image("\x1b]1337;File=...\x07".to_string());
app.set_sidebar_view(SidebarView::RunDebug);
app.run_debug.last_icon_cell = Some((10, 5));
app.flush_run_debug_icon_overlay();
assert!(
app.overlays.run_debug.was_emitted(),
"test setup: the flush must record the emit position"
);
// Switch away. The clear flag must be armed so the main loop's
// OR chain fires `terminal.clear()` once before the next draw.
app.set_sidebar_view(SidebarView::Explorer);
assert!(
app.consume_run_debug_image_clear(),
"leaving Run-Debug after emitting the icon must arm exactly one terminal.clear() so iTerm2's image cells are evicted",
);
assert!(
!app.consume_run_debug_image_clear(),
"the clear request must be one-shot — consuming twice in a row returns false",
);
}
#[test]
fn flush_run_debug_icon_overlay_is_silent_when_panel_is_not_visible() {
// Critical invariant: when the user has switched away from
// Run-Debug, the post-draw flush MUST NOT write any wipe payload
// (no spaces, no replacement OSC). The prior space-stamp wipe
// fired AFTER the redraw and erased the freshly-painted next
// sidebar in those cells. Eviction is now handled exclusively
// by `terminal.clear()` via `consume_run_debug_image_clear`.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays
.run_debug
.set_image("\x1b]1337;File=...\x07".to_string());
app.set_sidebar_view(SidebarView::RunDebug);
app.run_debug.last_icon_cell = Some((10, 5));
app.flush_run_debug_icon_overlay();
assert_eq!(app.overlays.run_debug.last_emitted(), Some((10, 5)));
// Switch away.
app.set_sidebar_view(SidebarView::Explorer);
// The flush in this state must clear last_emitted but emit
// nothing (we can only assert the bookkeeping side effect here;
// the absence of stdout writes is asserted indirectly by the
// function returning early before the write_all call).
app.flush_run_debug_icon_overlay();
assert_eq!(
app.overlays.run_debug.last_emitted(),
None,
"flush on a hidden panel must reset last_emitted so a re-entry primes a fresh emit",
);
}
#[test]
fn run_debug_icon_moving_within_a_visible_panel_arms_a_one_shot_terminal_clear() {
// Regression for the doubled/stacked headline-icon ghost: when the
// panel stays on Run-Debug but a layout change (terminal resize OR an
// internal pane-drag, which never fires Event::Resize) recenters the
// icon, the next flush would emit a fresh OSC-1337 image at the new
// cell while iTerm2 still caches the old one — two overlapping icons.
// The flush must instead detect the move, arm exactly one
// terminal.clear() to evict the stale cells, and skip re-emitting until
// the clear has run (last_emitted reset to None primes a fresh emit).
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays
.run_debug
.set_image("\x1b]1337;File=...\x07".to_string());
app.set_sidebar_view(SidebarView::RunDebug);
app.run_debug.last_icon_cell = Some((10, 5));
app.flush_run_debug_icon_overlay();
assert_eq!(app.overlays.run_debug.last_emitted(), Some((10, 5)));
// A resize / pane-drag recenters the icon to a new cell while the panel
// is still the active, visible Run-Debug view.
app.run_debug.last_icon_cell = Some((3, 2));
app.flush_run_debug_icon_overlay();
assert!(
app.consume_run_debug_image_clear(),
"an icon that moved within the visible panel must arm one terminal.clear() to evict the stale image cells",
);
assert!(
!app.consume_run_debug_image_clear(),
"the clear request must be one-shot",
);
assert_eq!(
app.overlays.run_debug.last_emitted(),
None,
"the move branch must reset last_emitted so the post-clear frame re-emits a single clean icon",
);
}
#[test]
fn tree_context_menu_on_workspace_root_offers_new_file_and_new_folder_only() {
// Right-clicking the workspace root row must NOT offer Rename/Delete
// (the root cannot be renamed or moved to trash from inside croft).
let tmp = tempfile::tempdir().unwrap();
let n = dir_node(tmp.path());
let items = build_tree_context_menu_items(Some(&n), tmp.path(), &[], tmp.path(), None, None);
let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
assert_eq!(labels, ["New File", "New Folder"]);
}
#[test]
fn bracketed_paste_into_search_input_appends_to_query() {
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("foo");
app.handle_paste("bar");
assert_eq!(app.search.query, "foobar");
}
#[test]
fn bracketed_paste_into_search_strips_newlines() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Search);
app.handle_paste("hello\nworld\r\n");
assert_eq!(app.search.query, "helloworld");
}
#[test]
fn search_view_focuses_search_input_not_terminal_or_tree() {
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.handle_key(key(
KeyCode::Char('F'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert!(app.focus == Pane::Tree);
assert!(app.search.focused);
assert!(!app.tree.focused);
assert!(!app.terminal().focused);
}
#[test]
fn cycling_focus_away_from_search_clears_search_focus_flag() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Search);
app.cycle_focus();
assert!(!app.search.focused);
}
#[test]
fn search_editing_shortcuts_route_to_search_only_when_the_search_input_is_focused() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Search);
assert!(
app.focus == Pane::Tree,
"Search view focuses the side panel"
);
app.search.query = String::from("alpha");
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(app.search.selection_range(), Some((0, 5)));
}
#[test]
fn search_visible_does_not_steal_editing_shortcuts_from_a_focused_terminal() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Search);
app.show_terminal = true;
app.focus_pane(Pane::Terminal);
app.search.query = String::from("alpha");
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(
app.search.selection_range(),
None,
"Cmd+A must act on the focused terminal, not the search query"
);
}
#[test]
fn search_visible_routes_cmd_v_to_search_only_when_search_input_focused() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.clipboard_reader = || Some(String::from("needle"));
app.set_sidebar_view(SidebarView::Search);
app.handle_key(key(KeyCode::Char('v'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(app.search.query, "needle");
}
#[test]
fn search_visible_routes_cmd_v_to_terminal_not_search_when_terminal_focused() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.clipboard_reader = || Some(String::from("needle"));
app.set_sidebar_view(SidebarView::Search);
app.show_terminal = true;
app.focus_pane(Pane::Terminal);
app.handle_key(key(KeyCode::Char('v'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(
app.search.query, "",
"Cmd+V must paste into the focused terminal, not leak into the search query"
);
}
#[test]
fn source_control_stages_a_toplevel_entry_from_a_subdir_workspace() {
// #139: porcelain paths are toplevel-relative, but every Source
// Control operation ran `git -C <workspace_root>` with them as
// cwd-relative pathspecs. A workspace rooted in a repo SUBDIR could
// not stage anything living outside that subdir.
let outer = tempfile::tempdir().unwrap();
let repo = outer.path().join("repo");
std::fs::create_dir(&repo).unwrap();
for args in [
vec!["init", "-q", "-b", "main"],
vec!["config", "user.email", "a@b"],
vec!["config", "user.name", "a"],
] {
let ok = std::process::Command::new("git")
.args(["-C"])
.arg(&repo)
.args(&args)
.status()
.map(|s| s.success())
.unwrap_or(false);
assert!(ok, "git setup step failed: {args:?}");
}
std::fs::write(repo.join("seed.txt"), "one\ntwo\n").unwrap();
let sub = repo.join("crates").join("foo");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(sub.join("keep.txt"), "x\n").unwrap();
for args in [vec!["add", "."], vec!["commit", "-qm", "init"]] {
let ok = std::process::Command::new("git")
.args(["-C"])
.arg(&repo)
.args(&args)
.status()
.map(|s| s.success())
.unwrap_or(false);
assert!(ok, "git setup step failed: {args:?}");
}
// A tracked TOPLEVEL file goes dirty while the workspace opens the
// subdirectory two levels down.
std::fs::write(repo.join("seed.txt"), "one\ntwo\nthree\n").unwrap();
let mut app = App::new(sub.clone()).unwrap();
app.refresh_source_control();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
let mut entry_idx = None;
while std::time::Instant::now() < deadline {
let _ = app.drain_git_responses();
if let Some(i) = app
.source_control
.entries
.iter()
.position(|e| e.path == "seed.txt")
{
entry_idx = Some(i);
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
let entry_idx = entry_idx
.expect("the panel lists the toplevel-relative porcelain entry from a subdir workspace");
assert_eq!(
app.scm_root().canonicalize().unwrap(),
repo.canonicalize().unwrap(),
"the discovered repo root rides the status reply"
);
app.stage_source_control_entry(entry_idx);
let staged = std::process::Command::new("git")
.args(["-C"])
.arg(&repo)
.args(["diff", "--cached", "--name-only"])
.output()
.unwrap();
assert!(staged.status.success(), "git diff --cached failed");
assert!(
String::from_utf8_lossy(&staged.stdout).contains("seed.txt"),
"staging from the panel must address the file by its toplevel-relative path; \
`git -C <subdir> add seed.txt` matches nothing"
);
}
#[test]
fn change_workspace_root_into_a_git_subdir_flips_source_control_into_repo_state() {
// Regression for the user's "Make Root into a .git-bearing folder
// doesn't update Source Control" bug: the git worker thread was
// spawned ONCE with the initial root captured by value. After
// change_workspace_root, the worker kept shelling git status
// against the OLD root, so the Source Control panel stayed in
// its no-repo empty state even though the new root was a real
// git tree.
let outer = tempfile::tempdir().unwrap();
let repo = outer.path().join("repo");
std::fs::create_dir(&repo).unwrap();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(&repo)
.args(["init", "-q", "-b", "main"])
.output();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(&repo)
.args(["config", "user.email", "a@b"])
.status();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(&repo)
.args(["config", "user.name", "a"])
.status();
let mut app = App::new(outer.path().to_path_buf()).unwrap();
std::thread::sleep(std::time::Duration::from_millis(150));
let _ = app.drain_git_responses();
assert!(
!app.source_control.status.in_repo,
"preconditions: outer dir must NOT be a git repo"
);
app.change_workspace_root(repo.clone());
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
let mut flipped = false;
while std::time::Instant::now() < deadline {
if app.drain_git_responses() && app.source_control.status.in_repo {
flipped = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert!(
flipped,
"after Make Root into a real git tree the worker must re-query against the new root and the Source Control panel must report in_repo=true; saw status={:?}",
app.source_control.status,
);
assert_eq!(app.source_control.status.branch.as_deref(), Some("main"));
}
fn make_committed_repo() -> tempfile::TempDir {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.email", "a@b"])
.status();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.name", "a"])
.status();
std::fs::write(p.join("seed.txt"), b"seed\n").unwrap();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(p)
.args(["add", "seed.txt"])
.status();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(p)
.args(["commit", "-q", "-m", "init"])
.status();
tmp
}
fn wait_for_changes(app: &mut App, predicate: impl Fn(&App) -> bool) -> bool {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
let mut next_kick = std::time::Instant::now();
while std::time::Instant::now() < deadline {
if std::time::Instant::now() >= next_kick {
app.refresh_source_control();
next_kick = std::time::Instant::now() + std::time::Duration::from_millis(200);
}
app.drain_git_responses();
if predicate(app) {
return true;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
predicate(app)
}
#[test]
fn stage_source_control_entry_runs_git_add_and_flips_kind_to_staged() {
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(
wait_for_changes(&mut app, |a| a
.source_control
.entries
.iter()
.any(
|e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::Modified
)),
"preconditions: seed.txt must appear as Modified"
);
let idx = app
.source_control
.entries
.iter()
.position(|e| e.path == "seed.txt")
.unwrap();
app.stage_source_control_entry(idx);
assert!(
wait_for_changes(&mut app, |a| a
.source_control
.entries
.iter()
.any(
|e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::StagedModified
)),
"after stage_source_control_entry the file must read as StagedModified; saw {:?}",
app.source_control.entries,
);
}
#[test]
fn stage_all_source_control_then_unstage_all_round_trips_every_entry() {
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
std::fs::write(tmp.path().join("fresh.txt"), b"new\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(
wait_for_changes(&mut app, |a| a.source_control.entries.len() >= 2),
"preconditions: both files must show as changes"
);
app.stage_all_source_control();
assert!(
wait_for_changes(&mut app, |a| !a.source_control.entries.is_empty()
&& a.source_control
.entries
.iter()
.all(|e| e.kind.section() == crate::git::ChangeSection::Staged)),
"after Stage All every entry must read as staged; saw {:?}",
app.source_control.entries,
);
app.unstage_all_source_control();
assert!(
wait_for_changes(&mut app, |a| !a.source_control.entries.is_empty()
&& a.source_control
.entries
.iter()
.all(|e| e.kind.section() != crate::git::ChangeSection::Staged)),
"after Unstage All nothing must remain staged; saw {:?}",
app.source_control.entries,
);
}
#[test]
fn discard_all_requires_confirmation_and_then_reverts_tracked_changes() {
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("seed.txt"), b"dirty edit\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| {
a.source_control
.entries
.iter()
.any(|e| e.path == "seed.txt")
});
// Requesting discard-all only arms the confirm modal; the file is untouched.
app.request_discard_all_source_control();
assert!(
app.pending_discard_all,
"Discard All must arm a confirmation rather than act immediately"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("seed.txt")).unwrap(),
"dirty edit\n",
"the working tree must be untouched until the user confirms"
);
app.confirm_pending_discard_all();
assert!(!app.pending_discard_all, "confirming clears the modal");
assert!(
wait_for_changes(&mut app, |_| std::fs::read_to_string(
tmp.path().join("seed.txt")
)
.map(|s| !s.contains("dirty edit"))
.unwrap_or(false)),
"after confirming, the tracked edit must be reverted to HEAD"
);
}
#[test]
fn create_tag_via_the_menu_opens_an_input_then_creates_the_tag() {
use crate::widgets::input_prompt::InputPurpose;
use crate::widgets::scm_menu::ScmAction;
let tmp = make_committed_repo();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.dispatch_scm_action(ScmAction::CreateTag);
let prompt = app
.input_prompt
.as_ref()
.expect("Create Tag must open an input prompt");
assert_eq!(prompt.purpose, InputPurpose::CreateTag);
for c in "v9.9.9".chars() {
app.input_prompt.as_mut().unwrap().push_char(c);
}
app.submit_input_prompt();
assert!(app.input_prompt.is_none(), "submitting closes the prompt");
assert!(
crate::git::list_tags(tmp.path())
.unwrap()
.contains(&"v9.9.9".to_string()),
"the tag must exist after submitting the Create Tag input"
);
}
#[test]
fn delete_branch_via_the_menu_opens_the_branch_picker_in_delete_mode() {
use crate::widgets::scm_menu::ScmAction;
let tmp = make_committed_repo();
crate::git::create_branch(tmp.path(), "doomed").unwrap();
crate::git::checkout_branch(tmp.path(), "main").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.dispatch_scm_action(ScmAction::DeleteBranch);
assert!(
app.branch_picker.is_some(),
"Delete Branch opens the branch picker"
);
assert_eq!(app.branch_purpose, crate::app::BranchPurpose::Delete);
}
/// Drain the network git operation in flight until it lands.
fn wait_for_git_net(app: &mut App) {
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"the network git operation",
|| {
app.drain_git_net();
app.git_net_job.is_none()
},
);
}
/// A push runs on a worker: the call returns with the operation in flight,
/// a second one is refused while it runs, and the result lands on a drain.
#[test]
fn a_push_runs_off_the_ui_thread_and_reports_when_it_lands() {
let tmp = make_committed_repo();
let bare = tempfile::tempdir().unwrap();
let git = |dir: &std::path::Path, args: &[&str]| {
std::process::Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.output()
.unwrap()
};
git(bare.path(), &["init", "-q", "--bare"]);
git(
tmp.path(),
&["remote", "add", "origin", bare.path().to_str().unwrap()],
);
git(tmp.path(), &["push", "-q", "-u", "origin", "main"]);
std::fs::write(tmp.path().join("seed.txt"), b"two\n").unwrap();
git(tmp.path(), &["commit", "-qam", "two"]);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.push_source_control();
assert!(app.git_net_job.is_some(), "the push is in flight");
app.pull_source_control();
assert!(app.status.contains("still running"), "{}", app.status);
wait_for_git_net(&mut app);
assert!(
!app.source_control.commit_feedback_is_error,
"{:?}",
app.source_control.commit_feedback
);
let remote_head = git(bare.path(), &["rev-parse", "main"]).stdout;
let local_head = git(tmp.path(), &["rev-parse", "HEAD"]).stdout;
assert_eq!(remote_head, local_head);
}
/// Opening a config file must not reload the active tab in place: it held
/// unsaved edits to another file, which were silently discarded.
#[test]
fn opening_a_config_file_keeps_the_active_tabs_unsaved_edits() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
std::fs::write(&a, "saved\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.editor.lines = vec![String::from("unsaved")];
app.editor.dirty = true;
let layer = tmp.path().join(".croft").join("config.json");
std::fs::create_dir_all(layer.parent().unwrap()).unwrap();
app.open_config_file_in_editor(layer.clone(), ConfigFileSeed::SettingsLayer);
assert_eq!(app.editor.path.as_deref(), Some(layer.as_path()));
let kept = app
.editor
.editors
.iter()
.find(|e| e.path.as_deref() == Some(a.as_path()))
.expect("a.txt still has its tab");
assert!(kept.dirty);
assert_eq!(kept.lines, vec![String::from("unsaved")]);
}
#[test]
fn bounded_output_gives_up_on_a_command_that_hangs() {
let started = std::time::Instant::now();
let budget = std::time::Duration::from_millis(500);
assert!(
bounded_output(
std::process::Command::new("sh").args(["-c", "sleep 30"]),
budget
)
.is_none()
);
assert!(
bounded_output(
std::process::Command::new("sh").args(["-c", "exec 1>&-; sleep 30"]),
budget
)
.is_none()
);
assert!(started.elapsed() < std::time::Duration::from_secs(10));
let (status, out) = bounded_output(
std::process::Command::new("sh").args(["-c", "printf 42"]),
std::time::Duration::from_secs(10),
)
.unwrap();
assert!(status.success());
assert_eq!(out, b"42");
}
/// The accept shifts the server's ranges by what was typed or deleted since
/// the request, applies the auto-import in the request's coordinates, is one
/// undo step, and credits the text to the server (#349).
#[test]
fn a_completion_accept_tracks_the_caret_and_is_one_generated_undo_step() {
use crate::widgets::editor::TextSpanEdit;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Requested at `abc|)`, then one Backspace: `ab|)`.
app.editor.lines = vec![String::from("ab)")];
app.editor.cursor_row = 0;
app.editor.cursor_col = 2;
app.completion_origin = Some((0, 3));
let item = crate::lsp::CompletionItem {
label: String::from("abcdef"),
text_edit: Some(TextSpanEdit {
start: (0, 0),
end: (0, 3),
new_text: String::from("abcdef"),
utf16: true,
}),
..Default::default()
};
assert!(app.accept_completion_edit(&item));
assert_eq!(app.editor.lines, vec![String::from("abcdef)")]);
assert_eq!(app.editor.cursor_col, 6);
// A same-row additional edit lands where the server meant it, and the
// whole accept is one undo step credited to the server.
app.editor.lines = vec![String::from("x = fo; y"), String::from("z")];
app.editor.provenance = crate::provenance::Provenance::new();
app.editor.cursor_col = 6;
app.completion_origin = Some((0, 6));
let before = app.editor.lines.clone();
let item = crate::lsp::CompletionItem {
label: String::from("foobar"),
text_edit: Some(TextSpanEdit {
start: (0, 4),
end: (0, 6),
new_text: String::from("foobar"),
utf16: true,
}),
additional_edits: vec![TextSpanEdit {
start: (0, 9),
end: (0, 9),
new_text: String::from("Z"),
utf16: true,
}],
..Default::default()
};
assert!(app.accept_completion_edit(&item));
assert_eq!(app.editor.lines[0], "x = foobar; yZ");
assert_eq!(app.editor.cursor_col, 10);
assert_eq!(
app.editor.provenance.seat(0),
Some(&crate::provenance::Seat::Generated)
);
app.editor.undo();
assert_eq!(app.editor.lines, before, "one accept is one undo step");
}
/// A completion is accepted by the server's own edit: TypeScript's `?.foo`
/// replaces the `.` before the word (croft produced `a.?.foo`), letters
/// typed since the request go too, and an auto-import lands with it.
#[test]
fn a_completion_applies_its_text_edit_and_additional_edits() {
use crate::widgets::editor::TextSpanEdit;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.lines = vec![String::from("a.f")];
app.editor.cursor_row = 0;
app.editor.cursor_col = 3;
let item = crate::lsp::CompletionItem {
label: String::from("foo"),
// Requested at `a.` (col 2); `f` was typed since.
text_edit: Some(TextSpanEdit {
start: (0, 1),
end: (0, 2),
new_text: String::from("?.foo"),
utf16: true,
}),
additional_edits: vec![TextSpanEdit {
start: (0, 0),
end: (0, 0),
new_text: String::from("import { x } from 'x';\n"),
utf16: true,
}],
..Default::default()
};
assert!(app.accept_completion_edit(&item));
assert_eq!(
app.editor.lines,
vec![
String::from("import { x } from 'x';"),
String::from("a?.foo")
]
);
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 6));
// No text edit: the prefix path takes over.
assert!(!app.accept_completion_edit(&crate::lsp::CompletionItem::default()));
// A range past the caret replaces the suffix it covers.
app.editor.lines = vec![String::from("fooBar")];
app.editor.cursor_row = 0;
app.editor.cursor_col = 3;
let item = crate::lsp::CompletionItem {
label: String::from("baz"),
text_edit: Some(TextSpanEdit {
start: (0, 0),
end: (0, 6),
new_text: String::from("baz"),
utf16: true,
}),
..Default::default()
};
assert!(app.accept_completion_edit(&item));
assert_eq!(app.editor.lines, vec![String::from("baz")]);
// A snippet takes the same range and imports, and still expands: the
// `.` its range covers goes, and the caret sits on the first tab stop.
app.editor.lines = vec![String::from("a.f")];
app.editor.cursor_row = 0;
app.editor.cursor_col = 3;
let item = crate::lsp::CompletionItem {
label: String::from("foo"),
is_snippet: true,
text_edit: Some(TextSpanEdit {
start: (0, 1),
end: (0, 3),
new_text: String::from("?.foo(${1:x})$0"),
utf16: true,
}),
additional_edits: vec![TextSpanEdit {
start: (0, 0),
end: (0, 0),
new_text: String::from("use x;\n"),
utf16: true,
}],
..Default::default()
};
assert!(app.accept_completion_edit(&item));
assert_eq!(
app.editor.lines,
vec![String::from("use x;"), String::from("a?.foo(x)")]
);
assert_eq!(app.editor.cursor_row, 1);
assert!(app.editor.snippet_active(), "tab stops are live");
}
/// Restoring a snapshot keeps the version it overwrites, even one never
/// snapshotted (an agent's write) or saved seconds ago (inside the merge
/// window, where the restore used to replace and delete it).
#[test]
fn restoring_a_snapshot_keeps_the_version_it_overwrites() {
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("a.rs");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
let now = super::now_millis();
crate::history::record_in(&app.history_root, &f, b"v1\n", now - 60_000).unwrap();
// Saved a second ago, then rewritten by someone else, never snapshotted.
crate::history::record_in(&app.history_root, &f, b"v2\n", now - 1_000).unwrap();
std::fs::write(&f, "v3 by an agent\n").unwrap();
app.history_restore = Some((f.clone(), now - 60_000, b"v1\n".to_vec()));
app.restore_history_snapshot();
assert_eq!(std::fs::read(&f).unwrap(), b"v1\n");
let held: Vec<Vec<u8>> = crate::history::entries_in(&app.history_root, &f)
.iter()
.map(|s| std::fs::read(&s.file).unwrap())
.collect();
assert!(held.contains(&b"v2\n".to_vec()), "{held:?}");
assert!(held.contains(&b"v3 by an agent\n".to_vec()), "{held:?}");
}
#[test]
fn dispatching_fetch_records_a_line_in_the_git_output_log() {
let tmp = make_committed_repo();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.dispatch_scm_action(crate::widgets::scm_menu::ScmAction::Fetch);
wait_for_git_net(&mut app);
assert!(
app.git_output_log.iter().any(|l| l.contains("fetch")),
"every dispatched git op must append to the git output log; saw {:?}",
app.git_output_log,
);
}
#[test]
fn unstage_source_control_entry_runs_git_reset_and_flips_kind_back_to_modified() {
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let idx = {
assert!(
wait_for_changes(&mut app, |a| a
.source_control
.entries
.iter()
.any(
|e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::Modified
)),
"preconditions: seed.txt must appear as Modified"
);
app.source_control
.entries
.iter()
.position(|e| e.path == "seed.txt")
.unwrap()
};
app.stage_source_control_entry(idx);
assert!(
wait_for_changes(&mut app, |a| a
.source_control
.entries
.iter()
.any(
|e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::StagedModified
)),
"preconditions: seed.txt must be staged before we can unstage it"
);
let staged_idx = app
.source_control
.entries
.iter()
.position(|e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::StagedModified)
.unwrap();
app.unstage_source_control_entry(staged_idx);
assert!(
wait_for_changes(&mut app, |a| a
.source_control
.entries
.iter()
.any(
|e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::Modified
)),
"after unstage the file must read as Modified again; saw {:?}",
app.source_control.entries,
);
}
#[test]
fn request_discard_source_control_entry_only_opens_a_confirm_modal_without_touching_disk() {
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| {
a.source_control
.entries
.iter()
.any(|e| e.path == "seed.txt")
});
let idx = app
.source_control
.entries
.iter()
.position(|e| e.path == "seed.txt")
.unwrap();
app.request_discard_source_control_entry(idx);
assert!(
app.pending_discard.is_some(),
"Discard click must request user confirmation rather than discarding immediately"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("seed.txt")).unwrap(),
"changed\n",
"request alone must not touch the working tree"
);
}
#[test]
fn confirming_discard_for_modified_file_restores_head_content() {
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| {
a.source_control
.entries
.iter()
.any(|e| e.path == "seed.txt")
});
let idx = app
.source_control
.entries
.iter()
.position(|e| e.path == "seed.txt")
.unwrap();
app.request_discard_source_control_entry(idx);
app.confirm_pending_discard();
assert!(
app.pending_discard.is_none(),
"modal must close after confirm"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("seed.txt")).unwrap(),
"seed\n",
"discard must restore HEAD content of a Modified file"
);
}
#[test]
fn confirming_discard_for_untracked_file_deletes_it_from_disk() {
let tmp = make_committed_repo();
let new_file = tmp.path().join("scratch.txt");
std::fs::write(&new_file, b"untracked\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| {
a.source_control
.entries
.iter()
.any(|e| e.path == "scratch.txt" && e.kind == crate::git::ChangeKind::Untracked)
});
let idx = app
.source_control
.entries
.iter()
.position(|e| e.path == "scratch.txt")
.unwrap();
app.request_discard_source_control_entry(idx);
assert!(matches!(
app.pending_discard.as_ref(),
Some(pd) if pd.untracked
));
app.confirm_pending_discard();
assert!(
!new_file.exists(),
"discard on an Untracked entry must delete the file from disk"
);
}
#[test]
fn cancel_pending_discard_clears_modal_without_acting() {
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| {
a.source_control
.entries
.iter()
.any(|e| e.path == "seed.txt")
});
let idx = app
.source_control
.entries
.iter()
.position(|e| e.path == "seed.txt")
.unwrap();
app.request_discard_source_control_entry(idx);
app.cancel_pending_discard();
assert!(app.pending_discard.is_none());
assert_eq!(
std::fs::read_to_string(tmp.path().join("seed.txt")).unwrap(),
"changed\n",
"cancel must NOT touch the working tree"
);
}
#[test]
fn clicking_the_stage_icon_on_a_selected_unstaged_row_stages_that_entry() {
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| {
a.source_control
.entries
.iter()
.any(|e| e.path == "seed.txt")
});
app.set_sidebar_view(SidebarView::SourceControl);
let backend = ratatui::backend::TestBackend::new(80, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let idx = app
.source_control
.entries
.iter()
.position(|e| e.path == "seed.txt")
.unwrap();
app.source_control.selected_change = Some(idx);
term.draw(|f| app.render(f)).unwrap();
let actions = app
.source_control
.last_row_actions
.expect("selected unstaged row must expose action rects");
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: actions.stage.x,
row: actions.stage.y,
modifiers: KeyModifiers::NONE,
});
assert!(
wait_for_changes(&mut app, |a| a
.source_control
.entries
.iter()
.any(
|e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::StagedModified
)),
"clicking the stage cell must run `git add` against that entry"
);
}
#[test]
fn clicking_the_discard_icon_on_a_selected_unstaged_row_opens_the_confirm_modal() {
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| {
a.source_control
.entries
.iter()
.any(|e| e.path == "seed.txt")
});
app.set_sidebar_view(SidebarView::SourceControl);
let backend = ratatui::backend::TestBackend::new(80, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let idx = app
.source_control
.entries
.iter()
.position(|e| e.path == "seed.txt")
.unwrap();
app.source_control.selected_change = Some(idx);
term.draw(|f| app.render(f)).unwrap();
let actions = app
.source_control
.last_row_actions
.expect("selected unstaged row must expose action rects");
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: actions.discard.x,
row: actions.discard.y,
modifiers: KeyModifiers::NONE,
});
assert!(
app.pending_discard.is_some(),
"discard click must arm the confirm modal (NEVER discard silently)"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("seed.txt")).unwrap(),
"changed\n",
"discard click alone must NOT touch the working tree until the user confirms"
);
}
#[test]
fn cmd_a_in_source_control_pane_selects_every_change_row() {
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
std::fs::write(tmp.path().join("scratch.txt"), b"new\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| a.source_control.entries.len() >= 2);
app.set_sidebar_view(SidebarView::SourceControl);
let n = app.source_control.entries.len();
app.handle_source_control_key(key(KeyCode::Char('a'), KeyModifiers::SUPER));
assert_eq!(
app.source_control.multi_selection.len(),
n,
"Cmd+A in SC must populate multi_selection with every entry"
);
}
#[test]
fn cmd_s_through_handle_key_dispatches_to_source_control_not_to_editor_save() {
// Regression for the user's "Cmd+S didn't react" report: the
// global `is_save_key` intercept used to fire BEFORE the SC
// handler, so Cmd+S called `App::save` (a no-op when no editor
// file was open) and the user's selected change never moved to
// the index. Route through `handle_key` (not `handle_source_control_key`)
// to exercise the full dispatcher.
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| {
a.source_control
.entries
.iter()
.any(|e| e.path == "seed.txt")
});
app.set_sidebar_view(SidebarView::SourceControl);
app.source_control.select_all_changes();
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
.unwrap();
assert!(
wait_for_changes(&mut app, |a| a
.source_control
.entries
.iter()
.any(
|e| e.path == "seed.txt" && e.kind.section() == crate::git::ChangeSection::Staged
)),
"Cmd+S routed through handle_key must reach the SC stage handler, not the global save key intercept"
);
}
#[test]
fn staging_a_filename_with_a_space_works_after_porcelain_dequoting() {
// Regression for "fatal: pathspec '\"linked_list copy.py\"' did
// not match any files": porcelain output wraps filenames with
// spaces in double quotes, and we used to feed those quotes
// straight into `git add`. The parser now dequotes; the staging
// path must end at the real filename.
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("linked_list copy.py"), b"x\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| {
a.source_control
.entries
.iter()
.any(|e| e.path == "linked_list copy.py")
});
assert!(
!app.source_control
.entries
.iter()
.any(|e| e.path.starts_with('"') || e.path.ends_with('"')),
"no entry's path may still carry the porcelain quoting wrapper"
);
let idx = app
.source_control
.entries
.iter()
.position(|e| e.path == "linked_list copy.py")
.unwrap();
app.stage_source_control_entry(idx);
assert!(
wait_for_changes(&mut app, |a| a
.source_control
.entries
.iter()
.any(|e| e.path == "linked_list copy.py"
&& e.kind.section() == crate::git::ChangeSection::Staged)),
"Staging a file whose name contains a space must succeed; saw status={:?}",
app.status,
);
}
#[test]
fn cmd_s_in_source_control_pane_stages_every_multi_selected_entry() {
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
std::fs::write(tmp.path().join("scratch.txt"), b"new\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| a.source_control.entries.len() >= 2);
app.set_sidebar_view(SidebarView::SourceControl);
app.source_control.select_all_changes();
app.handle_source_control_key(key(KeyCode::Char('s'), KeyModifiers::SUPER));
assert!(
wait_for_changes(&mut app, |a| {
let kinds: Vec<_> = a
.source_control
.entries
.iter()
.map(|e| e.kind.section())
.collect();
!kinds.is_empty()
&& kinds
.iter()
.all(|s| *s == crate::git::ChangeSection::Staged)
}),
"Cmd+S with multi-selection must stage every selected entry; saw {:?}",
app.source_control.entries,
);
}
#[test]
fn cmd_s_with_single_selection_stages_only_that_entry() {
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
std::fs::write(tmp.path().join("scratch.txt"), b"new\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| a.source_control.entries.len() >= 2);
app.set_sidebar_view(SidebarView::SourceControl);
let scratch_idx = app
.source_control
.entries
.iter()
.position(|e| e.path == "scratch.txt")
.unwrap();
// Single click resets multi_selection to just this row.
app.source_control.multi_selection.clear();
app.source_control.multi_selection.insert(scratch_idx);
app.source_control.selected_change = Some(scratch_idx);
app.handle_source_control_key(key(KeyCode::Char('s'), KeyModifiers::SUPER));
assert!(
wait_for_changes(&mut app, |a| a
.source_control
.entries
.iter()
.any(|e| e.path == "scratch.txt"
&& e.kind.section() == crate::git::ChangeSection::Staged)),
"scratch.txt must have been staged"
);
assert!(
app.source_control
.entries
.iter()
.any(|e| e.path == "seed.txt" && e.kind == crate::git::ChangeKind::Modified),
"seed.txt must remain unstaged (single-row stage scope)"
);
}
#[test]
fn cmd_enter_in_source_control_falls_back_to_plain_commit_without_pushing() {
// iTerm2 swallows Cmd+Enter as Toggle Fullscreen so the chord never
// reaches croft. Terminals that DO deliver it should treat Cmd as
// a no-op modifier — Enter alone commits, Ctrl+Enter pushes. The
// SC handler's plain `KeyCode::Enter` match arm catches the
// residual Cmd+Enter and calls `commit_source_control` (no push).
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| {
a.source_control
.entries
.iter()
.any(|e| e.path == "seed.txt")
});
app.set_sidebar_view(SidebarView::SourceControl);
app.source_control.message = "fix: plain cmd-enter".to_string();
app.source_control.message_cursor = app.source_control.message.chars().count();
app.handle_source_control_key(key(KeyCode::Enter, KeyModifiers::SUPER));
let log = std::process::Command::new("git")
.args(["-C"])
.arg(tmp.path())
.args(["log", "--oneline"])
.output()
.unwrap();
let log_out = String::from_utf8_lossy(&log.stdout);
assert!(
log_out.contains("fix: plain cmd-enter"),
"Cmd+Enter must still commit locally (push is bound to Ctrl+Enter only): log={log_out:?}"
);
}
#[test]
fn ctrl_enter_in_source_control_commits_and_pushes() {
let tmp = make_committed_repo();
// Wire a bare remote and set it as origin so `git push` has
// somewhere to send.
let remote = tempfile::tempdir().unwrap();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(remote.path())
.args(["init", "--bare", "-q", "-b", "main"])
.status();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(tmp.path())
.args(["remote", "add", "origin"])
.arg(remote.path())
.status();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(tmp.path())
.args(["push", "-u", "origin", "main"])
.status();
// Make a tracked change and stage it so commit-all-tracked has
// something to commit.
std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| {
a.source_control
.entries
.iter()
.any(|e| e.path == "seed.txt")
});
app.set_sidebar_view(SidebarView::SourceControl);
app.source_control.message = "fix: bump seed".to_string();
app.source_control.message_cursor = app.source_control.message.chars().count();
app.handle_source_control_key(key(KeyCode::Enter, KeyModifiers::CONTROL));
// The push runs on a worker.
wait_for_git_net(&mut app);
// Verify the remote received the commit (its log now reports two
// commits — the initial push + our new one).
let log = std::process::Command::new("git")
.args(["-C"])
.arg(remote.path())
.args(["log", "--oneline"])
.output()
.unwrap();
let log_out = String::from_utf8_lossy(&log.stdout);
assert!(
log_out.lines().count() >= 2,
"Cmd+Enter must have committed AND pushed (remote log: {log_out:?})"
);
assert!(
log_out.contains("fix: bump seed"),
"remote's log must include the new commit's subject"
);
}
#[test]
fn opening_a_modified_file_diff_parks_scroll_on_the_first_change_hunk() {
let tmp = make_committed_repo();
let big = (0..50).map(|i| format!("line {i}\n")).collect::<String>();
std::fs::write(tmp.path().join("seed.txt"), &big).unwrap();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(tmp.path())
.args(["add", "seed.txt"])
.status();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(tmp.path())
.args(["commit", "-q", "-m", "big seed"])
.status();
// Now change a line deep in the file so the first hunk lives well
// past row 0.
let mut lines: Vec<String> = big.lines().map(str::to_string).collect();
lines[30] = "edited-30".to_string();
std::fs::write(tmp.path().join("seed.txt"), lines.join("\n") + "\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| {
a.source_control
.entries
.iter()
.any(|e| e.path == "seed.txt")
});
let idx = app
.source_control
.entries
.iter()
.position(|e| e.path == "seed.txt")
.unwrap();
app.open_source_control_entry(idx);
let diff = app
.editor
.diff
.as_ref()
.expect("opening a Modified entry must build a diff");
assert!(
diff.scroll >= 25 && diff.scroll <= 30,
"diff must auto-scroll near the change (row ~30, with 2-row context above); saw scroll={}",
diff.scroll,
);
}
#[test]
fn f7_in_the_diff_view_jumps_to_the_next_change_hunk() {
let tmp = make_committed_repo();
// Build a multi-hunk file: edits at lines 10 and 40.
let original: String = (0..50).map(|i| format!("line {i}\n")).collect();
std::fs::write(tmp.path().join("seed.txt"), &original).unwrap();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(tmp.path())
.args(["add", "seed.txt"])
.status();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(tmp.path())
.args(["commit", "-q", "-m", "seed"])
.status();
let mut edited: Vec<String> = original.lines().map(str::to_string).collect();
edited[10] = "edited-10".to_string();
edited[40] = "edited-40".to_string();
std::fs::write(tmp.path().join("seed.txt"), edited.join("\n") + "\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| {
a.source_control
.entries
.iter()
.any(|e| e.path == "seed.txt")
});
let idx = app
.source_control
.entries
.iter()
.position(|e| e.path == "seed.txt")
.unwrap();
app.open_source_control_entry(idx);
let first_scroll = app.editor.diff.as_ref().unwrap().scroll;
// F7 jumps to the next hunk.
app.handle_editor_key(key(KeyCode::F(7), KeyModifiers::NONE));
let next_scroll = app.editor.diff.as_ref().unwrap().scroll;
assert!(
next_scroll > first_scroll,
"F7 must advance scroll past the current hunk (saw first={first_scroll}, next={next_scroll})"
);
// Shift+F7 walks back.
app.handle_editor_key(key(KeyCode::F(7), KeyModifiers::SHIFT));
let prev_scroll = app.editor.diff.as_ref().unwrap().scroll;
assert!(
prev_scroll < next_scroll,
"Shift+F7 must walk back to the prior hunk (saw next={next_scroll}, prev={prev_scroll})"
);
}
#[test]
fn forward_diff_jump_wraps_from_the_last_hunk_back_to_the_first() {
// Regression: the › arrow / F7 used to stick on the last hunk when
// that hunk lived in the bottom-clamped region of the diff. The cause
// was that `render_diff` clamps `diff.scroll` to `max_scroll` and
// writes it back, so the next forward jump re-derived an anchor BELOW
// the last hunk and kept re-selecting it instead of wrapping. Backward
// (‹) was unaffected because a too-low anchor still has earlier hunks
// to step through. This test drives forward jumps with a render between
// each (to trigger the clamp) and asserts the forward arrow eventually
// wraps to the first hunk.
let tmp = make_committed_repo();
let original: String = (0..60).map(|i| format!("line {i}\n")).collect();
std::fs::write(tmp.path().join("seed.txt"), &original).unwrap();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(tmp.path())
.args(["add", "seed.txt"])
.status();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(tmp.path())
.args(["commit", "-q", "-m", "seed"])
.status();
// Two hunks: one near the top, one near the very bottom so the bottom
// hunk falls inside the clamped viewport region.
let mut edited: Vec<String> = original.lines().map(str::to_string).collect();
edited[5] = "edited-5".to_string();
edited[58] = "edited-58".to_string();
std::fs::write(tmp.path().join("seed.txt"), edited.join("\n") + "\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| {
a.source_control
.entries
.iter()
.any(|e| e.path == "seed.txt")
});
let idx = app
.source_control
.entries
.iter()
.position(|e| e.path == "seed.txt")
.unwrap();
app.open_source_control_entry(idx);
// A small viewport forces render_diff to clamp scroll at the bottom.
let backend = ratatui::backend::TestBackend::new(120, 24);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let first_scroll = app.editor.diff.as_ref().unwrap().scroll;
// Forward to the bottom hunk; render to trigger the clamp writeback.
app.handle_editor_key(key(KeyCode::F(7), KeyModifiers::NONE));
term.draw(|f| app.render(f)).unwrap();
let bottom_scroll = app.editor.diff.as_ref().unwrap().scroll;
assert!(
bottom_scroll > first_scroll,
"F7 must advance to the bottom hunk (first={first_scroll}, bottom={bottom_scroll})"
);
// Forward again from the last hunk MUST wrap back to the first, not
// stick on the bottom hunk.
app.handle_editor_key(key(KeyCode::F(7), KeyModifiers::NONE));
term.draw(|f| app.render(f)).unwrap();
let wrapped_scroll = app.editor.diff.as_ref().unwrap().scroll;
assert_eq!(
wrapped_scroll, first_scroll,
"forward from the last hunk must wrap to the first (saw {wrapped_scroll}, expected {first_scroll})"
);
}
#[test]
fn focused_source_control_input_drives_a_visible_caret_at_the_message_cursor() {
// Regression for the user's "I don't see the caret blinking in the
// Source Control message box, so I have no clue where it is at any
// point in time" report. After focusing the SC panel in a real
// repo, `cursor_should_be_visible()` must report true and the
// caret cell must point inside the rendered input box.
let tmp = tempfile::tempdir().unwrap();
let _ = std::process::Command::new("git")
.args(["-C"])
.arg(tmp.path())
.args(["init", "-q", "-b", "main"])
.output();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
while std::time::Instant::now() < deadline {
app.drain_git_responses();
if app.source_control.status.in_repo {
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert!(
app.source_control.status.in_repo,
"preconditions: tempdir must register as a git repo"
);
app.set_sidebar_view(SidebarView::SourceControl);
let backend = ratatui::backend::TestBackend::new(80, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
app.handle_source_control_key(key(KeyCode::Char('f'), KeyModifiers::NONE));
app.handle_source_control_key(key(KeyCode::Char('i'), KeyModifiers::NONE));
app.handle_source_control_key(key(KeyCode::Char('x'), KeyModifiers::NONE));
term.draw(|f| app.render(f)).unwrap();
assert!(
app.cursor_should_be_visible(),
"caret must be visible when the Source Control panel owns focus and the input is laid out"
);
let (cx, cy) = app
.source_control
.cursor_screen_pos()
.expect("focused SC panel must expose a caret cell");
let r = app.source_control.last_input_area;
assert!(
cx >= r.x + 2 && cx < r.x + r.width - 1 && cy == r.y + 1,
"caret cell ({cx},{cy}) must sit inside the input's text row (input rect {r:?})"
);
assert_eq!(
cx,
r.x + 2 + 3,
"caret must advance one cell per typed char (3 chars typed → +3 cells past the first text cell)"
);
}
#[test]
fn editor_shift_alt_down_duplicates_the_current_line_via_handle_key() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.lines = vec![String::from("alpha"), String::from("beta")];
app.editor.cursor_row = 0;
app.editor.cursor_col = 3;
app.handle_key(key(KeyCode::Down, KeyModifiers::ALT | KeyModifiers::SHIFT))
.unwrap();
assert_eq!(app.editor.lines, vec!["alpha", "alpha", "beta"]);
assert_eq!(
(app.editor.cursor_row, app.editor.cursor_col),
(1, 3),
"cursor must follow onto the duplicated line"
);
}
#[test]
fn editor_shift_alt_up_duplicates_the_current_line_via_handle_key() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.lines = vec![String::from("alpha"), String::from("beta")];
app.editor.cursor_row = 1;
app.editor.cursor_col = 2;
app.handle_key(key(KeyCode::Up, KeyModifiers::ALT | KeyModifiers::SHIFT))
.unwrap();
assert_eq!(app.editor.lines, vec!["alpha", "beta", "beta"]);
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 2));
}
#[test]
fn editor_alt_right_jumps_one_word_forward() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.lines = vec![String::from("hello world rest")];
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
app.handle_key(key(KeyCode::Right, KeyModifiers::ALT))
.unwrap();
assert_eq!(app.editor.cursor_col, 5);
app.handle_key(key(KeyCode::Right, KeyModifiers::ALT))
.unwrap();
assert_eq!(app.editor.cursor_col, 11);
}
fn editor_app_with_lines(lines: &[&str]) -> App {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.lines = lines.iter().map(|s| (*s).to_string()).collect();
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
app
}
/// Wait for the provenance sidecar the save records after its snapshot
/// (#349); it lands on the same thread, strictly after the snapshot.
fn wait_for_seats(root: &std::path::Path, f: &std::path::Path, millis: u64) {
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the provenance sidecar",
|| crate::history::seats_for(root, f, millis).is_some(),
);
}
/// History recording runs off-thread; poll until the store has entries (or a
/// deadline passes and the caller's assert reports the miss).
fn wait_for_snapshots(
root: &std::path::Path,
f: &std::path::Path,
) -> Vec<crate::history::Snapshot> {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
let snaps = crate::history::entries_in(root, f);
if !snaps.is_empty() || std::time::Instant::now() > deadline {
return snaps;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
#[test]
fn saving_records_a_local_history_snapshot_that_diffs_and_restores() {
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "v1\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
// Type and save: the save hook records a snapshot of the on-disk bytes
// (off-thread, so poll for it).
app.handle_key(key(KeyCode::Char('X'), KeyModifiers::NONE))
.unwrap();
app.save();
let saved = std::fs::read_to_string(&f).unwrap();
let snaps = wait_for_snapshots(&app.history_root, &f);
assert_eq!(snaps.len(), 1, "a save must record one snapshot");
assert_eq!(
std::fs::read_to_string(&snaps[0].file).unwrap(),
saved,
"the snapshot holds exactly what hit the disk"
);
// Clicking the snapshot row opens a diff of snapshot vs working file and
// arms restore.
let hash = format!("local:{}", snaps[0].millis);
app.open_timeline_diff(f.clone(), hash);
assert!(
app.editor.diff.is_some(),
"a local snapshot row opens a diff view"
);
assert!(app.history_restore.is_some(), "restore is armed");
// Corrupt the file, then restore the snapshot back over it.
std::fs::write(&f, "clobbered\n").unwrap();
app.restore_history_snapshot();
assert_eq!(
std::fs::read_to_string(&f).unwrap(),
saved,
"restore writes the snapshot contents back to disk"
);
}
/// The agent review diff must not leave another file's "Restore Snapshot"
/// armed (#345): it opens a snapshot diff like the TIMELINE does, so it
/// owes the same disarm, or restore silently overwrites a file the user is
/// not looking at.
#[test]
fn the_review_diff_disarms_another_files_restore() {
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
let b = tmp.path().join("b.txt");
std::fs::write(&a, "a-disk\n").unwrap();
std::fs::write(&b, "b-disk\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
// a.txt's timeline snapshot is on screen: restore is armed for a.txt.
crate::history::record_in(&app.history_root, &a, b"a-old\n", 1000).unwrap();
app.editor.open(&a).unwrap();
app.open_timeline_diff(a.clone(), "local:1000".into());
assert!(app.history_restore.is_some(), "staging: a's snapshot armed");
// b.txt is in an agent lane and has never been reviewed, so the diff
// REFUSES - and a refusal leaves a's diff on screen, which is exactly
// when a stale restore is most dangerous.
let working = vec![String::from("claude")];
app.agent_ledger.record_write(&b, 7, &working);
app.diff_agent_lane_row("claude", &b);
assert!(
app.history_restore.is_none(),
"the review diff left the previous file's restore armed"
);
app.restore_history_snapshot();
assert_eq!(
std::fs::read_to_string(&a).unwrap(),
"a-disk\n",
"restore wrote a stale snapshot over an unrelated file"
);
}
/// Marking a file reviewed records a snapshot of the bytes it just hashed,
/// so the row can be diffed against what the user actually approved (#345).
///
/// The store is written only by croft's own saves; the agent-write path
/// records nothing. Adopting whatever snapshot was newest anchored the
/// review to an unrelated earlier save and then labelled it "(reviewed)".
#[test]
fn reviewing_anchors_to_the_content_it_baselined_not_an_older_save() {
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("touched.rs");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
// An OLD, unrelated save is already in the store - the trap: it is the
// newest snapshot at review time but is not what the agent wrote.
crate::history::record_in(&app.history_root, &f, b"an older user save\n", 1000).unwrap();
// The agent writes; the user never saved this content in croft.
std::fs::write(&f, "what the agent wrote\n").unwrap();
let working = vec![String::from("claude")];
app.agent_ledger.record_write(
&f,
crate::agent_lane::content_hash(b"what the agent wrote\n"),
&working,
);
assert!(app.mark_agent_file_reviewed("claude", &f));
let millis = app.agent_ledger.lane("claude")[0]
.reviewed_millis
.expect("the review recorded an anchor");
let snap = crate::history::snapshot_file_in(&app.history_root, &f, millis)
.expect("the anchor names a snapshot that exists");
assert_eq!(
std::fs::read(&snap).unwrap(),
b"what the agent wrote\n",
"the anchor must hold the reviewed content, not the older save"
);
assert_ne!(
millis, 1000,
"it must not adopt the unrelated older snapshot"
);
// And the diff opens against that content rather than refusing.
std::fs::write(&f, "what the agent wrote next\n").unwrap();
app.diff_agent_lane_row("claude", &f);
assert!(
app.status.contains("since you last reviewed"),
"the diff opens against the reviewed baseline: {}",
app.status
);
}
/// A snapshot click that fails (pruned .snap, unreadable file) must disarm
/// "Restore Snapshot": the palette entry otherwise writes whatever snapshot
/// was viewed BEFORE over a file that is not even on screen.
#[test]
fn a_failed_snapshot_click_disarms_a_stale_restore() {
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
let b = tmp.path().join("b.txt");
std::fs::write(&a, "a-disk\n").unwrap();
std::fs::write(&b, "b-disk\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
crate::history::record_in(&app.history_root, &a, b"a-old\n", 1000).unwrap();
app.editor.open(&a).unwrap();
app.open_timeline_diff(a.clone(), "local:1000".into());
assert!(app.history_restore.is_some(), "staging: a's snapshot armed");
// A pruned snapshot row of another file: the click fails...
app.open_timeline_diff(b.clone(), "local:999".into());
assert_eq!(app.status, "Snapshot no longer available");
assert!(
app.history_restore.is_none(),
"the failed click left the previous file's restore armed"
);
// ...and restore must refuse instead of clobbering a.txt.
app.restore_history_snapshot();
assert_eq!(
std::fs::read_to_string(&a).unwrap(),
"a-disk\n",
"restore wrote a stale snapshot over an unrelated file"
);
}
/// Local snapshots are path-keyed and repo-free, so a file outside the
/// workspace root must still list (and restore) its versions; the panel used
/// to sit on "Loading" forever while snapshots accumulated invisibly.
#[test]
fn a_file_outside_the_workspace_still_lists_its_local_snapshots() {
let tmp = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = outside.path().join("note.txt");
std::fs::write(&f, "v2\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
crate::history::record_in(&app.history_root, &f, b"v1\n", 1000).unwrap();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
let target = loop {
app.sync_explorer_panels();
if let Some(t) = app.timeline.diff_target(0) {
break Some(t);
}
if std::time::Instant::now() > deadline {
break None;
}
std::thread::sleep(std::time::Duration::from_millis(20));
};
assert_eq!(
target,
Some((f.clone(), "local:1000".to_string())),
"the out-of-root file's snapshot never reached the TIMELINE"
);
}
/// A Windows-1252 buffer (via Reopen with Encoding) saves non-UTF-8 bytes, so
/// its history must be recorded byte-exact — the old text-only path silently
/// skipped every save of such a file.
#[test]
fn saving_a_windows_1252_file_records_a_byte_exact_snapshot() {
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("latin.txt");
// 0xE9 is 'é' in Windows-1252 and invalid UTF-8.
std::fs::write(&f, b"caf\xE9\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.editor
.reopen_with_encoding(encoding_rs::WINDOWS_1252)
.unwrap();
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Char('X'), KeyModifiers::NONE))
.unwrap();
app.save();
let snaps = wait_for_snapshots(&app.history_root, &f);
assert_eq!(
snaps.len(),
1,
"a non-UTF-8 file's save must record history"
);
let disk = std::fs::read(&f).unwrap();
assert!(disk.contains(&0xE9), "staging: the save re-encoded to 1252");
assert_eq!(
std::fs::read(&snaps[0].file).unwrap(),
disk,
"the snapshot must hold the exact on-disk bytes"
);
}
#[test]
fn inline_blame_annotation_paints_on_the_cursor_line() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("m.rs");
std::fs::write(&f, "fn main() {}\nlet x = 1;\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 0;
app.editor.set_blame(
f.clone(),
Some(vec![
crate::git::BlameLine {
short_hash: "abc12345".into(),
summary: "init".into(),
author: "Vitali".into(),
age_secs: 3600,
uncommitted: false,
text: None,
},
crate::git::BlameLine {
short_hash: "abc12345".into(),
summary: "add x".into(),
author: "Alice".into(),
age_secs: 60,
uncommitted: false,
text: None,
},
]),
);
let backend = ratatui::backend::TestBackend::new(120, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let buf = term.backend().buffer();
let mut whole = String::new();
for y in 0..30 {
for x in 0..120 {
whole.push_str(buf[(x, y)].symbol());
}
whole.push('\n');
}
assert!(
whole.contains("Vitali, 1 hour ago"),
"the cursor line's blame annotation must render; got:\n{whole}"
);
assert!(
!whole.contains("Alice"),
"only the cursor line is annotated, not every line"
);
}
/// `Editor: Toggle Provenance` (#349) flips the lens on the active editor
/// and keeps it across the per-tick sync; off again on a second toggle.
#[test]
fn toggle_provenance_command_flips_the_editor_lens() {
let mut app = editor_app_with_lines(&["one", "two"]);
assert!(!app.editor.provenance_overlay, "the lens is off by default");
app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
assert!(app.editor.provenance_overlay, "the command turns it on");
assert_eq!(app.status, "Provenance: on");
app.sync_blame();
assert!(
app.editor.provenance_overlay,
"and the tick sync keeps it on"
);
app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
app.sync_blame();
assert!(
!app.editor.provenance_overlay,
"toggling again turns it off"
);
}
/// The group-by-seat lens on a Source Control diff (#349, slice four): the
/// command loads the file's persisted map and reports who wrote the lines
/// the change adds, so a review can be read as "the agent's part" and "my
/// part". Driven through the real command, not by setting the flag.
#[test]
fn the_group_by_seat_lens_reports_who_wrote_the_added_lines() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
// The working tree: one line HEAD already had, two the change adds.
std::fs::write(&f, "kept\nmine\nnobody's\n").unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(1..2, Seat::Me);
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.focus_pane(Pane::Editor);
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("note.txt (HEAD)"),
"kept\n",
&f,
true,
)
.unwrap();
assert!(app.editor.diff.is_some(), "staging: a diff view is open");
assert!(
!app.editor.diff.as_ref().unwrap().group_by_seat,
"staging: the lens is off by default"
);
app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
let diff = app.editor.diff.as_ref().unwrap();
assert!(diff.group_by_seat, "the command turns the lens on");
assert_eq!(
diff.seat_summary(),
"you 1 \u{2022} unrecorded 1",
"the added lines are reported per seat, the unwatched one as unrecorded"
);
assert_eq!(
app.status, "Diff: group by seat \u{2022} you 1 \u{2022} unrecorded 1",
"and the status line says the same"
);
app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
assert!(
!app.editor.diff.as_ref().unwrap().group_by_seat,
"toggling again turns it off"
);
}
/// The lens survives a rebuild of the view under it (#349 review): the
/// real refresh re-reads a Source Control diff whose file moved, and the
/// lens must stay on with a map reloaded against the NEW rows, rather than
/// going dark or keeping a map that named lines these rows renumbered.
#[test]
fn the_group_by_seat_lens_survives_a_rebuild_of_the_view() {
use crate::provenance::Seat;
let (tmp, f) = repo_with_seed("kept\n");
let hist = tempfile::tempdir().unwrap();
std::fs::write(&f, "kept\nmine\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.focus_pane(Pane::Editor);
let record = |millis: u64, seats: &crate::provenance::Provenance| {
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
millis,
seats,
)
.unwrap();
};
let mut seats = crate::provenance::Provenance::new();
seats.record(1..2, Seat::Me);
record(1_000, &seats);
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("seed.txt (HEAD)"),
"kept\n",
&f,
true,
)
.unwrap();
app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
root: tmp.path().to_path_buf(),
rel: String::from("seed.txt"),
});
app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
assert_eq!(
app.editor.diff.as_ref().unwrap().seat_summary(),
"you 1",
"staging: the lens is on and reports the one added line"
);
// An agent appends a line; the real refresh re-reads the moved file.
rewrite_later(&f, "kept\nmine\ntheirs\n");
let mut seats2 = crate::provenance::Provenance::new();
seats2.record(1..2, Seat::Me);
seats2.record(2..3, Seat::Agent(String::from("pane 2")));
record(500_000, &seats2);
let no_paths = std::collections::BTreeSet::new();
assert!(
app.refresh_open_diff_views(false, &[], &no_paths),
"staging: the refresh rebuilt the view"
);
let diff = app.editor.diff.as_ref().unwrap();
assert_eq!(
diff.right_lines.len(),
3,
"staging: the rebuilt view shows the new line"
);
assert!(
diff.group_by_seat,
"the lens stays on across the rebuild rather than going dark"
);
assert_eq!(
diff.seat_summary(),
"you 1 \u{2022} agent (pane 2) 1",
"and its map is reloaded against the rebuilt rows: {}",
diff.seat_summary()
);
}
/// A map is never joined onto rows it does not describe (#349 review): if
/// the file moved on disk since the view was built, the lens reports
/// nothing rather than crediting the view's stale lines from a newer map.
#[test]
fn the_group_by_seat_lens_refuses_a_map_for_lines_the_view_does_not_show() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "kept\nmine\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.focus_pane(Pane::Editor);
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("note.txt (HEAD)"),
"kept\n",
&f,
true,
)
.unwrap();
// Same LENGTH, different content ("else" for "mine"), so the (mtime,
// len) stamp gate genuinely cannot see this rewrite: the view still
// shows the old lines while disk and its snapshot have moved.
std::fs::write(&f, "kept\nelse\n").unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(1..2, Seat::Me);
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
let diff = app.editor.diff.as_ref().unwrap();
assert_eq!(
diff.right_lines,
vec![String::from("kept"), String::from("mine")],
"staging: the view still shows the pre-rewrite lines"
);
assert_eq!(
diff.seat_summary(),
"unrecorded 1",
"the newer map is refused rather than joined onto lines it never described"
);
}
/// A lone carriage return is one line to the diff opener (#349 review):
/// the comparison that binds a map to the view's rows has to split the same
/// way, or the lens reports every line unrecorded on such a file.
#[test]
fn the_group_by_seat_lens_handles_a_lone_carriage_return() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
// "a\rb" is ONE line to `str::lines`, which is how the view is built.
std::fs::write(&f, "kept\na\rb\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.focus_pane(Pane::Editor);
let mut seats = crate::provenance::Provenance::new();
seats.record(1..2, Seat::Me);
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("note.txt (HEAD)"),
"kept\n",
&f,
true,
)
.unwrap();
assert_eq!(
app.editor.diff.as_ref().unwrap().right_lines.len(),
2,
"staging: the opener made two lines, the lone CR inside the second"
);
app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
assert_eq!(
app.editor.diff.as_ref().unwrap().seat_summary(),
"you 1",
"the map is applied rather than refused over a splitting difference"
);
}
/// The lens refuses a diff whose right side is not the working tree (#349):
/// a diff parsed from raw git output numbers its rows by position in that
/// text, so joining a line-keyed seat map onto it would credit lines at
/// random. Refusing is the only safe answer.
#[test]
fn the_group_by_seat_lens_refuses_a_diff_that_is_not_the_working_tree() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
// A Timeline snapshot diff: same opener, left_is_git_head false.
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("note.txt (snapshot)"),
"old\n",
&f,
false,
)
.unwrap();
app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
assert!(
!app.editor.diff.as_ref().unwrap().group_by_seat,
"the lens stays off on a diff it cannot key"
);
assert!(
app.status.contains("working tree"),
"and says why: {}",
app.status
);
}
/// Provenance survives a restart (#349, criterion 2): a save records who
/// typed each line beside the history snapshot, and a fresh app that opens
/// the unchanged file gets the map back. Distinguishable seats per line, or
/// a seat on the wrong line would be invisible.
#[test]
fn provenance_survives_a_restart_when_the_file_is_unchanged() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\ntwo\nthree\n").unwrap();
{
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
// Recorded directly rather than typed: a typed newline splits the
// line below and credits it to the typist (the shipped rule), and
// this test needs one line nobody touched.
app.editor.provenance.record(0..1, Seat::Navigator);
app.editor
.provenance
.record(1..2, Seat::Agent(String::from("pane 2")));
app.editor.dirty = true;
app.save();
let snaps = wait_for_snapshots(&app.history_root, &f);
assert_eq!(snaps.len(), 1, "staging: the save recorded a snapshot");
assert_eq!(
std::fs::read(&snaps[0].file).unwrap(),
std::fs::read(&f).unwrap(),
"staging: the snapshot holds the saved bytes"
);
// The sidecar lands after the snapshot, on the same thread; wait for
// it rather than for the snapshot it follows.
wait_for_seats(&app.history_root, &f, snaps[0].millis);
}
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
assert_eq!(
app.editor.provenance.attributed(),
0,
"staging: a fresh open knows nothing yet"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance.seat(0),
Some(&Seat::Navigator),
"the navigator's line comes back: {:?}",
app.editor.provenance
);
assert_eq!(
app.editor.provenance.seat(1),
Some(&Seat::Agent(String::from("pane 2"))),
"and the agent's: {:?}",
app.editor.provenance
);
assert_eq!(
app.editor.provenance.seat(2),
None,
"the untouched line stays unknown"
);
}
/// A whole-buffer swap under the same path clears the map and is reconsidered
/// on its own (#349 review): the reload behind an FS-sync sweep or a
/// disk-conflict popup, a revert, "Reopen as Text" and a re-decode all go
/// through an opener, and none of them has to reset anything by hand. Driven
/// through the openers themselves; the marker is never touched.
#[test]
fn provenance_comes_back_after_every_same_path_swap() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\ntwo\n").unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Navigator);
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"staging: the first sync restores"
);
// The revert every reload path ends in.
app.editor.revert_to_disk().unwrap();
assert_eq!(
app.editor.provenance.attributed(),
0,
"staging: the revert cleared the map"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"the map comes back after a revert of the same path"
);
// "Reopen as Text": `open` on the path already open.
app.editor.open(&f).unwrap();
assert_eq!(
app.editor.provenance.attributed(),
0,
"staging: the reopen cleared the map"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"and after a reopen of the same path"
);
}
/// Two tabs on one file are two buffers (#349 review): a split opens the
/// same path in a fresh group, whose tab sits at the same `edit_seq` as the
/// first one did when it was synced. The marker is per buffer, so the split
/// pane gets the map too rather than staying blank for the session.
#[test]
fn a_split_of_a_synced_file_gets_the_map_in_the_new_group() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Navigator);
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"staging: the first tab is synced"
);
app.split_editor();
assert_eq!(
app.editor.path.as_deref(),
Some(f.as_path()),
"staging: the split opened the same file in the focused group"
);
assert_eq!(
app.editor.provenance.attributed(),
0,
"staging: the new group's tab knows nothing yet"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"the split pane's buffer is synced on its own"
);
}
/// A swap into a viewer drops the map (#349 review): the hex view's single
/// placeholder line was written by no seat, and a save from the viewer must
/// not persist the text tab's map against bytes it never described. The swap
/// back to text is an ordinary reopen and gets the persisted map again.
#[test]
fn a_viewer_swap_drops_the_map_and_the_text_reopen_gets_it_back() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Navigator);
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"staging: the text tab is synced"
);
app.editor.open_hex(&f).unwrap();
assert!(app.editor.hex.is_some(), "staging: the tab is a hex view");
assert_eq!(
app.editor.provenance.attributed(),
0,
"the swap into the viewer dropped the map"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance.attributed(),
0,
"and a sync does not credit the viewer's placeholder line"
);
assert_eq!(
app.editor.provenance_to_record().attributed(),
0,
"a save from the viewer would record no map"
);
app.editor.open(&f).unwrap();
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"the reopen as text gets the persisted map back"
);
}
/// A markdown preview is not a viewer (#349 review): `lines` still holds the
/// file's own text and the tab is saveable, so a save taken while the
/// preview is up records the map rather than dropping it (and, inside the
/// merge window, deleting the previous snapshot's sidecar with nothing to
/// replace it).
#[test]
fn a_markdown_preview_save_keeps_the_map() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.md");
std::fs::write(&f, "# one\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.editor.provenance.record(0..1, Seat::Navigator);
assert!(
app.editor.toggle_markdown_preview(),
"staging: the preview is up"
);
assert!(
!app.editor.has_non_text_view(),
"staging: a markdown preview tab is still saveable text"
);
assert_eq!(
app.editor.provenance_to_record().seat(0),
Some(&Seat::Navigator),
"the buffer's own text is in `lines`; its map still describes it"
);
app.editor.dirty = true;
app.save();
let snaps = wait_for_snapshots(&app.history_root, &f);
assert_eq!(snaps.len(), 1, "staging: the save recorded a snapshot");
wait_for_seats(&app.history_root, &f, snaps[0].millis);
}
/// The lens paints in every pane, so the map is restored onto every open
/// buffer (#349 review), not only the focused one: a split whose other
/// group holds the file must not show the lens on with every line blank.
#[test]
fn provenance_is_synced_onto_the_inactive_group_too() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Navigator);
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
// Split before any sync: both groups hold the file, neither knows its map.
app.split_editor();
let inactive = app.editor_layout.inactive_groups();
assert_eq!(inactive.len(), 1, "staging: one inactive group");
assert_eq!(
inactive[0].path.as_deref(),
Some(f.as_path()),
"staging: the inactive group holds the file"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"staging: the focused tab is synced"
);
assert_eq!(
app.editor_layout.inactive_groups()[0].provenance,
seats,
"the inactive group's tab is synced too"
);
}
/// A save records the saved tab's own map (#349 review): with the same file
/// open in two groups, an auto save of the inactive group's buffer must not
/// persist the focused group's map against bytes it never described.
#[test]
fn an_inactive_group_save_records_the_map_of_that_buffer() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.split_editor();
// The focused group's buffer: clean, and wearing a map of its own.
app.editor
.provenance
.record(0..1, Seat::Peer(String::from("ana")));
// The inactive group's buffer: the navigator types, so it is dirty and
// due, and its map says navigator.
{
let mut groups = app.editor_layout.inactive_groups_mut();
let other: &mut crate::widgets::editor::Editor = &mut *groups[0];
assert_eq!(
other.path.as_deref(),
Some(f.as_path()),
"staging: same file"
);
other.cursor_row = 0;
other.cursor_col = 0;
other.insert_str_as("nav\n", Seat::Navigator);
assert!(other.dirty, "staging: the inactive buffer is dirty");
age_last_edit(other);
}
app.auto_save = true;
assert!(
app.tick_auto_save(),
"staging: the sweep saved the dirty buffer"
);
assert!(
std::fs::read_to_string(&f).unwrap().starts_with("nav\n"),
"staging: the inactive buffer's text is what hit the disk"
);
let snaps = wait_for_snapshots(&app.history_root, &f);
assert_eq!(snaps.len(), 1, "staging: the save recorded a snapshot");
wait_for_seats(&app.history_root, &f, snaps[0].millis);
let recorded = crate::history::seats_for(&app.history_root, &f, snaps[0].millis).unwrap();
assert_eq!(
recorded.seat(0),
Some(&Seat::Navigator),
"the sidecar holds the saved buffer's map, not the focused tab's: {recorded:?}"
);
}
/// A clean buffer can still be stale (#349 review): when one tab of a split
/// saves, the other keeps the pre-save text and its own disk stamp. The
/// newest snapshot then matches disk while describing text that tab never
/// held, so the map must NOT be applied to it.
#[test]
fn a_stale_tab_is_not_credited_with_the_map_of_the_saving_tab() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.split_editor();
// The inactive group types and saves; the focused tab is untouched, so
// it stays clean, unattributed, and holding the pre-save text.
{
let mut groups = app.editor_layout.inactive_groups_mut();
let other: &mut crate::widgets::editor::Editor = &mut *groups[0];
other.cursor_row = 0;
other.cursor_col = 0;
other.insert_str_as("nav\n", Seat::Navigator);
age_last_edit(other);
}
app.auto_save = true;
assert!(
app.tick_auto_save(),
"staging: the sweep saved the other buffer"
);
let snaps = wait_for_snapshots(&app.history_root, &f);
wait_for_seats(&app.history_root, &f, snaps[0].millis);
// Positive control: there IS a map beside a snapshot matching disk, so a
// sync that ignored staleness would have something to apply.
assert_eq!(
std::fs::read(&snaps[0].file).unwrap(),
std::fs::read(&f).unwrap(),
"staging: the newest snapshot matches the file on disk"
);
assert!(!app.editor.dirty, "staging: the focused tab is clean");
assert_eq!(
app.editor.lines,
vec![String::from("one")],
"staging: and still holds the pre-save text"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance.attributed(),
0,
"a stale buffer is not credited from a snapshot of text it never held: {:?}",
app.editor.provenance
);
}
/// An empty file gets its map back too (#349 review): `open` gives an empty
/// buffer one sentinel line, so a comparison against the snapshot's bare
/// (zero-line) split would withhold the map from every emptied file.
#[test]
fn the_map_of_an_emptied_file_survives_a_restart() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "").unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Navigator);
crate::history::record_with_seats_in(hist.path(), &f, b"", 1_000, &seats).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
assert_eq!(
app.editor.lines,
vec![String::new()],
"staging: an empty file opens as one empty line"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"the emptied file's map comes back: {:?}",
app.editor.provenance
);
}
/// A UTF-16 file's map comes back too (#349 review): the snapshot holds the
/// file's raw bytes, so the comparison must decode them the way `open` does,
/// through the BOM, rather than assuming UTF-8.
#[test]
fn the_map_of_a_utf16_file_survives_a_restart() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
let mut bytes = vec![0xFF, 0xFE];
for unit in "one
two
"
.encode_utf16()
{
bytes.extend_from_slice(&unit.to_le_bytes());
}
std::fs::write(&f, &bytes).unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Navigator);
crate::history::record_with_seats_in(hist.path(), &f, &bytes, 1_000, &seats).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
assert_eq!(
app.editor.lines,
vec![String::from("one"), String::from("two")],
"staging: the file opened as UTF-16 text"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"the UTF-16 file's map comes back: {:?}",
app.editor.provenance
);
}
/// The recorded map is bound to the bytes it describes (#349 review): the
/// worker re-reads the file, so a save of the same path landing in between
/// must not get the earlier buffer's map attached to its bytes. The snapshot
/// is still recorded; only the attribution is withheld.
#[test]
fn the_map_is_not_recorded_against_another_save_s_bytes() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Navigator);
// The map describes "one", but something else reaches the disk first:
// exactly the race the worker's re-read opens.
std::fs::write(&f, "someone else\n").unwrap();
app.record_history_snapshot_of(&f, seats, Some(b"one\n".to_vec()));
let snaps = wait_for_snapshots(&app.history_root, &f);
assert_eq!(snaps.len(), 1, "the snapshot is still recorded");
assert_eq!(
std::fs::read(&snaps[0].file).unwrap(),
b"someone else\n",
"and holds the bytes that were actually on disk"
);
assert_eq!(
crate::history::seats_for(&app.history_root, &f, snaps[0].millis),
None,
"but wears no map, rather than one describing text it does not hold"
);
// Positive control: the same call with matching bytes DOES record a map,
// so the assertion above is about the binding and not about the plumbing.
let mut seats2 = crate::provenance::Provenance::new();
seats2.record(0..1, Seat::Peer(String::from("ana")));
let on_disk = std::fs::read(&f).unwrap();
app.record_history_snapshot_of(&f, seats2, Some(on_disk));
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the control's sidecar",
|| {
crate::history::entries_in(&app.history_root, &f)
.first()
.is_some_and(|s| {
crate::history::seats_for(&app.history_root, &f, s.millis).is_some()
})
},
);
}
/// A restore of a snapshot with no sidecar restores every line unknown
/// (#349 review): the buffer's previous map described the text the restore
/// replaced, and keeping it would credit lines nobody observed.
#[test]
fn restoring_a_snapshot_without_seats_leaves_every_line_unknown() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
let (v1, v2) = (b"one\n".as_slice(), b"one\ntwo\n".as_slice());
let mut seats_v2 = crate::provenance::Provenance::new();
seats_v2.record(1..2, Seat::Navigator);
crate::history::record_in(hist.path(), &f, v1, 1_000).unwrap();
let recent = now_millis() - 100;
crate::history::record_with_seats_in(hist.path(), &f, v2, recent, &seats_v2).unwrap();
std::fs::write(&f, v2).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.sync_provenance();
assert_eq!(app.editor.provenance, seats_v2, "staging: v2's map is live");
app.open_timeline_diff(f.clone(), String::from("local:1000"));
app.editor.open(&f).unwrap();
app.restore_history_snapshot();
assert_eq!(
std::fs::read(&f).unwrap(),
v1,
"staging: v1 is back on disk"
);
assert_eq!(
app.editor.provenance.attributed(),
0,
"a snapshot that recorded no seats restores every line unknown: {:?}",
app.editor.provenance
);
}
/// A tab that is not eligible yet is not the same as one considered (#349
/// review): a sync that lands on a dirty buffer leaves it for a later tick
/// rather than burning the map for the session.
#[test]
fn a_dirty_tab_is_reconsidered_for_provenance_once_it_is_clean() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Peer(String::from("ana")));
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.editor.dirty = true;
app.sync_provenance();
assert_eq!(
app.editor.provenance.attributed(),
0,
"staging: a dirty buffer takes no map"
);
app.editor.dirty = false;
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"the same buffer, clean, gets the map on the next tick"
);
}
/// Restoring a snapshot carries that snapshot's seats (#349 review): onto the
/// reverted buffer, and onto the snapshot the restore records, which inside
/// the merge window supersedes the newest one and takes its sidecar with it.
/// Before this the restore recorded the just-cleared (empty) map, so a
/// persisted map was destroyed by the very command that reinstated its text.
#[test]
fn restoring_a_snapshot_carries_its_seats_onto_the_restore() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
let (v1, v2) = (b"one\ntwo\n".as_slice(), b"one\ntwo\nthree\n".as_slice());
let mut seats_v1 = crate::provenance::Provenance::new();
seats_v1.record(0..1, Seat::Navigator);
let mut seats_v2 = crate::provenance::Provenance::new();
seats_v2.record(2..3, Seat::Agent(String::from("pane 2")));
// v2 is the newest snapshot and recent enough that the restore lands
// inside the merge window, which must not supersede it.
let recent = now_millis() - 100;
crate::history::record_with_seats_in(hist.path(), &f, v1, 1_000, &seats_v1).unwrap();
crate::history::record_with_seats_in(hist.path(), &f, v2, recent, &seats_v2).unwrap();
std::fs::write(&f, v2).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.sync_provenance();
assert_eq!(app.editor.provenance, seats_v2, "staging: v2's map is live");
// Arm the restore from the timeline, then make the file the active tab
// again (the diff view closed) and restore through the real command.
app.open_timeline_diff(f.clone(), String::from("local:1000"));
assert!(
app.history_restore.is_some(),
"staging: the restore is armed"
);
app.editor.open(&f).unwrap();
app.restore_history_snapshot();
assert_eq!(
std::fs::read(&f).unwrap(),
v1,
"staging: v1 is back on disk"
);
assert_eq!(
app.editor.provenance, seats_v1,
"the reverted buffer wears the restored snapshot's seats"
);
// The record runs off-thread: wait for the superseding snapshot.
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the restore's snapshot",
|| {
crate::history::entries_in(hist.path(), &f)
.first()
.is_some_and(|newest| newest.millis > recent)
},
);
let snaps = crate::history::entries_in(hist.path(), &f);
// v2 is kept, not superseded: the restore overwrote it, and replacing
// its snapshot inside the merge window lost that version for good.
assert_eq!(
snaps.len(),
3,
"v1 restored, v2 kept, v1 original: {snaps:?}"
);
assert_eq!(std::fs::read(&snaps[0].file).unwrap(), v1);
assert_eq!(std::fs::read(&snaps[1].file).unwrap(), v2);
wait_for_seats(hist.path(), &f, snaps[0].millis);
assert_eq!(
crate::history::seats_for(hist.path(), &f, snaps[0].millis),
Some(seats_v1.clone()),
"and the newest snapshot carries v1's seats, not an empty map"
);
// A fresh open of the restored file gets them back the ordinary way.
let mut again = App::new(tmp.path().to_path_buf()).unwrap();
again.history_root = hist.path().to_path_buf();
again.editor.open(&f).unwrap();
again.sync_provenance();
assert_eq!(again.editor.provenance, seats_v1);
}
/// A persisted map is restored only onto the text it described: a file
/// changed since the snapshot (by anything, croft or not) opens with every
/// line unknown rather than credited from a stale map.
#[test]
fn provenance_is_not_restored_onto_text_the_snapshot_never_saw() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "v1\n").unwrap();
{
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
app.editor.insert_str_as("nav\n", Seat::Navigator);
app.save();
let snaps = wait_for_snapshots(&app.history_root, &f);
assert_eq!(snaps.len(), 1, "staging: the save recorded a snapshot");
// Positive control: there IS a map that a careless restore would apply.
wait_for_seats(&app.history_root, &f, snaps[0].millis);
}
// Edited outside croft after the save: the snapshot's map describes text
// that is no longer what is on disk.
let mut on_disk = std::fs::read_to_string(&f).unwrap();
on_disk.insert_str(0, "someone else\n");
std::fs::write(&f, on_disk).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.sync_provenance();
assert_eq!(
app.editor.provenance.attributed(),
0,
"a changed file is not credited from a stale map: {:?}",
app.editor.provenance
);
}
/// The lens reaches every tab of every group, not only the focused editor
/// (#349 review): the gutter bar paints in every pane, so `sync_focus_flags`
/// carries it the way it carries indent guides.
#[test]
fn the_provenance_lens_reaches_every_editor_after_the_flag_sync() {
let mut app = editor_app_with_lines(&["one", "two"]);
app.editor
.push_editor(crate::widgets::editor::Editor::new());
assert!(app.editor.editors.len() >= 2, "fixture: two tabs");
// A split puts the first group out of focus; the lens must reach it too.
app.editor.path = Some(std::path::PathBuf::from("split-anchor.txt"));
app.split_editor();
app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
app.sync_focus_flags();
let every_editor_on = app.editor.editors.iter().all(|e| e.provenance_overlay)
&& app
.editor_layout
.inactive_groups()
.iter()
.flat_map(|g| g.editors.iter())
.all(|e| e.provenance_overlay);
assert!(
every_editor_on,
"every tab in every group carries the lens after the sync"
);
app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
app.sync_focus_flags();
assert!(
app.editor.editors.iter().all(|e| !e.provenance_overlay),
"and every tab drops it"
);
}
#[test]
fn toggle_inline_blame_command_flips_the_editor_flag_and_pref() {
let mut app = editor_app_with_lines(&["one", "two"]);
assert!(
app.inline_blame_enabled,
"inline blame is on by default (GitLens parity)"
);
app.run_command(crate::widgets::command_palette::Command::ToggleInlineBlame);
assert!(!app.inline_blame_enabled, "the command turns it off");
// sync_blame propagates the pref onto the active editor each tick.
app.sync_blame();
assert!(!app.editor.blame_enabled);
app.run_command(crate::widgets::command_palette::Command::ToggleInlineBlame);
assert!(app.inline_blame_enabled, "toggling again turns it back on");
app.sync_blame();
assert!(app.editor.blame_enabled);
}
#[test]
fn toggle_indent_guides_command_flips_every_editor_via_the_frame_sync() {
let mut app = editor_app_with_lines(&["fn a() {", " x();", "}"]);
assert!(
app.indent_guides_enabled,
"indent guides are on by default (VS Code editor.guides.indentation)"
);
app.run_command(crate::widgets::command_palette::Command::ToggleIndentGuides);
assert!(!app.indent_guides_enabled, "the command turns them off");
// The per-frame focus sync pushes the flag onto every editor in every
// group, so tabs opened after the toggle can never resurrect guides.
app.sync_focus_flags();
assert!(app.editor.editors.iter().all(|e| !e.show_indent_guides));
// A tab opened AFTER the toggle starts on the constructor default (true)
// and must be brought in line by the next frame's sync.
app.editor
.open_text_buffer(std::path::Path::new("later.rs"), "fn x() {\n y();\n}")
.unwrap();
assert!(
app.editor.show_indent_guides,
"a fresh tab starts on the default, proving the sync below does the work"
);
app.sync_focus_flags();
assert!(
app.editor.editors.iter().all(|e| !e.show_indent_guides),
"the frame sync disables guides on the tab opened after the toggle"
);
app.run_command(crate::widgets::command_palette::Command::ToggleIndentGuides);
assert!(app.indent_guides_enabled);
app.editor
.open_text_buffer(std::path::Path::new("even-later.rs"), "fn z() {}")
.unwrap();
app.sync_focus_flags();
assert!(
app.editor.editors.iter().all(|e| e.show_indent_guides),
"re-enabling reaches tabs opened before and after the toggle"
);
}
#[test]
fn toggle_bracket_colors_command_flips_every_editor_via_the_frame_sync() {
let mut app = editor_app_with_lines(&["fn a(x: u8) {}"]);
assert!(
app.bracket_colors_enabled,
"bracket colorization is on by default (VS Code default since 1.67)"
);
app.run_command(crate::widgets::command_palette::Command::ToggleBracketColors);
assert!(!app.bracket_colors_enabled, "the command turns it off");
app.editor
.open_text_buffer(std::path::Path::new("later.rs"), "g(1)")
.unwrap();
app.sync_focus_flags();
assert!(
app.editor.editors.iter().all(|e| !e.show_bracket_colors),
"the frame sync disables the tab opened after the toggle too"
);
app.run_command(crate::widgets::command_palette::Command::ToggleBracketColors);
app.sync_focus_flags();
assert!(app.editor.editors.iter().all(|e| e.show_bracket_colors));
}
#[test]
fn toggle_render_whitespace_cycles_modes_across_every_editor() {
use crate::widgets::editor::WhitespaceMode;
let mut app = editor_app_with_lines(&["a b"]);
let all_editors_in = |app: &App, mode: WhitespaceMode| {
app.editor.editors.iter().all(|e| e.whitespace_mode == mode)
};
assert_eq!(
app.whitespace_mode,
WhitespaceMode::Selection,
"selection is the default (VS Code editor.renderWhitespace)"
);
app.sync_focus_flags();
assert!(all_editors_in(&app, WhitespaceMode::Selection));
app.run_command(crate::widgets::command_palette::Command::ToggleRenderWhitespace);
assert_eq!(app.whitespace_mode, WhitespaceMode::All);
app.editor
.open_text_buffer(std::path::Path::new("later.txt"), "c d")
.unwrap();
app.sync_focus_flags();
assert!(
all_editors_in(&app, WhitespaceMode::All),
"the frame sync carries the mode to tabs opened after the toggle"
);
app.run_command(crate::widgets::command_palette::Command::ToggleRenderWhitespace);
assert_eq!(app.whitespace_mode, WhitespaceMode::None);
app.sync_focus_flags();
assert!(all_editors_in(&app, WhitespaceMode::None));
app.run_command(crate::widgets::command_palette::Command::ToggleRenderWhitespace);
assert_eq!(app.whitespace_mode, WhitespaceMode::Selection, "full cycle");
app.sync_focus_flags();
assert!(all_editors_in(&app, WhitespaceMode::Selection));
}
#[test]
fn toggle_inline_values_clears_trailers_on_disable() {
let mut app = editor_app_with_lines(&["def f():", " x = 1"]);
assert!(
app.inline_values_enabled,
"inline values are on by default (VS Code debug.inlineValues: auto)"
);
// Simulate a stop having populated trailers, then disable: every editor
// must drop them immediately, not on the next stop.
app.editor.inline_values.insert(1, String::from("x = 1"));
app.run_command(crate::widgets::command_palette::Command::ToggleInlineValues);
assert!(!app.inline_values_enabled);
assert!(
app.editor
.editors
.iter()
.all(|e| e.inline_values.is_empty()),
"disabling clears the trailers in every editor"
);
app.run_command(crate::widgets::command_palette::Command::ToggleInlineValues);
assert!(app.inline_values_enabled, "round trip");
}
#[test]
fn editor_cmd_gg_jumps_to_top_of_file() {
let mut app = editor_app_with_lines(&["a", "b", "c", "d"]);
app.editor.cursor_row = 3;
app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
.unwrap();
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 0));
}
#[test]
fn editor_cmd_g_then_plain_g_also_jumps_to_top() {
let mut app = editor_app_with_lines(&["a", "b", "c", "d"]);
app.editor.cursor_row = 3;
app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('g'), KeyModifiers::NONE))
.unwrap();
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 0));
}
#[test]
fn editor_cmd_g_count_g_jumps_to_specific_line() {
let mut app = editor_app_with_lines(&["a", "b", "c", "d", "e"]);
app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('3'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('g'), KeyModifiers::NONE))
.unwrap();
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (2, 0));
}
#[test]
fn editor_cmd_g_multidigit_count_g_jumps_to_specific_line() {
let mut app = editor_app_with_lines(&(0..30).map(|_| "x").collect::<Vec<_>>());
app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('1'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('2'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('g'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.cursor_row, 11);
}
#[test]
fn editor_cmd_shift_g_jumps_to_bottom_of_file() {
let mut app = editor_app_with_lines(&["a", "b", "c", "d"]);
app.handle_key(key(
KeyCode::Char('G'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(app.editor.cursor_row, 3);
assert_ne!(
app.sidebar_view,
SidebarView::SourceControl,
"cmd+shift+g in editor pane must NOT hijack to source control"
);
}
#[test]
fn editor_cmd_d_now_selects_the_word_instead_of_deleting() {
// Cmd+D moved from the old `Cmd+d d` delete-line convenience to VS Code's
// "Add Selection to Next Find Match"; delete-line now lives on Cmd+Shift+K.
let mut app = editor_app_with_lines(&["alpha", "beta", "gamma"]);
app.editor.cursor_row = 1;
app.handle_key(key(KeyCode::Char('d'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(
app.editor.lines,
vec!["alpha", "beta", "gamma"],
"Cmd+D no longer deletes the line"
);
assert!(
app.editor.selection.is_some(),
"Cmd+D selects the word under the cursor"
);
}
#[test]
fn editor_cmd_yy_does_not_modify_buffer() {
let mut app = editor_app_with_lines(&["alpha", "beta", "gamma"]);
app.editor.cursor_row = 1;
app.handle_key(key(KeyCode::Char('y'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('y'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(app.editor.lines, vec!["alpha", "beta", "gamma"]);
assert!(app.status.starts_with("Yanked"));
}
#[test]
fn editor_chord_cancels_on_unrelated_key() {
let mut app = editor_app_with_lines(&["alpha"]);
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('d'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines, vec!["alphax"]);
}
#[test]
fn editor_ctrl_a_jumps_to_start_of_line() {
let mut app = editor_app_with_lines(&["hello world"]);
app.editor.cursor_col = 7;
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::CONTROL))
.unwrap();
assert_eq!(app.editor.cursor_col, 0);
}
#[test]
fn editor_ctrl_e_jumps_to_end_of_line() {
let mut app = editor_app_with_lines(&["hello world"]);
app.editor.cursor_col = 3;
app.handle_key(key(KeyCode::Char('e'), KeyModifiers::CONTROL))
.unwrap();
assert_eq!(app.editor.cursor_col, 11);
}
#[test]
fn editor_ctrl_k_kills_to_end_of_line() {
let mut app = editor_app_with_lines(&["hello world", "next"]);
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::CONTROL))
.unwrap();
assert_eq!(app.editor.lines, vec!["hello", "next"]);
}
#[test]
fn editor_cmd_count_gg_jumps_to_line_with_leading_count() {
let mut app = editor_app_with_lines(&["a", "b", "c", "d", "e"]);
app.handle_key(key(KeyCode::Char('3'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('g'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(app.editor.cursor_row, 2);
}
#[test]
fn editor_cmd_count_yy_yanks_n_lines_with_leading_count() {
let mut app = editor_app_with_lines(&["a", "b", "c", "d"]);
app.editor.cursor_row = 0;
app.handle_key(key(KeyCode::Char('2'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('y'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('y'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(app.editor.lines, vec!["a", "b", "c", "d"]);
assert!(app.status.contains("Yanked 2"));
}
#[test]
fn editor_cmd_count_then_shift_g_jumps_to_specific_line() {
let mut app = editor_app_with_lines(&["a", "b", "c", "d", "e"]);
app.handle_key(key(KeyCode::Char('4'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(
KeyCode::Char('G'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(app.editor.cursor_row, 3);
}
#[test]
fn editor_ctrl_u_kills_to_start_of_line() {
let mut app = editor_app_with_lines(&["hello world"]);
app.editor.cursor_col = 6;
app.handle_key(key(KeyCode::Char('u'), KeyModifiers::CONTROL))
.unwrap();
assert_eq!(app.editor.lines, vec!["world"]);
assert_eq!(app.editor.cursor_col, 0);
}
#[test]
fn editor_cmd_o_opens_line_below_with_indent() {
let mut app = editor_app_with_lines(&[" foo", "bar"]);
app.editor.cursor_row = 0;
app.editor.cursor_col = 4;
app.handle_key(key(KeyCode::Char('o'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(app.editor.lines, vec![" foo", " ", "bar"]);
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 4));
}
#[test]
fn editor_cmd_shift_enter_opens_line_above_with_indent() {
// Open-line-above moved off Cmd+Shift+O (now Go to Symbol) onto its real
// VS Code chord, Cmd+Shift+Enter.
let mut app = editor_app_with_lines(&["foo", " bar"]);
app.editor.cursor_row = 1;
app.editor.cursor_col = 6;
app.handle_key(key(
KeyCode::Enter,
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(app.editor.lines, vec!["foo", " ", " bar"]);
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 4));
}
#[test]
fn editor_cmd_shift_o_opens_go_to_symbol() {
let mut app = editor_app_with_lines(&["fn foo() {}", "fn bar() {}"]);
app.editor.path = Some(std::path::PathBuf::from("lib.rs"));
app.focus_pane(Pane::Editor);
app.handle_key(key(
KeyCode::Char('O'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert!(
app.go_to_symbol.is_some(),
"Cmd+Shift+O must open the Go to Symbol picker"
);
}
#[test]
fn f1_opens_the_shortcuts_modal_from_any_focus() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
.unwrap();
assert!(
app.shortcuts_modal.is_some(),
"F1 must open the shortcuts panel"
);
}
#[test]
fn esc_closes_the_shortcuts_modal_and_restores_normal_input() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(
app.shortcuts_modal.is_none(),
"Esc must dismiss the shortcuts panel"
);
}
#[test]
fn shortcuts_modal_swallows_keys_so_editor_does_not_receive_them() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.lines = vec![String::from("hello")];
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.lines,
vec!["hello"],
"while the shortcuts modal is open, typed letters must not leak into the editor buffer"
);
}
#[test]
fn opening_the_shortcuts_modal_arms_one_image_clear_so_iterm_evicts_cached_osc_1337_cells() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
.unwrap();
assert!(
app.consume_shortcuts_image_clear(),
"F1 must arm terminal.clear() so iTerm2's image cache (activity bar icons, welcome wordmark, editor preview) is wiped before the modal paints, otherwise those cached image cells bleed through the modal text"
);
assert!(
!app.consume_shortcuts_image_clear(),
"the flag is one-shot — a second consume call must return false so the driver does not re-clear every frame"
);
}
#[test]
fn closing_the_shortcuts_modal_arms_image_clear_and_re_dirties_overlays() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
.unwrap();
let _ = app.consume_shortcuts_image_clear();
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(
app.consume_shortcuts_image_clear(),
"Esc must also arm terminal.clear() so the modal's text cells get wiped and the activity bar / welcome wordmark / hero icons can be re-emitted cleanly"
);
assert!(app.overlays.activity.dirty());
assert!(app.overlays.welcome.is_dirty());
assert!(app.overlays.hero.is_dirty());
}
#[test]
fn ssh_empty_state_overlay_arms_image_clear_when_user_switches_off_remote_view() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Simulate the post-emit state without actually writing OSC bytes.
app.overlays.ssh.set_displayed(true);
app.set_sidebar_view(SidebarView::Explorer);
app.flush_ssh_empty_state_overlay();
assert!(
app.consume_ssh_empty_state_image_clear(),
"leaving the Remote view after the illustration was painted must arm one terminal.clear() so iTerm2 evicts the cached image cells — otherwise the server-rack PNG ghosts onto the Explorer tree the user just clicked to"
);
assert!(!app.overlays.ssh.is_displayed());
}
#[test]
fn ssh_empty_state_overlay_arms_image_clear_when_modal_opens_on_top() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Remote);
app.overlays.ssh.set_displayed(true);
app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
.unwrap();
app.flush_ssh_empty_state_overlay();
assert!(
app.consume_ssh_empty_state_image_clear(),
"F1 opening the shortcuts modal over the SSH empty state must arm an image-clear so the illustration doesn't bleed through the modal text"
);
}
#[test]
fn activity_icons_stay_visible_beside_the_centered_shortcuts_modal() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.activity.set_images(dummy_activity_images());
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let before = app.pending_activity_image_overlays().len();
assert_eq!(
before, 12,
"precondition: eight view icons + the settings gear + the three layout toolbar icons emit"
);
app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
.unwrap();
term.draw(|f| app.render(f)).unwrap();
let during = app.pending_activity_image_overlays().len();
assert_eq!(
during, before,
"the shortcuts modal is centered over the editor column, so the far-left activity-bar icons it does not cover must keep re-emitting — otherwise the terminal.clear() armed by F1 wipes iTerm2's cached cells and the icons vanish for the whole time the modal is up; saw {before} icons before opening"
);
}
#[test]
fn activity_icons_behind_a_modal_that_reaches_the_left_edge_are_suppressed() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.activity.set_images(dummy_activity_images());
let backend = ratatui::backend::TestBackend::new(40, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let before = app.pending_activity_image_overlays().len();
app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
.unwrap();
term.draw(|f| app.render(f)).unwrap();
let during = app.pending_activity_image_overlays().len();
assert!(
during < before || before == 0,
"on a terminal narrow enough that the centered modal reaches column 0, icons whose blocks intersect the modal must be suppressed so they don't ghost over the modal text; saw {before} icons before, {during} during"
);
}
#[test]
fn settings_gear_is_bottom_anchored_below_the_view_icons() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.activity.set_images(dummy_activity_images());
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let gear = app.sidebar_areas.settings_icon;
let run_debug = app.sidebar_areas.run_debug_icon;
assert!(gear.width > 0, "gear must lay out on a tall bar");
assert!(
gear.y > run_debug.y,
"the gear is anchored at the bottom, below the Run-and-Debug view icon"
);
assert_eq!(
app.pending_activity_image_overlays().len(),
12,
"eight view icons + the settings gear + the three layout toolbar icons emit"
);
}
#[test]
fn settings_gear_bottom_inset_matches_the_view_icon_top_inset() {
// The view icons start one cell below the bar's top edge
// (`activity_explorer_y` = `bar.y + 1`). The gear must leave the same
// one-cell gap above the status bar instead of hugging the bottom row,
// so the bar reads as vertically balanced rather than bottom-heavy.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.activity.set_images(dummy_activity_images());
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let explorer = app.sidebar_areas.explorer_icon;
let gear = app.sidebar_areas.settings_icon;
assert!(gear.width > 0, "gear must lay out on a tall bar");
// The activity bar spans every row except the single status-bar row.
let bar_bottom = app.last_frame_area.height - 1 - 1;
let top_inset = explorer.y - app.last_frame_area.y;
let bottom_inset = bar_bottom - (gear.y + gear.height - 1);
assert_eq!(
bottom_inset, top_inset,
"the gap below the gear must equal the gap above the first view icon"
);
}
#[test]
fn clicking_the_gear_opens_the_color_theme_menu_then_the_picker() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.activity.set_images(dummy_activity_images());
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let gear = app.sidebar_areas.settings_icon;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
column: gear.x,
row: gear.y,
modifiers: KeyModifiers::NONE,
});
let menu = app.context_menu.as_ref().expect("gear opens a menu");
assert!(
matches!(
menu.items.as_slice(),
[
MenuEntry::Item {
action: MenuAction::OpenThemePicker,
..
},
MenuEntry::Item {
action: MenuAction::OpenCustomizeLayout,
..
}
]
),
"the gear menu holds Color Theme then Customize Layout"
);
// Selecting Color Theme replaces the menu with the theme picker.
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
let picker = app.context_menu.as_ref().expect("picker opens");
assert_eq!(picker.items.len(), crate::theme::Theme::all().len());
assert!(
picker
.items
.iter()
.all(|e| matches!(e.action(), Some(MenuAction::SetTheme(_)))),
"every picker row switches a theme"
);
}
#[test]
fn applying_a_theme_switches_the_active_theme_and_arms_a_repaint() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert_eq!(
app.theme,
crate::theme::Theme::BLACK,
"fresh install defaults to the black theme"
);
app.apply_theme(crate::theme::Theme::DARK_BLUE);
assert_eq!(app.theme, crate::theme::Theme::DARK_BLUE);
// A theme switch arms a one-shot clear so iTerm2 evicts the stale-bg
// image layer and the whole screen repaints on the new background.
assert!(app.consume_activity_image_clear());
}
#[test]
fn shortcuts_modal_scrolls_down_then_back_to_top_via_keys() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
.unwrap();
let modal = app.shortcuts_modal.as_mut().unwrap();
modal.last_inner_height = 5;
modal.last_content_height = 50;
app.handle_key(key(KeyCode::PageDown, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.shortcuts_modal.as_ref().unwrap().scroll, 10);
app.handle_key(key(KeyCode::Home, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.shortcuts_modal.as_ref().unwrap().scroll, 0);
}
#[test]
fn cmd_p_opens_the_file_finder_modal_for_quick_open() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
assert!(
app.file_finder.is_some(),
"Cmd+P must open the Quick Open file finder modal so the user can type a name and jump to a file the way VS Code does"
);
}
#[test]
fn ctrl_p_opens_the_file_finder_modal_on_systems_without_super() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::CONTROL))
.unwrap();
assert!(
app.file_finder.is_some(),
"Ctrl+P must also open the Quick Open finder so the chord works on Linux / iTerm2 sessions that report CONTROL rather than SUPER"
);
}
#[test]
fn plain_p_keystroke_does_not_open_the_file_finder() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::NONE))
.unwrap();
assert!(
app.file_finder.is_none(),
"an unmodified 'p' must reach the editor / tree typeahead and never trigger the modal"
);
}
#[test]
fn esc_closes_the_file_finder_modal() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(
app.file_finder.is_none(),
"Esc must dismiss the file finder"
);
}
/// Issue #207: the light theme must recolor the HOST terminal too. The
/// portable OSC 10/11 pair carries the theme's fg/bg to Ghostty and every
/// other host (iTerm2 additionally gets its sRGB override), and the
/// panic/exit restore must hand the user's own colors back.
#[test]
fn host_dynamic_colors_follow_the_theme() {
let light = crate::theme::Theme::from_id("light");
let seq = super::host_colors_seq(light);
assert!(
seq.contains("\x1b]11;rgb:ff/ff/ff"),
"light background must reach the host via OSC 11"
);
assert!(
seq.contains("\x1b]10;rgb:3b/3b/3b"),
"light foreground must reach the host via OSC 10"
);
let black = super::host_colors_seq(crate::theme::Theme::BLACK);
assert!(black.contains("\x1b]11;rgb:00/00/00"));
assert!(
String::from_utf8_lossy(super::TERMINAL_RESTORE_SEQ).contains("\x1b]110\x07\x1b]111\x07"),
"the panic/exit restore must reset the host's own colors"
);
}
/// Issue #207: under Croft Light the quick-input popups must paint light
/// chrome, not the historical hardcoded dark constants. Renders the Cmd+P
/// finder under both a dark theme and the light theme and inspects actual
/// buffer cells: dark stays byte-identical to the legacy palette, light
/// lands on the VS Code Light Modern quick-input fill with dark text.
#[test]
fn quick_open_popup_follows_the_light_theme() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
std::fs::write(tmp.path().join("beta.rs"), "").unwrap();
for (theme, want_bg, dark_text) in [
(
crate::theme::Theme::DARK_BLUE,
ratatui::style::Color::Rgb(0x16, 0x18, 0x1f),
false,
),
(
crate::theme::Theme::from_id("light"),
ratatui::style::Color::Rgb(0xf8, 0xf8, 0xf8),
true,
),
] {
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.apply_theme(theme);
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let finder = app.file_finder.as_ref().unwrap();
// Probe the SECOND result row: the first wears the selection fill,
// the second the plain popup body.
let (x, y) = (finder.last_rect.x + 4, finder.last_rect.y + 4);
let cell = &term.backend().buffer()[(x, y)];
assert_eq!(
cell.bg,
want_bg,
"{}: the finder body must wear the theme's popup fill",
theme.id()
);
if dark_text {
let ratatui::style::Color::Rgb(r, g, b) = cell.fg else {
panic!("light finder text must be an Rgb color, got {:?}", cell.fg)
};
let luma = 0.299 * f32::from(r) + 0.587 * f32::from(g) + 0.114 * f32::from(b);
assert!(
luma < 128.0,
"light finder text must be dark on the white popup, got {:?}",
cell.fg
);
}
}
}
/// Issue #225: the selected activity-bar icon must stay visible on the light
/// theme, and stay distinguishable from the unselected ones. Renders the bar
/// (glyph fallback path) under Croft Light and reads the real cells: the
/// selected Explorer glyph carries VS Code's `activityBar.foreground`, an
/// unselected glyph the lighter `inactiveForeground`, and neither is the bar
/// background.
#[test]
fn the_selected_activity_icon_is_visible_on_the_light_theme() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let light = crate::theme::Theme::from_id("light");
app.apply_theme(light);
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let buf = term.backend().buffer();
let cell_of = |glyph: char| {
(0..40u16)
.flat_map(|y| (0..4u16).map(move |x| (x, y)))
.find(|&(x, y)| buf[(x, y)].symbol() == glyph.to_string())
.map(|(x, y)| buf[(x, y)].clone())
.unwrap_or_else(|| panic!("the activity bar must paint {glyph:?}"))
};
// Explorer is the sidebar view every workspace opens on, so it is the
// selected icon here; Search is not.
let selected = cell_of(crate::icons::ACTIVITY_EXPLORER);
let resting = cell_of(crate::icons::ACTIVITY_SEARCH);
assert_eq!(
selected.fg,
light.activity_icon_active(),
"the selected icon wears activityBar.foreground, not the white that vanishes on a light bar"
);
assert_eq!(resting.fg, light.activity_icon_inactive());
assert_ne!(
selected.fg, resting.fg,
"selection must be readable from the icon itself, not only from the pill"
);
assert_ne!(
selected.fg, selected.bg,
"the selected glyph must not be painted in the bar's own background"
);
}
/// Issue #217: the Explorer's file names were white-on-white under Croft
/// Light (a bare `Color::White` that bypassed the theme adapter). Render
/// the tree under the light theme and inspect the actual name cell: the
/// text must be dark, and under a dark theme it must stay white.
#[test]
fn explorer_names_are_legible_on_the_light_theme() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
for (theme, want_dark) in [
(crate::theme::Theme::DARK_BLUE, false),
(crate::theme::Theme::from_id("light"), true),
] {
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.apply_theme(theme);
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
// Find the cell where "alpha.rs" is painted in the tree column.
let buf = term.backend().buffer();
let mut found = None;
'rows: for y in 0..40u16 {
for x in 0..40u16 {
if buf[(x, y)].symbol() == "a"
&& buf[(x + 1, y)].symbol() == "l"
&& buf[(x + 2, y)].symbol() == "p"
&& buf[(x + 3, y)].symbol() == "h"
{
found = Some((x, y));
break 'rows;
}
}
}
let (x, y) = found.expect("alpha.rs must be visible in the Explorer");
let fg = buf[(x, y)].fg;
if want_dark {
let ratatui::style::Color::Rgb(r, g, b) = fg else {
panic!("light tree names must resolve to Rgb, got {fg:?}")
};
let luma = 0.299 * f32::from(r) + 0.587 * f32::from(g) + 0.114 * f32::from(b);
assert!(luma < 128.0, "tree name must be dark on white, got {fg:?}");
} else {
assert_eq!(
fg,
ratatui::style::Color::White,
"dark themes keep the historical white tree names"
);
}
}
}
/// Issue #205: Cmd+P search results must be mouse clickable. A left click on
/// a result row confirms that row (the way VS Code's quick-pick behaves):
/// it opens the clicked file, not the keyboard-selected one, and dismisses
/// the finder.
#[test]
fn clicking_a_file_finder_row_opens_that_file() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
std::fs::write(tmp.path().join("beta.rs"), "").unwrap();
std::fs::write(tmp.path().join("gamma.rs"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let finder = app.file_finder.as_ref().unwrap();
assert!(
finder.results.len() >= 3,
"the three seeded files must all be indexed"
);
// The list body starts three rows below the popup top (border, prompt,
// separator). Row 1 of the list is the SECOND result - clicking it must
// open that entry, not the keyboard selection parked on row 0.
let col = finder.last_rect.x + 4;
let row = finder.last_rect.y + 3 + 1;
let expected = finder.results[1].entry.path.clone();
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert!(
app.file_finder.is_none(),
"a click on a result row must confirm the pick and dismiss the finder"
);
assert_eq!(
app.editor.path.as_deref(),
Some(expected.as_path()),
"the clicked row's file must be the one that opens"
);
}
/// A click inside the popup but off the result rows (the query prompt line)
/// must neither open a file nor dismiss the finder - only clicks OUTSIDE the
/// popup close it, and only clicks ON a row confirm it.
#[test]
fn clicking_the_file_finder_prompt_line_is_inert() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let finder = app.file_finder.as_ref().unwrap();
let col = finder.last_rect.x + 4;
let prompt_row = finder.last_rect.y + 1;
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
col,
prompt_row,
));
assert!(
app.file_finder.is_some(),
"a click on the query line must not dismiss the finder"
);
assert_eq!(
app.editor.path, None,
"a click on the query line must not open anything"
);
}
/// A click on an empty list row (inside the popup, below the last result)
/// maps to no result and must be inert rather than opening some file or
/// closing the popup.
#[test]
fn clicking_below_the_last_file_finder_result_is_inert() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let finder = app.file_finder.as_ref().unwrap();
let results = finder.results.len();
let col = finder.last_rect.x + 4;
// One row past the last result, still inside the popup body.
let row = finder.last_rect.y + 3 + results as u16;
assert!(
row < finder.last_rect.y + finder.last_rect.height - 1,
"the empty row must land inside the popup for this test to mean anything"
);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert!(
app.file_finder.is_some(),
"a click on an empty list row must not dismiss the finder"
);
assert_eq!(
app.editor.path, None,
"a click on an empty list row must not open anything"
);
}
/// The command palette shares the quick-pick anatomy, so its rows must be
/// clickable too: a left click on a result row runs that command and
/// dismisses the palette.
#[test]
fn clicking_a_command_palette_row_runs_that_command() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(
KeyCode::Char('p'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert!(
app.command_palette.is_some(),
"Cmd+Shift+P must open the palette"
);
for c in "keyboard shortcuts reference".chars() {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let palette = app.command_palette.as_ref().unwrap();
assert!(
!palette.results.is_empty(),
"the query must keep the Help: Keyboard Shortcuts Reference command"
);
let col = palette.last_rect.x + 4;
let row = palette.last_rect.y + 3;
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert!(
app.command_palette.is_none(),
"a click on a palette row must run the command and dismiss the palette"
);
assert!(
app.shortcuts_modal.is_some(),
"the clicked command (Help: Keyboard Shortcuts Reference) must actually run"
);
}
#[test]
fn typing_in_file_finder_fuzzy_filters_the_result_list() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
std::fs::create_dir(tmp.path().join("sub")).unwrap();
std::fs::write(tmp.path().join("sub").join("beta.rs"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('b'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('e'), KeyModifiers::NONE))
.unwrap();
let finder = app
.file_finder
.as_ref()
.expect("finder must still be open while typing");
let names: Vec<String> = finder
.visible_results()
.iter()
.map(|r| r.entry.rel.clone())
.collect();
assert!(
names.iter().any(|n| n == "sub/beta.rs"),
"typing 'be' must keep sub/beta.rs in the result list — got {names:?}"
);
assert!(
!names.iter().any(|n| n == "alpha.rs"),
"typing 'be' must drop alpha.rs because 'be' is not a subsequence of 'alpha.rs' — got {names:?}"
);
}
#[test]
fn enter_in_file_finder_opens_the_selected_file_and_closes_the_modal() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "fn main() {}").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(
app.file_finder.is_none(),
"Enter must close the modal after opening the file"
);
let opened = app
.editor
.path
.as_ref()
.expect("the active tab must now have a path");
assert_eq!(
opened.file_name().and_then(|n| n.to_str()),
Some("alpha.rs"),
"Enter must open the highlighted entry (alpha.rs) into the active editor tab"
);
}
/// #465: a viewer runs the declared program on the file in a pane of its own,
/// with `{file}` replaced by the file's path, and the pane takes focus. The
/// program here is `sh`, so nothing has to be installed for the test.
#[test]
fn opening_a_file_in_a_viewer_runs_the_tool_on_it_in_a_new_terminal_pane() {
let tmp = tempfile::tempdir().unwrap();
let data = tmp.path().join("data.csv");
std::fs::write(&data, "a,b\n1,2\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.consented_extensions.insert("csvlens".into());
let before = app.terminals.len();
let viewer = crate::mcp::registry::ContributedViewer {
ext_id: "csvlens".into(),
id: "csvlens".into(),
label: "Open in csvlens".into(),
command: "/bin/sh".into(),
args: vec![
"-c".into(),
"echo VIEWING \"$1\"; sleep 30".into(),
"sh".into(),
"{file}".into(),
],
extensions: vec!["csv".into()],
provision: None,
};
app.open_in_viewer(&viewer, &data);
assert_eq!(
app.terminals.len(),
before + 1,
"the viewer gets a pane of its own"
);
assert!(app.show_terminal, "the panel is shown");
assert!(
matches!(app.focus, Pane::Terminal),
"and the pane takes focus"
);
let want = format!("VIEWING {}", data.display());
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the viewer to print the file it was handed",
|| app.terminal().visible_text().contains(&want),
);
}
/// A file name that is not valid UTF-8 must not be handed to the viewer
/// mangled (#485 review): the tool would open a different path and fail.
/// Until the pane spawn can carry OS-native arguments, such a file is
/// refused with a status line rather than opened wrong.
#[cfg(unix)]
#[test]
fn a_viewer_refuses_a_path_it_cannot_pass_faithfully() {
use std::os::unix::ffi::OsStrExt;
let tmp = tempfile::tempdir().unwrap();
// The file is deliberately not created: APFS refuses such a name, and
// the guard fires before the viewer path touches the disk anyway.
let odd = tmp
.path()
.join(std::ffi::OsStr::from_bytes(b"d\xffata.csv"));
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let viewer = crate::mcp::registry::ContributedViewer {
ext_id: "csvlens".into(),
id: "csvlens".into(),
label: "Open in csvlens".into(),
command: "/bin/sh".into(),
args: vec!["-c".into(), "sleep 30".into(), "sh".into(), "{file}".into()],
extensions: vec!["csv".into()],
provision: None,
};
let before = app.terminals.len();
app.open_in_viewer(&viewer, &odd);
assert_eq!(
app.terminals.len(),
before,
"no pane is spawned for a path that cannot be passed"
);
assert!(
app.status.contains("not valid UTF-8"),
"the status says why: {:?}",
app.status
);
}
/// A viewer spawns a program from a manifest, so it passes the same
/// first-run consent gate a sidecar does (#485 review): the first use of an
/// extension's viewer shows the exact command line and spawns nothing until
/// the user allows it; a consented extension runs straight away.
#[test]
fn a_viewer_asks_for_consent_before_its_first_run() {
let tmp = tempfile::tempdir().unwrap();
let data = tmp.path().join("data.csv");
std::fs::write(&data, "a,b\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let viewer = crate::mcp::registry::ContributedViewer {
ext_id: format!("consent-test-{}", std::process::id()),
id: "csvlens".into(),
label: "Open in csvlens".into(),
command: "/bin/sh".into(),
args: vec!["-c".into(), "sleep 30".into(), "sh".into(), "{file}".into()],
extensions: vec!["csv".into()],
provision: None,
};
let before = app.terminals.len();
app.open_in_viewer(&viewer, &data);
assert_eq!(app.terminals.len(), before, "nothing spawns before consent");
let prompt = app
.input_prompt
.as_ref()
.expect("the consent prompt is open");
assert!(
prompt.title.contains(&viewer.ext_id) && prompt.title.contains("/bin/sh"),
"the prompt names the extension and the exact command: {:?}",
prompt.title
);
}
/// A scratch config dir holding the given user extension manifests
/// (`<id>` → manifest text). An app pointed at it (`app.config_dir`) reads
/// its extensions and consent from there and nowhere else; the process
/// environment is never touched, so the test is safe beside every other.
fn scratch_config(manifests: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let croft = tmp.path().join("croft");
for (id, text) in manifests {
let dir = croft.join("extensions").join(id);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("extension.toml"), text).unwrap();
}
(tmp, croft)
}
/// The consent set recorded in a scratch config dir.
fn consent_on_disk(croft: &Path) -> std::collections::BTreeSet<String> {
crate::prefs::Prefs::load(&croft.join("config.json"))
.unwrap_or_default()
.mcp_consented
}
/// One consent per extension, read from one place (#485 review): the sidecar
/// gate consults the same session set the viewer gate does, so allowing an
/// extension through either gate satisfies the other in the same session,
/// whatever became of the prefs write. And a prefs write that fails is
/// reported before the command's own argument prompt takes the screen.
#[test]
fn the_sidecar_gate_reads_the_session_consent_set() {
use crate::widgets::input_prompt::InputPurpose;
const EXT: &str = r#"
id = "tconsent"
name = "tconsent"
api_version = 1
[[mcp_servers]]
id = "srv"
command = "/bin/false"
[[commands]]
id = "tconsent.go"
title = "tconsent: go"
server = "srv"
tool = "go"
arg = "q"
prompt = "Query"
"#;
let (_scratch, croft) = scratch_config(&[("tconsent", EXT)]);
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.config_dir = croft.clone();
app.consented_extensions = consent_on_disk(&croft);
// Allowed this session, not (yet) on disk: the gate must not re-prompt,
// it must move on to the command's own argument prompt.
app.consented_extensions.insert("tconsent".into());
app.run_extension_command("tconsent.go");
assert!(
matches!(
app.input_prompt.as_ref().map(|p| &p.purpose),
Some(InputPurpose::McpArg { .. })
),
"a consented extension goes straight to its argument prompt, not consent: {:?}",
app.input_prompt.as_ref().map(|p| p.title.clone())
);
// Allowing through the sidecar prompt with the prefs file unwritable: the
// failure is reported where the user can see it and the grant holds.
app.close_input_prompt();
app.consented_extensions.remove("tconsent");
std::fs::create_dir_all(croft.join("config.json")).unwrap();
app.run_extension_command("tconsent.go");
assert!(
matches!(
app.input_prompt.as_ref().map(|p| &p.purpose),
Some(InputPurpose::McpConsent { .. })
),
"fixture: an unconsented extension is asked first"
);
app.submit_input_prompt();
assert!(
app.status.contains("could not be saved"),
"a failed prefs write is reported: {:?}",
app.status
);
assert!(
matches!(
app.input_prompt.as_ref().map(|p| &p.purpose),
Some(InputPurpose::McpArg { .. })
),
"and the command went on to its argument prompt"
);
assert!(
app.consented_extensions.contains("tconsent"),
"the session grant holds"
);
}
/// Allowing a viewer records the consent and resumes the open that asked;
/// a prefs write that fails is said in the status rather than swallowed.
#[test]
fn allowing_a_viewer_records_consent_and_resumes_the_open() {
const EXT: &str = r#"
id = "tviewer"
name = "tviewer"
api_version = 1
[[viewers]]
id = "sh"
label = "Open in sh"
command = "/bin/sh"
args = ["-c", "sleep 30", "sh", "{file}"]
extensions = ["csv"]
"#;
let (_scratch, croft) = scratch_config(&[("tviewer", EXT)]);
let tmp = tempfile::tempdir().unwrap();
let data = tmp.path().join("data.csv");
std::fs::write(&data, "a,b\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.config_dir = croft.clone();
app.consented_extensions = consent_on_disk(&croft);
let viewer = crate::mcp::registry::viewer_by_id_in_dir(&croft, "tviewer/sh")
.expect("the scratch viewer");
let before = app.terminals.len();
app.open_in_viewer(&viewer, &data);
assert!(
app.input_prompt.is_some(),
"fixture: consent is asked first"
);
app.submit_input_prompt();
assert_eq!(app.terminals.len(), before + 1, "allowing resumes the open");
assert!(
app.consented_extensions.contains("tviewer"),
"and records the consent"
);
let saved = consent_on_disk(&croft);
assert!(saved.contains("tviewer"), "on disk too: {saved:?}");
assert!(
!app.status.contains("could not be saved"),
"a successful save is not reported as a failure: {:?}",
app.status
);
// Now with the prefs file made unwritable (a directory in its place):
// the consent still holds for the session and the status says the save
// failed, instead of the failure vanishing.
app.consented_extensions.remove("tviewer");
let _ = std::fs::remove_file(croft.join("config.json"));
std::fs::create_dir_all(croft.join("config.json")).unwrap();
app.open_in_viewer(&viewer, &data);
app.submit_input_prompt();
assert!(
app.status.contains("could not be saved"),
"a failed prefs write is reported: {:?}",
app.status
);
assert!(
app.consented_extensions.contains("tviewer"),
"the session grant still holds"
);
}
/// The Explorer row and the palette row for a viewer are built from the
/// same config dir the click resolves them through: a viewer installed only
/// under the app's dir gets its row, and the row opens.
#[test]
fn a_viewer_row_is_built_and_resolved_through_the_same_config_dir() {
const EXT: &str = r#"
id = "tviewer"
name = "tviewer"
api_version = 1
[[viewers]]
id = "sh"
label = "Open in sh"
command = "/bin/sh"
args = ["-c", "sleep 30", "sh", "{file}"]
extensions = ["csv"]
"#;
let (_scratch, croft) = scratch_config(&[("tviewer", EXT)]);
let tmp = tempfile::tempdir().unwrap();
let csv = tmp.path().join("data.csv");
std::fs::write(&csv, "a,b\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.config_dir = croft.clone();
app.consented_extensions = consent_on_disk(&croft);
app.consented_extensions.insert("tviewer".into());
let n = file_node(&csv);
let items = build_tree_context_menu_items_in_dir(
&croft,
Some(&n),
tmp.path(),
std::slice::from_ref(&csv),
tmp.path(),
None,
None,
);
let row = items
.iter()
.find_map(|(label, a)| match a {
MenuAction::OpenInViewer(id, p) if p == &csv => Some((label.clone(), id.clone())),
_ => None,
})
.expect("the viewer under the app's config dir gets a row");
assert_eq!(row, ("Open in sh".to_string(), "tviewer/sh".to_string()));
let before = app.terminals.len();
app.dispatch_menu_action(
MenuAction::OpenInViewer(row.1.clone(), csv.clone()),
tmp.path().to_path_buf(),
);
assert_eq!(
app.terminals.len(),
before + 1,
"and the row resolves and opens"
);
let palette_ids: Vec<String> = crate::mcp::registry::contributed_viewer_commands_in_dir(&croft)
.into_iter()
.map(|c| c.id)
.collect();
assert!(
palette_ids.iter().any(|id| id == "viewer:tviewer/sh"),
"the palette row comes from the same dir: {palette_ids:?}"
);
}
/// Uninstalling an extension forgets its consent, in the session and on
/// disk: a later re-add is a fresh install of a program the user has not
/// approved this time, so the first-run gate asks again. The disabled state
/// it clears lands in the same config file.
#[test]
fn uninstalling_an_extension_forgets_its_consent() {
let (_scratch, croft) = scratch_config(&[]);
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.config_dir = croft.clone();
app.consented_extensions = consent_on_disk(&croft);
crate::prefs::save_mcp_consent_in(&croft, "csvlens").unwrap();
app.consented_extensions.insert("csvlens".into());
app.disabled_extensions.insert("csvlens".into());
crate::prefs::save_disabled_extensions_in(&croft, &app.disabled_extensions).unwrap();
app.perform_extension_uninstall("csvlens");
let disabled_on_disk = crate::prefs::Prefs::load(&croft.join("config.json"))
.unwrap_or_default()
.disabled_extensions;
assert!(
!disabled_on_disk.contains("csvlens"),
"the disabled state is cleared in the app's own config file: {disabled_on_disk:?}"
);
assert!(
app.status.starts_with("Uninstalled"),
"fixture: the catalog entry uninstalls cleanly: {:?}",
app.status
);
assert!(
!app.consented_extensions.contains("csvlens"),
"the session grant is gone"
);
let saved = consent_on_disk(&croft);
assert!(
!saved.contains("csvlens"),
"and so is the one on disk: {saved:?}"
);
}
/// A viewer that is gone by the time its menu row is clicked, or by the time
/// its consent prompt is allowed (the extension was removed in between),
/// must say so rather than do nothing: a silent click reads as a broken
/// menu. Neither path spawns anything or records consent for a viewer it
/// could not find.
#[test]
fn a_vanished_viewer_is_reported_from_the_menu_and_the_consent_prompt() {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let tmp = tempfile::tempdir().unwrap();
let data = tmp.path().join("data.csv");
std::fs::write(&data, "a,b\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let before = app.terminals.len();
let key = format!("vanished-ext-{}/csvlens", std::process::id());
app.status.clear();
app.dispatch_menu_action(
MenuAction::OpenInViewer(key.clone(), data.clone()),
tmp.path().to_path_buf(),
);
assert_eq!(app.terminals.len(), before, "the menu click spawns nothing");
assert!(
app.status.contains("no longer"),
"the click says the viewer is gone: {:?}",
app.status
);
app.status.clear();
app.open_input_prompt(
InputPrompt::new(
InputPurpose::ViewerConsent {
key: key.clone(),
path: data,
},
"Allow",
"",
)
.with_value("allow"),
);
app.submit_input_prompt();
assert!(app.input_prompt.is_none(), "the prompt closes");
assert_eq!(app.terminals.len(), before, "allowing spawns nothing");
assert!(
app.status.contains("no longer"),
"allowing says the viewer is gone: {:?}",
app.status
);
assert!(
!app.consented_extensions
.iter()
.any(|e| key.starts_with(e.as_str())),
"no consent is recorded for a viewer that could not be found"
);
}
/// #465: the palette row reaches the viewer route (not the MCP command path)
/// and guards on the active file before anything is spawned.
#[test]
fn a_viewer_palette_row_guards_on_the_active_file() {
let tmp = tempfile::tempdir().unwrap();
let notes = tmp.path().join("notes.md");
let data = tmp.path().join("data.csv");
std::fs::write(¬es, "# hi\n").unwrap();
std::fs::write(&data, "a,b\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.consented_extensions.insert("csvlens".into());
// The `viewer:` prefix is routed before the MCP lookup: an unknown viewer
// is reported as a viewer, not as an extension command.
app.run_extension_command("viewer:nope");
assert_eq!(app.status, "Viewer 'nope' is unavailable");
let viewer = crate::mcp::registry::ContributedViewer {
ext_id: "csvlens".into(),
id: "csvlens".into(),
label: "Open in csvlens".into(),
command: "/bin/sh".into(),
args: vec!["-c".into(), "sleep 30".into()],
extensions: vec!["csv".into(), "tsv".into()],
provision: None,
};
let before = app.terminals.len();
app.editor.path = None;
app.open_active_file_in_viewer(&viewer);
assert_eq!(app.status, "Open in csvlens: open a file first");
app.editor.open(¬es).unwrap();
app.open_active_file_in_viewer(&viewer);
assert_eq!(
app.status,
"Open in csvlens: the active file is not one of .csv / .tsv"
);
assert_eq!(app.terminals.len(), before, "a guard spawns nothing");
app.editor.open(&data).unwrap();
app.open_active_file_in_viewer(&viewer);
assert_eq!(
app.terminals.len(),
before + 1,
"a matching file opens in a pane"
);
}
/// #465: the Explorer menu offers the viewer for a single file it handles,
/// after Rename and before the compare entries, and for nothing else.
#[test]
fn the_explorer_menu_offers_a_viewer_for_a_single_matching_file_only() {
let tmp = tempfile::tempdir().unwrap();
let csv = tmp.path().join("data.csv");
let md = tmp.path().join("notes.md");
std::fs::write(&csv, "a,b\n").unwrap();
std::fs::write(&md, "# hi\n").unwrap();
let viewer_for = |file: &Path| {
(file.extension().and_then(|e| e.to_str()) == Some("csv"))
.then(|| (String::from("Open in csvlens"), String::from("csvlens")))
};
let target = tmp.path().to_path_buf();
let n = file_node(&csv);
let items = build_tree_context_menu_items_with(
Some(&n),
tmp.path(),
std::slice::from_ref(&csv),
&target,
None,
None,
viewer_for,
);
let labels: Vec<&str> = items.iter().map(|(s, _)| s.as_str()).collect();
let at = labels
.iter()
.position(|l| *l == "Open in csvlens")
.expect("a csv gets the viewer entry");
assert_eq!(labels[at - 1], "Rename", "it follows Rename");
assert!(
matches!(&items[at].1, MenuAction::OpenInViewer(id, p) if id == "csvlens" && p == &csv)
);
let n = file_node(&md);
let items = build_tree_context_menu_items_with(
Some(&n),
tmp.path(),
std::slice::from_ref(&md),
&target,
None,
None,
viewer_for,
);
assert!(
!items.iter().any(|(l, _)| l == "Open in csvlens"),
"a kind no viewer handles gets no entry"
);
// A multi-selection is not one file, so no viewer entry either.
let n = file_node(&csv);
let both = vec![csv.clone(), md.clone()];
let items = build_tree_context_menu_items_with(
Some(&n),
tmp.path(),
&both,
&target,
None,
None,
viewer_for,
);
assert!(
!items.iter().any(|(l, _)| l == "Open in csvlens"),
"a multi-selection gets no viewer entry"
);
}
#[test]
fn quick_open_with_a_line_range_lands_on_the_line_and_selects_the_range() {
// #472: `alpha:236-239` in Cmd+P must still find alpha.rs, and Enter
// must land on line 236 with 236-239 selected so the range reads as
// highlighted. `alpha:12` lands on the line with nothing selected.
let tmp = tempfile::tempdir().unwrap();
let body: String = (1..=300).map(|i| format!("line {i}\n")).collect();
std::fs::write(tmp.path().join("alpha.rs"), &body).unwrap();
std::fs::write(tmp.path().join("beta.rs"), "fn b() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let type_and_enter = |app: &mut App, text: &str| {
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
for c in text.chars() {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
};
type_and_enter(&mut app, "alpha:236-239");
assert!(app.file_finder.is_none(), "Enter closes the modal");
assert_eq!(
app.editor
.path
.as_deref()
.and_then(|p| p.file_name())
.and_then(|n| n.to_str()),
Some("alpha.rs"),
"the file part of the query is what gets opened"
);
let sel = app
.editor
.selection
.expect("the range is selected so it reads as highlighted");
let ((r0, c0), (r1, _)) = sel.normalised();
assert_eq!(
(r0, c0),
(235, 0),
"the selection starts at the top of line 236"
);
assert_eq!(r1, 238, "and reaches line 239");
// The cursor sits at the selection's HEAD, as every other
// selection-installing path leaves it, and the head is the landing line
// (the anchor is the far end), so the line the user asked for is the one
// on screen and Shift+motion extends from it.
assert_eq!(
(app.editor.cursor_row, app.editor.cursor_col),
sel.head,
"the cursor is at the head of the range"
);
assert_eq!(
app.editor.cursor_row, 235,
"and the head is the landing line"
);
assert!(
app.status.ends_with("alpha.rs:236-239"),
"the status names the range: {:?}",
app.status
);
app.handle_key(key(KeyCode::Up, KeyModifiers::SHIFT))
.unwrap();
let ((r0, _), (r1, _)) = app.editor.selection.expect("still selected").normalised();
assert_eq!(
(r0, r1),
(234, 238),
"Shift+Up extends the range from the landing line"
);
let page = app.editor.page_size().max(1);
assert!(
app.editor.scroll <= 235 && 235 < app.editor.scroll + page,
"the landing line is on screen: scroll={} page={page}",
app.editor.scroll
);
// A pick with no hint replaces the range a hinted pick left: quick open
// never installed a selection before hints existed, so a bare `alpha`
// must not re-show one the user did not just ask for.
// Extended by hand, the range is the user's now and a re-pick keeps it;
// a freshly installed one is cleared by the next pick.
let extended = app.editor.selection;
type_and_enter(&mut app, "alpha");
assert_eq!(
app.editor.selection, extended,
"a range the user extended survives an unhinted re-pick"
);
type_and_enter(&mut app, "alpha:236-239");
type_and_enter(&mut app, "alpha");
assert!(
app.editor.selection.is_none(),
"an unhinted pick clears the range a hinted pick left"
);
// A saturated line number goes through the open path like any other
// out-of-range line: it lands on the last line and the status reports
// the line landed on, never the sentinel.
type_and_enter(&mut app, "alpha:99999999999999999999");
assert_eq!(
app.editor.cursor_row, 299,
"a saturated line lands on the last line"
);
assert!(
app.status.ends_with("alpha.rs:300"),
"the status names the landed line, not the typed one: {:?}",
app.status
);
// Both ends of a range are clamped the same way.
type_and_enter(&mut app, "alpha:280-99999999999999999999");
assert!(
app.status.ends_with("alpha.rs:280-300"),
"both ends of the range are clamped to the file: {:?}",
app.status
);
// A selection the user made by hand is theirs: an unhinted pick of the
// file already in front of them does not take it away. Only a range a
// hinted pick installed is cleared by the next pick.
let mine = crate::widgets::editor::EditorSelection {
anchor: (10, 0),
head: (11, 3),
};
app.editor.selection = Some(mine);
type_and_enter(&mut app, "alpha");
assert_eq!(
app.editor.selection,
Some(mine),
"an unhinted re-pick keeps a selection the user made"
);
// Stale secondary carets do not survive a pick: the next keystroke
// would otherwise edit at every one of them.
app.editor.cursor_row = 5;
app.editor.add_cursor_below();
assert!(
app.editor.has_multi_cursor(),
"fixture: a second caret exists"
);
type_and_enter(&mut app, "alpha:236-239");
assert!(
!app.editor.has_multi_cursor(),
"a pick collapses the carets along with the selection"
);
// A zero column (0-based tool output) keeps the line and drops the
// column, as the terminal's path:line:col parser does.
type_and_enter(&mut app, "alpha:236:0");
assert_eq!(
(app.editor.cursor_row, app.editor.cursor_col),
(235, 0),
"`:236:0` lands on line 236 at the start"
);
type_and_enter(&mut app, "alpha:12");
assert_eq!(
app.editor.cursor_row, 11,
"a single line lands on that line"
);
assert!(
app.editor.selection.is_none(),
"a single line is a place to land, not a range to select"
);
assert!(
app.status.ends_with("alpha.rs:12"),
"the status names the line: {:?}",
app.status
);
type_and_enter(&mut app, "alpha:5000");
assert_eq!(
app.editor.cursor_row, 299,
"a line past the end lands on the last line"
);
// A range taller than the viewport still shows the landing line after a
// paint: the paint-time clamp follows the cursor, so the cursor must be
// on that line. Painted first so the page size is the real one.
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
type_and_enter(&mut app, "alpha:100-200");
term.draw(|f| app.render(f)).unwrap();
let page = app.editor.page_size().max(1);
assert!(
app.editor.scroll <= 99 && 99 < app.editor.scroll + page,
"line 100 is on screen after the paint: scroll={} page={page}",
app.editor.scroll
);
let ((r0, _), (r1, _)) = app
.editor
.selection
.expect("the tall range is selected")
.normalised();
assert_eq!((r0, r1), (99, 199));
type_and_enter(&mut app, "alpha:236:7");
assert_eq!(
(app.editor.cursor_row, app.editor.cursor_col),
(235, 6),
"`:line:col` lands on the column too"
);
// The click path goes through the same open, so a clicked row honours
// the hint as Enter does.
use crossterm::event::{MouseButton, MouseEventKind};
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
for c in "alpha:40".chars() {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let finder = app.file_finder.as_ref().unwrap();
assert_eq!(
finder.results.len(),
1,
"the file part alone matches alpha.rs"
);
// The list body starts three rows below the popup top (border, prompt,
// separator); row 0 is the only result.
let (col, row) = (finder.last_rect.x + 4, finder.last_rect.y + 3);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
assert!(app.file_finder.is_none(), "the click confirms the pick");
assert_eq!(
app.editor.cursor_row, 39,
"a clicked row lands on the hinted line"
);
}
#[test]
fn down_arrow_moves_selection_in_the_file_finder() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a1.rs"), "").unwrap();
std::fs::write(tmp.path().join("a2.rs"), "").unwrap();
std::fs::write(tmp.path().join("a3.rs"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
let before = app.file_finder.as_ref().unwrap().selected_index();
app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
.unwrap();
let after = app.file_finder.as_ref().unwrap().selected_index();
assert_eq!(
after,
before + 1,
"Down arrow must move the selection cursor one row"
);
}
#[test]
fn backspace_removes_a_character_from_the_finder_query() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('b'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.file_finder.as_ref().unwrap().query, "a");
}
#[test]
fn opening_the_file_finder_arms_one_image_clear_so_iterm_evicts_cached_osc_1337_cells() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
assert!(
app.consume_file_finder_image_clear(),
"Cmd+P must arm terminal.clear() so iTerm2's image cache (activity bar icons, welcome wordmark, editor preview) is wiped before the modal paints, otherwise those cached image cells bleed through the file list"
);
assert!(
!app.consume_file_finder_image_clear(),
"the flag is one-shot — a second consume call must return false so the driver does not re-clear every frame"
);
}
#[test]
fn cmd_shift_e_jumps_to_explorer_from_any_pane() {
let mut app = editor_app_with_lines(&["x"]);
app.set_sidebar_view(SidebarView::Search);
app.show_tree = false;
app.handle_key(key(
KeyCode::Char('e'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(app.sidebar_view, SidebarView::Explorer);
assert!(
app.show_tree,
"Cmd+Shift+E must un-collapse the sidebar if it was hidden"
);
}
#[test]
fn cmd_b_and_ctrl_b_toggle_the_primary_side_bar() {
// VS Code's "Toggle Primary Side Bar" is Cmd+B on macOS (Ctrl+B on
// Linux); croft accepts both so the chord behaves identically whether
// iTerm2 forwards Cmd+B as a Super CSI-u sequence or a raw Ctrl+B byte
// arrives over SSH. The sidebar starts visible.
let mut app = editor_app_with_lines(&["x"]);
assert!(app.show_tree, "sidebar starts visible");
app.handle_key(key(KeyCode::Char('b'), KeyModifiers::SUPER))
.unwrap();
assert!(!app.show_tree, "Cmd+B hides the side bar");
app.handle_key(key(KeyCode::Char('b'), KeyModifiers::SUPER))
.unwrap();
assert!(app.show_tree, "Cmd+B again shows it");
app.handle_key(key(KeyCode::Char('b'), KeyModifiers::CONTROL))
.unwrap();
assert!(!app.show_tree, "Ctrl+B toggles the same state");
}
#[test]
fn cmd_shift_s_jumps_to_source_control_even_when_editor_is_focused() {
let mut app = editor_app_with_lines(&["x"]);
app.focus_pane(Pane::Editor);
app.handle_key(key(
KeyCode::Char('s'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(
app.sidebar_view,
SidebarView::SourceControl,
"Cmd+Shift+S must jump to Source Control even from the editor (no Save-As to collide with); Search stays on Cmd+Shift+F"
);
assert!(
matches!(app.focus, Pane::Tree),
"Cmd+Shift+S must move keyboard focus into the Source Control panel"
);
}
#[test]
fn cmd_shift_d_jumps_to_run_and_debug_from_any_pane() {
let mut app = editor_app_with_lines(&["x"]);
app.focus_pane(Pane::Editor);
app.handle_key(key(
KeyCode::Char('d'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(app.sidebar_view, SidebarView::RunDebug);
}
#[test]
fn cmd_shift_r_jumps_to_remote_from_any_pane() {
let mut app = editor_app_with_lines(&["x"]);
app.focus_pane(Pane::Editor);
app.handle_key(key(
KeyCode::Char('r'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(app.sidebar_view, SidebarView::Remote);
}
#[test]
fn is_drop_to_local_key_matches_only_cmd_shift_l() {
assert!(is_drop_to_local_key(key(
KeyCode::Char('l'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
assert!(is_drop_to_local_key(key(
KeyCode::Char('L'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT
)));
assert!(!is_drop_to_local_key(key(
KeyCode::Char('l'),
KeyModifiers::SUPER
)));
assert!(!is_drop_to_local_key(key(
KeyCode::Char('q'),
KeyModifiers::CONTROL
)));
assert!(!is_drop_to_local_key(key(
KeyCode::Char('r'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
}
#[test]
fn cmd_shift_l_on_remote_requests_drop_to_local() {
let mut app = editor_app_with_lines(&["x"]);
app.is_remote = true;
app.handle_key(key(
KeyCode::Char('l'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert!(
app.drop_to_local && app.quit,
"Cmd+Shift+L on a remote-launched croft must request a clean hand-back to the local croft"
);
}
#[test]
fn cmd_shift_l_on_local_is_inert() {
let mut app = editor_app_with_lines(&["x"]);
app.is_remote = false;
app.handle_key(key(
KeyCode::Char('l'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert!(
!app.drop_to_local && !app.quit,
"Cmd+Shift+L on a local croft must do nothing - there is no remote session to leave"
);
}
#[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 cmd_shift_t_unhides_the_terminal_if_it_was_collapsed() {
let mut app = editor_app_with_lines(&["x"]);
app.focus_pane(Pane::Editor);
app.show_terminal = false;
app.handle_key(key(
KeyCode::Char('T'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert!(
app.show_terminal,
"Cmd+Shift+T must un-hide the terminal if it was collapsed (Ctrl+J) — otherwise the focus jump lands in a zero-row pane"
);
assert!(matches!(app.focus, Pane::Terminal));
}
#[test]
fn cmd_t_globally_splits_the_terminal_and_does_not_double_fire_as_focus() {
let mut app = editor_app_with_lines(&["x"]);
app.focus_pane(Pane::Editor);
let before = app.terminals.len();
app.handle_key(key(KeyCode::Char('t'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(
app.terminals.len(),
before + 1,
"Cmd+T must split the terminal from any pane; Cmd+Shift+T (focus) must not steal the bare Cmd+T chord"
);
assert!(
!is_terminal_split_key(key(
KeyCode::Char('t'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)),
"Cmd+Shift+T is focus, not split"
);
assert!(
!is_terminal_split_key(key(
KeyCode::Char('t'),
KeyModifiers::SUPER | KeyModifiers::ALT
)),
"Cmd+Opt+T is iTerm2's relocated New Tab, not split"
);
}
#[test]
fn ctrl_shift_t_still_splits_the_terminal_and_does_not_double_fire_as_focus() {
let mut app = editor_app_with_lines(&["x"]);
app.focus_pane(Pane::Editor);
let before = app.terminals.len();
app.handle_key(key(
KeyCode::Char('t'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(
app.terminals.len(),
before + 1,
"Ctrl+Shift+T must remain bound to split_terminal — the new Cmd+Shift+T focus chord must not steal it"
);
}
#[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 iterm2_image_drag_artefact_does_not_paste_its_path_into_the_editor() {
// Root cause of the user's "Pasted 67 chars" surprise: when iTerm2
// hijacks a click-drag on an OSC-1337 activity-bar icon, it writes
// the decoded PNG to $TMPDIR/iTerm2.<rand>.png and re-injects the
// path as a bracketed paste. parse_dropped_paths filters those
// paths out of the IMPORT list, but without an early-return in
// handle_paste the fallthrough would still insert the raw path
// text into the focused editor.
let mut app = editor_app_with_lines(&[""]);
app.focus_pane(Pane::Editor);
let tmp = tempfile::tempdir().unwrap();
let temp_dir = tmp.path().join("T").join("com.googlecode.iterm2");
std::fs::create_dir_all(&temp_dir).unwrap();
let fake = temp_dir.join("iTerm2.5AO7K5.png");
std::fs::write(&fake, b"\x89PNG\r\n\x1a\n").unwrap();
let payload = format!("{}\n", fake.display());
app.handle_paste(&payload);
assert_eq!(
app.editor.lines,
vec![""],
"iTerm2 inline-image drag artefact must be silently dropped at every level — the path string must NOT be pasted as text into the editor body (the user reported a CLAUDE.local.md tab opening with 'Pasted 67 chars' after trying to resize the sidebar near the Explorer icon)"
);
}
#[test]
fn cmd_f_in_editor_opens_the_inline_find_overlay_not_the_new_file_prompt() {
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(),
"Cmd+F with the editor focused must open the VS Code-style inline Find bar over the editor pane, not the Explorer 'new file' prompt"
);
assert!(
app.prompt.is_none(),
"Cmd+F in editor must NOT open the new-file Prompt — that is reserved for the Explorer pane"
);
}
#[test]
fn cmd_f_in_explorer_still_opens_the_new_file_prompt() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Tree);
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
assert!(
app.prompt.is_some(),
"Cmd+F in the Explorer pane must keep creating a new file — the existing behaviour the user asked us to preserve"
);
assert!(
app.editor_find.is_none(),
"Cmd+F in the Explorer must NOT open the editor Find overlay; the chord is overloaded by pane"
);
}
#[test]
fn cmd_shift_f_global_search_closes_the_local_editor_find_bar() {
// With the in-file Find bar (Cmd+F) open, jumping to global Search
// (Cmd+Shift+F) must dismiss the local bar. render_editor_find paints
// whenever editor_find is Some regardless of focus, so a lingering bar
// shadows the global search input on the left pane.
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"
);
app.handle_key(key(
KeyCode::Char('f'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(
app.sidebar_view,
SidebarView::Search,
"Cmd+Shift+F must switch the sidebar to global Search"
);
assert!(
app.editor_find.is_none(),
"Cmd+Shift+F must close the local editor Find bar so it cannot shadow the global search input"
);
}
#[test]
fn typing_in_editor_find_jumps_the_cursor_to_the_next_match() {
let mut app = editor_app_with_lines(&["alpha beta", "alpha gamma"]);
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('b'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('e'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('t'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
.unwrap();
assert_eq!(
(app.editor.cursor_row, app.editor.cursor_col),
(0, 6),
"typing 'beta' must jump the cursor to the first 'beta' occurrence — got ({}, {})",
app.editor.cursor_row,
app.editor.cursor_col
);
}
#[test]
fn enter_in_editor_find_jumps_to_the_next_match_and_shift_enter_walks_back() {
let mut app = editor_app_with_lines(&["alpha", "beta alpha", "alpha"]);
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('l'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('h'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.cursor_row, 1,
"Enter must jump to the next 'alpha' match on row 1"
);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.cursor_row, 2,
"Enter again must walk forward to the row 2 match"
);
app.handle_key(key(KeyCode::Enter, KeyModifiers::SHIFT))
.unwrap();
assert_eq!(
app.editor.cursor_row, 1,
"Shift+Enter must walk back one match to row 1"
);
}
#[test]
fn jumping_to_a_match_records_an_active_search_match_so_the_renderer_can_paint_it_orange() {
let mut app = editor_app_with_lines(&["alpha beta alpha"]);
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('l'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('h'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
.unwrap();
let first = app.editor.active_search_match;
assert_eq!(
first,
Some((0, 0, 5)),
"typing 'alpha' lands the cursor on the first match (col 0, len 5); active_search_match must record exactly that so the renderer can paint just those 5 cells orange while the other 'alpha' at col 11 keeps the regular yellow — got {first:?}"
);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
let second = app.editor.active_search_match;
assert_eq!(
second,
Some((0, 11, 5)),
"Enter walks to the next match at col 11; the active marker must follow so the previously-orange match resets to yellow and the new cursor row gets the orange band"
);
}
#[test]
fn esc_closes_the_editor_find_overlay_and_clears_the_highlight() {
let mut app = editor_app_with_lines(&["alpha"]);
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
.unwrap();
assert!(app.editor.search_highlight.is_some());
assert!(
app.editor.active_search_match.is_some(),
"typing should land the cursor on a match and arm the active-match marker"
);
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(app.editor_find.is_none(), "Esc must close the find bar");
assert!(
app.editor.search_highlight.is_none(),
"Esc must clear the editor's match highlight so leftover dim cells don't survive into normal typing"
);
assert!(
app.editor.active_search_match.is_none(),
"Esc must also clear the active-match marker so the orange band does not survive the overlay closing"
);
}
#[test]
fn editor_find_pre_fills_the_query_from_word_under_cursor_on_open() {
let mut app = editor_app_with_lines(&["alphabet"]);
app.editor.cursor_row = 0;
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(
app.editor_find.as_ref().unwrap().query,
"alpha",
"opening Cmd+F with the cursor mid-word must pre-fill the query with the identifier chars to the left of the cursor, matching VS Code"
);
}
#[test]
fn editor_find_paste_appends_clipboard_to_the_query() {
let mut app = editor_app_with_lines(&["alpha needle beta"]);
app.clipboard_reader = || Some(String::from("needle"));
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('v'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(
app.editor_find.as_ref().unwrap().query,
"needle",
"Cmd+V inside the find bar must paste from the system clipboard"
);
}
#[test]
fn picking_a_nested_file_via_cmd_p_expands_every_parent_dir_in_the_explorer_and_selects_the_row() {
let tmp = tempfile::tempdir().unwrap();
let nested_dir = tmp.path().join("packages").join("inner").join("citations");
std::fs::create_dir_all(&nested_dir).unwrap();
let target = nested_dir.join("storage.py");
std::fs::write(&target, "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.tree.last_inner.height = 20;
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('t'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('o'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
let selected = app
.tree
.selected_path()
.map(|p| p.to_path_buf())
.expect("a row must be selected after Enter on the finder");
assert_eq!(
selected, target,
"the explorer cursor must land on the picked file, not stay on whichever row was selected before — got {selected:?}"
);
let visible_paths: Vec<String> = app
.tree
.nodes
.iter()
.map(|n| n.path.display().to_string())
.collect();
for expected_parent in [
tmp.path().join("packages"),
tmp.path().join("packages").join("inner"),
tmp.path().join("packages").join("inner").join("citations"),
] {
let s = expected_parent.display().to_string();
assert!(
visible_paths.contains(&s),
"parent dir {s} must appear in the flattened node list — i.e. every ancestor of the picked file must be expanded so the row is reachable: got {visible_paths:?}"
);
}
}
#[test]
fn bracketed_paste_into_open_file_finder_appends_to_the_query_not_the_editor() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.lines = vec![String::from("hello")];
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
app.handle_paste("alpha");
assert_eq!(
app.file_finder.as_ref().unwrap().query,
"alpha",
"an iTerm2 bracketed paste while the finder is open must land in the finder query so the user can Cmd+P then Cmd+V a filename"
);
assert_eq!(
app.editor.lines,
vec!["hello"],
"the editor pane behind the modal must not receive the pasted text"
);
}
#[test]
fn cmd_v_keystroke_in_file_finder_reads_clipboard_into_the_query() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.clipboard_reader = || Some(String::from("alpha"));
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('v'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(
app.file_finder.as_ref().unwrap().query,
"alpha",
"Cmd+V inside the finder must read the system clipboard and append every char to the query — this covers terminals that disable bracketed paste or route Cmd+V via CSI-u"
);
}
#[test]
fn file_finder_paste_strips_control_chars_so_a_pasted_newline_does_not_submit_garbage() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
app.handle_paste("al\nph\ta");
assert_eq!(
app.file_finder.as_ref().unwrap().query,
"alpha",
"control chars in pasted text must be filtered out — a stray newline must not end the line and a tab must not navigate"
);
}
#[test]
fn file_finder_modal_swallows_typed_characters_so_editor_does_not_receive_them() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.lines = vec![String::from("hello")];
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.lines,
vec!["hello"],
"while the file finder is open, typed letters must not leak into the editor buffer"
);
assert_eq!(
app.file_finder.as_ref().unwrap().query,
"x",
"typed letters must go into the finder query instead"
);
}
#[test]
fn editor_cmd_a_still_selects_all() {
let mut app = editor_app_with_lines(&["hello", "world"]);
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(app.editor.selection_text(), "hello\nworld");
}
#[test]
fn editor_alt_left_jumps_one_word_backward() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.lines = vec![String::from("hello world rest")];
app.editor.cursor_row = 0;
app.editor.cursor_col = 16;
app.handle_key(key(KeyCode::Left, KeyModifiers::ALT))
.unwrap();
assert_eq!(app.editor.cursor_col, 12);
app.handle_key(key(KeyCode::Left, KeyModifiers::ALT))
.unwrap();
assert_eq!(app.editor.cursor_col, 6);
}
#[test]
fn editor_shift_alt_right_runs_expand_selection_not_word_extension() {
// #254 reassigned Shift+Alt+Right from word-wise extension to VS
// Code's Expand Selection (the same collision VS Code resolves the
// same way). With no path/language, the textual fallback grows to
// the line span immediately — no LSP round trip.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.lines = vec![String::from("hello world")];
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
app.handle_key(key(KeyCode::Right, KeyModifiers::ALT | KeyModifiers::SHIFT))
.unwrap();
assert_eq!(
app.editor.selection_text(),
"hello world",
"Shift+Option+Right expands to the enclosing range (the line here)"
);
// Shift+Alt+Left retraces to the gesture's start.
app.handle_key(key(KeyCode::Left, KeyModifiers::ALT | KeyModifiers::SHIFT))
.unwrap();
assert!(
app.editor.selection.is_none(),
"shrink retraced to the caret"
);
}
#[test]
fn search_visible_does_not_steal_cmd_x_from_focused_editor() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Search);
app.focus_pane(Pane::Editor);
app.search.query = String::from("needle");
app.editor.lines = vec![String::from("alpha")];
app.editor.cursor_row = 0;
app.editor.cursor_col = 5;
app.editor.select_all();
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(app.editor.lines, [String::new()]);
assert_eq!(app.search.query, "needle");
}
#[test]
fn search_visible_does_not_steal_bracketed_paste_from_focused_editor() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Search);
app.focus_pane(Pane::Editor);
app.search.query = String::from("needle");
app.editor.lines = vec![String::from("alpha")];
app.editor.cursor_row = 0;
app.editor.cursor_col = 5;
app.handle_paste(" beta");
assert_eq!(app.editor.lines, [String::from("alpha beta")]);
assert_eq!(app.search.query, "needle");
}
#[test]
fn cmd_v_pastes_clipboard_into_focused_editor_even_when_search_sidebar_visible() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.clipboard_reader = || Some(String::from(" beta"));
app.set_sidebar_view(SidebarView::Search);
app.focus_pane(Pane::Editor);
app.search.query = String::from("needle");
app.editor.lines = vec![String::from("alpha")];
app.editor.cursor_row = 0;
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('v'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(app.editor.lines, [String::from("alpha beta")]);
assert_eq!(app.search.query, "needle");
}
#[test]
fn cmd_a_in_search_selects_entire_query() {
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("alpha");
app.handle_search_key(key(KeyCode::Char('a'), KeyModifiers::SUPER));
assert_eq!(
app.search.selection_range(),
Some((0, "alpha".len())),
"Cmd+A in search input must select the whole query"
);
}
#[test]
fn cmd_c_in_search_with_full_selection_clears_no_text() {
// After Cmd+A then Cmd+C, the query stays put (copy is non-destructive).
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("alpha");
app.handle_search_key(key(KeyCode::Char('a'), KeyModifiers::SUPER));
app.handle_search_key(key(KeyCode::Char('c'), KeyModifiers::SUPER));
assert_eq!(app.search.query, "alpha");
}
#[test]
fn cmd_x_in_search_with_full_selection_clears_query() {
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("alpha");
app.handle_search_key(key(KeyCode::Char('a'), KeyModifiers::SUPER));
app.handle_search_key(key(KeyCode::Char('x'), KeyModifiers::SUPER));
assert_eq!(app.search.query, "");
assert_eq!(app.search.selection_range(), None);
}
#[test]
fn paste_clipboard_into_search_with_injected_text_appends_to_query() {
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("foo");
app.paste_clipboard_into_search(Some("BAR"));
assert_eq!(app.search.query, "fooBAR");
}
#[test]
fn paste_clipboard_into_search_with_no_text_is_noop() {
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("foo");
app.paste_clipboard_into_search(None);
assert_eq!(app.search.query, "foo");
}
#[test]
fn paste_clipboard_into_search_with_no_text_sets_diagnostic_status() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Search);
app.paste_clipboard_into_search(None);
assert!(
app.status.to_lowercase().contains("clipboard"),
"expected diagnostic status mentioning the clipboard, got: {:?}",
app.status
);
}
#[test]
fn paste_clipboard_into_search_with_empty_text_sets_diagnostic_status() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Search);
app.paste_clipboard_into_search(Some(""));
assert!(
app.status.to_lowercase().contains("clipboard"),
"expected diagnostic status mentioning the clipboard, got: {:?}",
app.status
);
}
#[test]
fn unmatched_cmd_key_in_search_logs_diagnostic_status() {
// If iTerm or the kitty CSI u path delivers a Cmd+<letter> the search
// handler doesn't recognise, leave a breadcrumb so the user can tell
// us exactly what crossterm saw — this is how we'll diagnose Cmd+V
// delivery problems without an interactive debugger.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Search);
app.handle_search_key(key(KeyCode::Char('q'), KeyModifiers::SUPER));
assert!(
app.status.contains("Cmd+"),
"expected unhandled-cmd diagnostic, got: {:?}",
app.status
);
}
#[test]
fn cmd_v_is_recognised_as_search_paste_key() {
assert!(is_search_paste_key(key(
KeyCode::Char('v'),
KeyModifiers::SUPER
)));
assert!(is_search_paste_key(key(
KeyCode::Char('v'),
KeyModifiers::CONTROL
)));
assert!(is_search_paste_key(key(
KeyCode::Char('\u{16}'),
KeyModifiers::NONE
)));
assert!(!is_search_paste_key(key(
KeyCode::Char('v'),
KeyModifiers::NONE
)));
assert!(!is_search_paste_key(key(
KeyCode::Char('a'),
KeyModifiers::SUPER
)));
}
#[test]
fn cmd_v_is_recognised_as_editor_paste_key() {
assert!(is_editor_paste_key(key(
KeyCode::Char('v'),
KeyModifiers::SUPER
)));
assert!(is_editor_paste_key(key(
KeyCode::Char('v'),
KeyModifiers::CONTROL
)));
assert!(is_editor_paste_key(key(
KeyCode::Char('\u{16}'),
KeyModifiers::NONE
)));
assert!(!is_editor_paste_key(key(
KeyCode::Char('v'),
KeyModifiers::NONE
)));
assert!(!is_editor_paste_key(key(
KeyCode::Char('a'),
KeyModifiers::SUPER
)));
}
#[test]
fn left_click_on_paste_button_triggers_clipboard_paste_into_search() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Search);
app.tree.last_area = Rect {
x: 0,
y: 0,
width: 60,
height: 12,
};
app.search.last_area = Rect {
x: 0,
y: 0,
width: 60,
height: 12,
};
app.search.last_inner = Rect {
x: 1,
y: 1,
width: 58,
height: 10,
};
app.search.paste_button_x = 40;
app.search.paste_button_y = 1;
app.search.paste_button_w = 5;
let original_status = app.status.clone();
let m = crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 42,
row: 1,
modifiers: KeyModifiers::NONE,
};
app.handle_mouse(m);
assert_ne!(
app.status, original_status,
"click on Paste button must invoke the clipboard paste path (status updates whether clipboard read succeeds, fails, or returns empty)"
);
}
#[test]
fn double_clicking_a_search_hit_pins_the_tab_so_the_next_hit_opens_beside_it() {
// Search results must mirror the Explorer's preview/pin gesture: a
// single click opens the hit in the replaceable preview slot, a
// double-click pins it so navigating to the next result opens a NEW
// preview tab beside it instead of replacing the file under review.
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.txt"), "needle a\n").unwrap();
std::fs::write(tmp.path().join("b.txt"), "needle b\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Search);
app.search.query = String::from("needle");
app.search.run_query();
assert_eq!(app.search.hits.len(), 2, "precondition: one hit per file");
app.search.last_area = Rect {
x: 0,
y: 0,
width: 60,
height: 20,
};
app.search.last_inner = Rect {
x: 1,
y: 1,
width: 58,
height: 18,
};
// Result rows start 5 rows below the inner top (header + blank + single-row
// query field + separator + caption), matching SearchPanel::hit_at_y.
let first_hit_row = app.search.last_inner.y + 5;
let click = |row: u16| crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 5,
row,
modifiers: KeyModifiers::NONE,
};
let first_path = app.search.hits[0].path.clone();
let second_path = app.search.hits[1].path.clone();
app.handle_mouse(click(first_hit_row));
assert!(
app.editor.editors[app.editor.active_index()].preview,
"a single click on a search hit opens it as a preview tab"
);
app.handle_mouse(click(first_hit_row));
assert!(
!app.editor.editors[app.editor.active_index()].preview,
"a second click on the same hit within the double-click window must pin the tab, exactly like double-clicking a file in the Explorer"
);
app.handle_mouse(click(first_hit_row + 1));
let paths: Vec<_> = app
.editor
.editors
.iter()
.filter_map(|e| e.path.clone())
.collect();
assert!(
paths.contains(&first_path) && paths.contains(&second_path),
"after pinning the first hit, opening the second must keep both files open (got {paths:?}); the pinned tab must not be replaced by the next preview"
);
assert!(
app.editor.editors[app.editor.active_index()].preview,
"the second hit lands in a fresh preview tab beside the pinned one"
);
}
#[test]
fn cmd_p_index_is_built_in_the_background_so_open_does_not_walk_synchronously() {
// Regression for the user's "Cmd+P is so slow" report. The old
// open_file_finder ran build_file_index synchronously on the
// UI thread on first invocation; for a sizeable workspace
// that stalled the TUI for the entire walk. The fix kicks
// off the walk in App::new and delivers the index via
// channel - by the time the user reaches for Cmd+P, the
// index is already cached.
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), b"").unwrap();
std::fs::create_dir(tmp.path().join(".croft")).unwrap();
std::fs::write(tmp.path().join(".croft").join("lsp.log"), b"").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Poll for the background-built index to land. With this tiny
// workspace it should arrive within a couple of hundred ms.
let mut waited_ms = 0u32;
loop {
app.poll_file_finder_index();
if app.file_finder_index.is_some() {
break;
}
if waited_ms >= 5000 {
panic!(
"background walker thread must deliver the file index within 5s of App::new on a 2-file workspace"
);
}
std::thread::sleep(std::time::Duration::from_millis(20));
waited_ms += 20;
}
// Once the index has landed, open_file_finder must consume it
// without falling back to the synchronous walk - and the index
// MUST contain the .croft/lsp.log entry the user expected to
// find via Cmd+P typing 'lsp.log'.
let rels: Vec<String> = app
.file_finder_index
.as_ref()
.unwrap()
.iter()
.map(|e| e.rel.clone())
.collect();
assert!(
rels.iter().any(|r| r == ".croft/lsp.log"),
"background index must contain .croft/lsp.log; got {rels:?}"
);
}
#[test]
fn cmd_p_index_refreshes_after_a_new_file_lands_on_disk() {
// Regression: the Cmd+P index was built once at App::new and
// never refreshed, so files created later (by another process,
// by a git checkout that swapped the working tree, or by an
// in-app create) stayed invisible to Cmd+P until croft was
// restarted. drain_fs_events now triggers kick_file_finder_index_rebuild
// so creates and deletes propagate into the haystack the
// finder ranks against.
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join(".git")).unwrap();
std::fs::write(tmp.path().join("alpha.rs"), b"").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Wait for the initial background index to land.
let mut waited = 0u32;
loop {
app.poll_file_finder_index();
if app.file_finder_index.is_some() {
break;
}
if waited >= 5000 {
panic!("initial index must land within 5s");
}
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
// Drain any startup FS-watcher noise so the next loop reacts
// only to the file we are about to create.
for _ in 0..20 {
let _ = app.drain_fs_events();
std::thread::sleep(std::time::Duration::from_millis(10));
}
let new_dir = tmp
.path()
.join("packages/ant-ts-lib-noggin/src/entities/files");
std::fs::create_dir_all(&new_dir).unwrap();
std::fs::write(new_dir.join("resolver.ts"), b"export {};\n").unwrap();
let started = std::time::Instant::now();
let mut saw = false;
for _ in 0..400 {
let _ = app.drain_fs_events();
app.poll_file_finder_index();
if let Some(idx) = app.file_finder_index.as_ref()
&& idx
.iter()
.any(|e| e.rel == "packages/ant-ts-lib-noggin/src/entities/files/resolver.ts")
{
saw = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(
saw,
"Cmd+P index must include resolver.ts within a few seconds of it being written to disk; without this, branch-new files stay invisible to Cmd+P until croft restarts"
);
assert!(
started.elapsed() <= std::time::Duration::from_secs(5),
"index refresh must finish within 5s of the FS event on a 2-file workspace"
);
}
#[test]
fn cmd_p_index_drops_a_file_deleted_off_disk() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join(".git")).unwrap();
std::fs::write(tmp.path().join("alpha.rs"), b"").unwrap();
let target = tmp.path().join("doomed.rs");
std::fs::write(&target, b"").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mut waited = 0u32;
loop {
app.poll_file_finder_index();
if let Some(idx) = app.file_finder_index.as_ref()
&& idx.iter().any(|e| e.rel == "doomed.rs")
{
break;
}
if waited >= 5000 {
panic!("initial index must contain doomed.rs within 5s");
}
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
for _ in 0..20 {
let _ = app.drain_fs_events();
std::thread::sleep(std::time::Duration::from_millis(10));
}
std::fs::remove_file(&target).unwrap();
let mut gone = false;
for _ in 0..400 {
let _ = app.drain_fs_events();
app.poll_file_finder_index();
if let Some(idx) = app.file_finder_index.as_ref()
&& !idx.iter().any(|e| e.rel == "doomed.rs")
{
gone = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(
gone,
"deleted file must drop out of the Cmd+P index after the FS-event-driven rebuild lands"
);
}
#[test]
fn change_workspace_root_rebuilds_cmd_p_index_against_the_new_root() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("root_a");
let b = tmp.path().join("root_b");
std::fs::create_dir_all(&a).unwrap();
std::fs::create_dir_all(&b).unwrap();
std::fs::write(a.join("only_in_a.rs"), b"").unwrap();
std::fs::write(b.join("only_in_b.rs"), b"").unwrap();
let mut app = App::new(a.clone()).unwrap();
let mut waited = 0u32;
loop {
app.poll_file_finder_index();
if let Some(idx) = app.file_finder_index.as_ref()
&& idx.iter().any(|e| e.rel == "only_in_a.rs")
{
break;
}
if waited >= 5000 {
panic!("initial index against root_a must land within 5s");
}
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
app.change_workspace_root(b.clone());
let mut saw_b = false;
for _ in 0..400 {
app.poll_file_finder_index();
if let Some(idx) = app.file_finder_index.as_ref() {
let rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
if rels.contains(&"only_in_b.rs") && !rels.contains(&"only_in_a.rs") {
saw_b = true;
break;
}
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(
saw_b,
"after change_workspace_root(b), the Cmd+P index must reflect root_b's files (only_in_b.rs present, only_in_a.rs gone); without this, Cmd+/ leaves Cmd+P searching the previous project"
);
}
#[test]
fn open_cmd_p_finder_re_ranks_in_place_when_the_index_swaps() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join(".git")).unwrap();
std::fs::write(tmp.path().join("alpha.rs"), b"").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mut waited = 0u32;
loop {
app.poll_file_finder_index();
if app.file_finder_index.is_some() {
break;
}
if waited >= 5000 {
panic!("initial index must land within 5s");
}
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
// Open Cmd+P, type the new filename — initially zero results.
app.open_file_finder();
for c in "resolver.ts".chars() {
app.file_finder.as_mut().unwrap().push_char(c);
}
assert!(
app.file_finder
.as_ref()
.unwrap()
.visible_results()
.is_empty(),
"resolver.ts is not on disk yet; finder must show no matches before the file is created"
);
let new_dir = tmp
.path()
.join("packages/ant-ts-lib-noggin/src/entities/files");
std::fs::create_dir_all(&new_dir).unwrap();
std::fs::write(new_dir.join("resolver.ts"), b"").unwrap();
let mut surfaced = false;
for _ in 0..400 {
let _ = app.drain_fs_events();
app.poll_file_finder_index();
let finder = app.file_finder.as_ref().unwrap();
if finder
.visible_results()
.iter()
.any(|r| r.entry.rel == "packages/ant-ts-lib-noggin/src/entities/files/resolver.ts")
{
surfaced = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(
surfaced,
"an open Cmd+P finder must re-rank against the rebuilt index without the user closing and reopening it"
);
}
#[test]
fn click_on_tree_row_aligned_with_terminal_splitter_y_selects_the_row_not_the_splitter() {
// Regression for the user's "I can't click on the last two files,
// but arrow+Enter opens them" report. Root cause: the editor /
// terminal splitter handler at handle_mouse checks `m.row == y
// || m.row == y.saturating_sub(1)` WITHOUT gating by column, so
// a click on a tree row in the LEFT column whose y happens to
// line up with the editor/terminal splitter (which only lives
// in the RIGHT column) was hijacked into a splitter-drag and
// never reached the Explorer's `node_at_y` branch.
let tmp = tempfile::tempdir().unwrap();
for name in [
"alpha.txt",
"beta.txt",
"gamma.txt",
"delta.txt",
"epsilon.txt",
"zeta.txt",
] {
std::fs::write(tmp.path().join(name), b"").unwrap();
}
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Layout: activity-bar(4) + tree-pane on the left, editor +
// terminal stacked on the right. Pick a splitter row that
// intersects one of the rendered tree rows.
app.tree.last_area = Rect {
x: 4,
y: 0,
width: 32,
height: 12,
};
app.tree.last_inner = Rect {
x: 5,
y: 1,
width: 30,
height: 10,
};
app.sidebar_splitter_x = Some(36);
// Splitter sits inside the tree's rendered row band.
app.terminal_splitter_y = Some(6);
// The clicked tree row's y MUST equal terminal_splitter_y to
// trigger the bug; column stays well inside tree.last_inner.x..
let click_row = 6u16;
let click_col = app.tree.last_inner.x + 2;
let target_idx = (click_row - app.tree.last_inner.y) as usize;
assert!(
target_idx < app.tree.nodes.len(),
"test setup must put a real tree row at the splitter y"
);
let click = crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: click_col,
row: click_row,
modifiers: KeyModifiers::NONE,
};
app.handle_mouse(click);
assert!(
app.splitter_drag.is_none(),
"click in the LEFT (tree) column must never arm a splitter drag, even when the row y lines up with the editor/terminal splitter that lives in the RIGHT column"
);
assert_eq!(
app.tree.selected, target_idx,
"the tree row under the click must become selected; the user reported the bottom rows of the tree being unclickable even though they were plainly visible"
);
}
#[test]
fn double_clicking_directory_toggles_only_once() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join("sub")).unwrap();
std::fs::write(tmp.path().join("sub").join("child.txt"), "hi").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.tree.last_area = Rect {
x: 0,
y: 0,
width: 40,
height: 8,
};
app.tree.last_inner = Rect {
x: 1,
y: 1,
width: 38,
height: 6,
};
let sub_idx = app
.tree
.nodes
.iter()
.position(|node| node.path.ends_with("sub"))
.unwrap();
let row = app.tree.last_inner.y + sub_idx as u16;
let click = crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 6,
row,
modifiers: KeyModifiers::NONE,
};
app.handle_mouse(click);
let sub_idx = app
.tree
.nodes
.iter()
.position(|node| node.path.ends_with("sub"))
.unwrap();
assert!(app.tree.nodes[sub_idx].expanded);
let expanded_len = app.tree.nodes.len();
app.handle_mouse(click);
let sub_idx = app
.tree
.nodes
.iter()
.position(|node| node.path.ends_with("sub"))
.unwrap();
assert!(app.tree.nodes[sub_idx].expanded);
assert_eq!(app.tree.nodes.len(), expanded_len);
}
#[test]
fn typing_after_select_all_replaces_query() {
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("alpha");
app.handle_search_key(key(KeyCode::Char('a'), KeyModifiers::SUPER));
app.handle_search_key(key(KeyCode::Char('z'), KeyModifiers::NONE));
assert_eq!(app.search.query, "z");
}
#[test]
fn shift_arrow_extends_tree_selection() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.txt"), "").unwrap();
std::fs::write(tmp.path().join("b.txt"), "").unwrap();
std::fs::write(tmp.path().join("c.txt"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.tree.select_replace(1);
app.handle_tree_key(key(KeyCode::Down, KeyModifiers::SHIFT));
app.handle_tree_key(key(KeyCode::Down, KeyModifiers::SHIFT));
assert_eq!(app.tree.action_paths().len(), 3);
}
#[test]
fn cmd_a_in_tree_marks_all_visible() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.txt"), "").unwrap();
std::fs::write(tmp.path().join("b.txt"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_tree_key(key(KeyCode::Char('a'), KeyModifiers::SUPER));
assert_eq!(app.tree.marked.len(), app.tree.nodes.len());
}
#[test]
fn esc_in_tree_clears_marks() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.txt"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.tree.toggle_mark(1);
assert!(!app.tree.marked.is_empty());
app.handle_tree_key(key(KeyCode::Esc, KeyModifiers::NONE));
assert!(app.tree.marked.is_empty());
}
#[test]
fn cmd_c_then_cmd_v_copies_explorer_paths_into_target() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("src.txt"), "hello").unwrap();
std::fs::create_dir(tmp.path().join("dest")).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let src_idx = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("src.txt"))
.unwrap();
app.tree.select_replace(src_idx);
app.handle_tree_key(key(KeyCode::Char('c'), KeyModifiers::SUPER));
let dest_idx = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("dest"))
.unwrap();
app.tree.select_replace(dest_idx);
app.handle_tree_key(key(KeyCode::Char('v'), KeyModifiers::SUPER));
let dest_file = tmp.path().join("dest/src.txt");
assert!(dest_file.exists(), "copy must place file in target dir");
assert!(
tmp.path().join("src.txt").exists(),
"copy must keep the source"
);
}
#[test]
fn cmd_x_then_cmd_v_moves_explorer_paths_into_target() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("src.txt"), "hello").unwrap();
std::fs::create_dir(tmp.path().join("dest")).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let src_idx = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("src.txt"))
.unwrap();
app.tree.select_replace(src_idx);
app.handle_tree_key(key(KeyCode::Char('x'), KeyModifiers::SUPER));
let dest_idx = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("dest"))
.unwrap();
app.tree.select_replace(dest_idx);
app.handle_tree_key(key(KeyCode::Char('v'), KeyModifiers::SUPER));
assert!(tmp.path().join("dest/src.txt").exists());
assert!(
!tmp.path().join("src.txt").exists(),
"cut must remove source"
);
assert!(
app.tree_clipboard.is_none(),
"cut clipboard must be consumed on paste"
);
}
#[test]
fn delete_key_trashes_every_marked_path() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.txt"), "").unwrap();
std::fs::write(tmp.path().join("b.txt"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let a_idx = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("a.txt"))
.unwrap();
let b_idx = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("b.txt"))
.unwrap();
app.tree.select_replace(a_idx);
app.tree.toggle_mark(b_idx);
// Delete now asks first: it opens a confirmation popup, nothing is trashed yet.
app.handle_tree_key(key(KeyCode::Delete, KeyModifiers::NONE));
assert!(
app.input_prompt.is_some(),
"Delete must open a confirm popup"
);
assert!(
tmp.path().join("a.txt").exists(),
"not trashed until confirmed"
);
// Enter confirms; now both selected entries move to Trash.
app.submit_input_prompt();
assert!(!tmp.path().join("a.txt").exists());
assert!(!tmp.path().join("b.txt").exists());
}
#[test]
fn scratch_buffer_saves_under_the_workspace_root_with_a_safe_name() {
// A scratch buffer (MCP output / Git Output) must anchor under the open
// project, not write a bare filename to croft's cwd, and must sanitise path
// separators in the title so the name is a valid single file.
let tmp = tempfile::tempdir().unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
let p = app.scratch_buffer_path("Web: a/b.md");
assert_eq!(p, tmp.path().join("Web: a-b.md"));
}
#[test]
fn drag_drop_moves_marked_paths_to_target_dir() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("src.txt"), "x").unwrap();
std::fs::create_dir(tmp.path().join("dest")).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.tree.last_area = Rect {
x: 0,
y: 0,
width: 40,
height: 8,
};
app.tree.last_inner = Rect {
x: 1,
y: 1,
width: 38,
height: 6,
};
let src_idx = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("src.txt"))
.unwrap();
let dest_idx = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("dest"))
.unwrap();
let src_row = app.tree.last_inner.y + src_idx as u16;
let dest_row = app.tree.last_inner.y + dest_idx as u16;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 6,
row: src_row,
modifiers: KeyModifiers::NONE,
});
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
column: 6,
row: dest_row,
modifiers: KeyModifiers::NONE,
});
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
column: 6,
row: dest_row,
modifiers: KeyModifiers::NONE,
});
assert!(tmp.path().join("dest/src.txt").exists());
assert!(!tmp.path().join("src.txt").exists());
}
#[test]
fn alt_drag_copies_instead_of_moves() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("src.txt"), "x").unwrap();
std::fs::create_dir(tmp.path().join("dest")).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.tree.last_area = Rect {
x: 0,
y: 0,
width: 40,
height: 8,
};
app.tree.last_inner = Rect {
x: 1,
y: 1,
width: 38,
height: 6,
};
let src_idx = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("src.txt"))
.unwrap();
let dest_idx = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("dest"))
.unwrap();
let src_row = app.tree.last_inner.y + src_idx as u16;
let dest_row = app.tree.last_inner.y + dest_idx as u16;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 6,
row: src_row,
modifiers: KeyModifiers::NONE,
});
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
column: 6,
row: dest_row,
modifiers: KeyModifiers::ALT,
});
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
column: 6,
row: dest_row,
modifiers: KeyModifiers::ALT,
});
assert!(tmp.path().join("dest/src.txt").exists());
assert!(
tmp.path().join("src.txt").exists(),
"Alt-drag must keep the source"
);
}
#[test]
fn shift_click_extends_marks_from_anchor() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.txt"), "").unwrap();
std::fs::write(tmp.path().join("b.txt"), "").unwrap();
std::fs::write(tmp.path().join("c.txt"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.tree.last_area = Rect {
x: 0,
y: 0,
width: 40,
height: 8,
};
app.tree.last_inner = Rect {
x: 1,
y: 1,
width: 38,
height: 6,
};
let first_idx = 1usize;
let last_idx = app.tree.nodes.len() - 1;
let first_row = app.tree.last_inner.y + first_idx as u16;
let last_row = app.tree.last_inner.y + last_idx as u16;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 6,
row: first_row,
modifiers: KeyModifiers::NONE,
});
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
column: 6,
row: first_row,
modifiers: KeyModifiers::NONE,
});
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 6,
row: last_row,
modifiers: KeyModifiers::SHIFT,
});
let span = last_idx - first_idx + 1;
assert_eq!(app.tree.action_paths().len(), span);
}
#[test]
fn alt_click_toggles_individual_mark_on_release() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.txt"), "").unwrap();
std::fs::write(tmp.path().join("b.txt"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.tree.last_area = Rect {
x: 0,
y: 0,
width: 40,
height: 8,
};
app.tree.last_inner = Rect {
x: 1,
y: 1,
width: 38,
height: 6,
};
let a_idx = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("a.txt"))
.unwrap();
let b_idx = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("b.txt"))
.unwrap();
let a_row = app.tree.last_inner.y + a_idx as u16;
let b_row = app.tree.last_inner.y + b_idx as u16;
for row in [a_row, b_row] {
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 6,
row,
modifiers: KeyModifiers::ALT,
});
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
column: 6,
row,
modifiers: KeyModifiers::ALT,
});
}
let marked: BTreeSet<PathBuf> = app.tree.marked.clone();
assert!(marked.contains(&tmp.path().join("a.txt")));
assert!(marked.contains(&tmp.path().join("b.txt")));
}
#[test]
fn ctrl_click_also_toggles_individual_mark() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.txt"), "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.tree.last_area = Rect {
x: 0,
y: 0,
width: 40,
height: 8,
};
app.tree.last_inner = Rect {
x: 1,
y: 1,
width: 38,
height: 6,
};
let a_idx = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("a.txt"))
.unwrap();
let row = app.tree.last_inner.y + a_idx as u16;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 6,
row,
modifiers: KeyModifiers::CONTROL,
});
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
column: 6,
row,
modifiers: KeyModifiers::CONTROL,
});
assert!(app.tree.marked.contains(&tmp.path().join("a.txt")));
}
#[test]
fn alt_click_does_not_open_the_file() {
// Toggle is meant to mark — never to open. The deferred-toggle flow
// must not reach `editor.open_preview` when Alt/Ctrl is held.
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("a.txt");
std::fs::write(&f, "hi").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.tree.last_area = Rect {
x: 0,
y: 0,
width: 40,
height: 8,
};
app.tree.last_inner = Rect {
x: 1,
y: 1,
width: 38,
height: 6,
};
let idx = app.tree.nodes.iter().position(|n| n.path == f).unwrap();
let row = app.tree.last_inner.y + idx as u16;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 6,
row,
modifiers: KeyModifiers::ALT,
});
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
column: 6,
row,
modifiers: KeyModifiers::ALT,
});
assert!(
app.editor.is_blank_initial(),
"alt-click must not open the file"
);
}
#[test]
fn parse_dropped_paths_accepts_a_single_existing_absolute_path() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("dropped.txt");
std::fs::write(&f, "hi").unwrap();
let parsed = parse_dropped_paths(&format!("{}\n", f.display()));
assert_eq!(parsed, vec![f]);
}
#[test]
fn parse_dropped_paths_drops_iterm2_inline_image_drag_artefact() {
// iTerm2 lets the user drag any OSC-1337 inline image (which is
// how croft paints activity-bar icons / welcome wordmark / SSH
// hero) out of the terminal. On mouse-up iTerm2 writes the bytes
// to $TMPDIR/iTerm2.<rand>.png and re-injects the path as a
// bracketed paste, which croft would otherwise see as "the user
// dragged a file into the editor" and open as an image preview.
// That has happened to the user accidentally when they tried to
// click a sidebar icon and the click drifted into a drag — the
// file `iTerm2.5AO7K5.png` opened as a tab showing the Explorer
// glyph. The drop must be silently filtered.
let tmp = tempfile::tempdir().unwrap();
let temp_dir = tmp.path().join("T").join("com.googlecode.iterm2");
std::fs::create_dir_all(&temp_dir).unwrap();
let fake = temp_dir.join("iTerm2.5AO7K5.png");
std::fs::write(&fake, b"\x89PNG\r\n\x1a\n").unwrap();
let parsed = parse_dropped_paths(&format!("{}\n", fake.display()));
assert!(
parsed.is_empty(),
"iTerm2's inline-image drag temp file must be filtered out so a stray click-drag on an activity-bar icon does not open a phantom PNG tab — got {parsed:?}"
);
}
#[test]
fn parse_dropped_paths_keeps_user_pngs_that_happen_to_share_a_temp_dir() {
// The filter must key on the `iTerm2.<rand>.png` filename
// pattern, not just "anything under /tmp". A real user-authored
// PNG that happens to live under a temp directory must still be
// accepted, otherwise the heuristic over-fires.
let tmp = tempfile::tempdir().unwrap();
let temp_dir = tmp.path().join("T");
std::fs::create_dir_all(&temp_dir).unwrap();
let user_png = temp_dir.join("my_screenshot.png");
std::fs::write(&user_png, b"\x89PNG\r\n\x1a\n").unwrap();
let parsed = parse_dropped_paths(&format!("{}\n", user_png.display()));
assert_eq!(
parsed,
vec![user_png.clone()],
"a user-named PNG under a temp dir must still be droppable — only the literal iTerm2.<rand>.png pattern is the artefact"
);
}
#[test]
fn parse_dropped_paths_strips_file_url_prefix_and_decodes() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("with space.txt");
std::fs::write(&f, "hi").unwrap();
let url = format!("file://{}/with%20space.txt", tmp.path().to_string_lossy());
let parsed = parse_dropped_paths(&url);
assert_eq!(parsed, vec![f]);
}
#[test]
fn parse_dropped_paths_handles_backslash_escaped_spaces() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("with space.txt");
std::fs::write(&f, "hi").unwrap();
let escaped = format!("{}/with\\ space.txt", tmp.path().to_string_lossy());
let parsed = parse_dropped_paths(&escaped);
assert_eq!(parsed, vec![f]);
}
#[test]
fn parse_dropped_paths_supports_multi_file_drop_via_newlines() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
let b = tmp.path().join("b.txt");
std::fs::write(&a, "1").unwrap();
std::fs::write(&b, "2").unwrap();
let payload = format!("{}\n{}\n", a.display(), b.display());
let parsed = parse_dropped_paths(&payload);
assert_eq!(parsed.len(), 2);
assert!(parsed.contains(&a));
assert!(parsed.contains(&b));
}
#[test]
fn parse_dropped_paths_supports_multi_file_drop_via_unescaped_spaces() {
// iTerm2's Finder-drop format for two files with spaces in their
// names is `<path1> <path2>`, where spaces inside a path are
// backslash-escaped and the separator between paths is a literal
// space. Make sure both paths come through.
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("02 Аленький цветочек.mp3");
let b = tmp.path().join("03 Буратино.mp3");
std::fs::write(&a, "x").unwrap();
std::fs::write(&b, "y").unwrap();
let payload = format!(
"{}/02\\ Аленький\\ цветочек.mp3 {}/03\\ Буратино.mp3",
tmp.path().to_string_lossy(),
tmp.path().to_string_lossy(),
);
let parsed = parse_dropped_paths(&payload);
assert_eq!(parsed.len(), 2, "expected two paths, got {parsed:?}");
assert!(parsed.contains(&a));
assert!(parsed.contains(&b));
}
#[test]
fn parse_dropped_paths_keeps_quoted_path_with_space_intact() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("with space.txt");
std::fs::write(&a, "x").unwrap();
let payload = format!("\"{}\"", a.display());
let parsed = parse_dropped_paths(&payload);
assert_eq!(parsed, vec![a]);
}
#[test]
fn parse_dropped_paths_handles_mix_of_quoted_and_escaped_paths() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("plain.txt");
let b = tmp.path().join("with space.txt");
std::fs::write(&a, "x").unwrap();
std::fs::write(&b, "y").unwrap();
let payload = format!("{} \"{}\"", a.display(), b.display(),);
let parsed = parse_dropped_paths(&payload);
assert_eq!(parsed.len(), 2, "got {parsed:?}");
assert!(parsed.contains(&a));
assert!(parsed.contains(&b));
}
#[test]
fn parse_dropped_paths_returns_empty_for_plain_text() {
// Plain typed text must not be hijacked as a drop import.
let parsed = parse_dropped_paths("hello world this is some text");
assert!(parsed.is_empty());
}
#[test]
fn parse_dropped_paths_skips_nonexistent_paths() {
let parsed = parse_dropped_paths("/this/path/definitely/does/not/exist");
assert!(parsed.is_empty());
}
#[test]
fn finder_drop_into_explorer_moves_file_into_workspace() {
let workspace = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let src = outside.path().join("dragged.txt");
std::fs::write(&src, "hello").unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Tree);
app.set_sidebar_view(SidebarView::Explorer);
app.handle_paste(&format!("{}\n", src.display()));
let dest = workspace.path().join("dragged.txt");
assert!(dest.exists(), "file should land in the workspace");
assert!(!src.exists(), "Finder drop must move, not copy");
assert_eq!(std::fs::read_to_string(&dest).unwrap(), "hello");
}
#[test]
fn finder_drop_into_terminal_pastes_path_instead_of_scp_in_remote_view() {
let workspace = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let src = outside.path().join("dragged.txt");
std::fs::write(&src, "hello").unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
app.remote.targets = vec![crate::remote::RemoteTarget {
alias: String::from("alpha"),
host_name: Some(String::from("alpha.example.com")),
user: Some(String::from("vitali")),
}];
app.remote.selected = 0;
app.set_sidebar_view(SidebarView::Remote);
// Focus sits in the embedded terminal (e.g. a Claude Code session)
// while the Remote sidebar happens to be the active view. A Finder
// drag-drop here must forward the path into the terminal so the
// running program receives it, NOT hijack it into an scp upload to
// the auto-selected host. Focus wins, mirroring the Explorer branch.
app.show_terminal = true;
app.focus_pane(Pane::Terminal);
let editor_before = app.editor.lines.clone();
app.handle_paste(&format!("{}\n", src.display()));
assert!(
app.take_pending_scp_uploads().is_empty(),
"terminal-focused drop must not queue an scp upload",
);
assert_eq!(
app.editor.lines, editor_before,
"terminal-focused drop must not leak the path into the editor",
);
assert!(src.exists(), "the drop must not move or delete the source");
}
#[test]
fn finder_drop_into_editor_inserts_path_instead_of_scp_in_remote_view() {
let workspace = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let src = outside.path().join("e.txt");
std::fs::write(&src, "x").unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
app.remote.targets = vec![crate::remote::RemoteTarget {
alias: String::from("beta"),
host_name: None,
user: None,
}];
app.remote.selected = 0;
app.set_sidebar_view(SidebarView::Remote);
app.focus_pane(Pane::Editor);
app.handle_paste(&format!("{}\n", src.display()));
assert!(
app.take_pending_scp_uploads().is_empty(),
"editor-focused drop must not queue an scp upload",
);
assert!(
app.editor.lines.iter().any(|l| l.contains("e.txt")),
"editor-focused drop should insert the dropped path, was: {:?}",
app.editor.lines,
);
}
#[test]
fn finder_drop_onto_remote_tree_still_queues_scp() {
let workspace = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let src = outside.path().join("dragged.txt");
std::fs::write(&src, "hello").unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
app.remote.targets = vec![crate::remote::RemoteTarget {
alias: String::from("alpha"),
host_name: Some(String::from("alpha.example.com")),
user: Some(String::from("vitali")),
}];
app.remote.selected = 0;
app.set_sidebar_view(SidebarView::Remote);
// Dropping ONTO the Remote sidebar (tree focused) is the deliberate
// upload gesture and must still queue an scp copy to the host.
app.focus_pane(Pane::Tree);
app.handle_paste(&format!("{}\n", src.display()));
let queued = app.take_pending_scp_uploads();
assert_eq!(queued.len(), 1, "one scp upload should be queued");
assert_eq!(queued[0].alias, "alpha");
assert_eq!(queued[0].src, src);
assert!(src.exists(), "scp must copy, not move");
}
#[test]
fn finder_drop_on_remote_view_with_no_target_reports_clear_status() {
let workspace = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let src = outside.path().join("dragged.txt");
std::fs::write(&src, "hi").unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
app.remote.targets.clear();
app.remote.selected = 0;
app.set_sidebar_view(SidebarView::Remote);
app.focus_pane(Pane::Tree);
app.handle_paste(&format!("{}\n", src.display()));
assert!(app.take_pending_scp_uploads().is_empty());
assert!(
app.status.contains("no Remote Explorer host"),
"status must explain the failure, was: {:?}",
app.status,
);
assert!(
src.exists(),
"with no host the source file must be left intact",
);
}
fn relay_test_lock() -> &'static std::sync::Mutex<()> {
// The relay tests share the cache-dir test override, the
// CROFT_RELAY_KEY env var, and real relay directories, so they still
// serialize against each other — but no test mutates `$HOME` any more
// (#37), so the old crate-wide HOME_LOCK is gone and this lock is
// private to the relay family.
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
&LOCK
}
/// Point `$HOME` (hence `croft_cache_dir`) at a temp dir and set a fixed
/// `CROFT_RELAY_KEY` for the duration of `body`, restoring prior values after.
/// The relay dir is `$HOME/.cache/croft/relay-<CROFT_RELAY_KEY>`, so a relay
/// test controls the rendezvous by controlling those two env vars rather than
/// injecting the old per-connection `CROFT_DROP_RELAY_*` paths. Serialized by
/// `relay_test_lock`.
const TEST_RELAY_KEY: &str = "0123456789abcdef";
fn with_relay_home<T>(home: &std::path::Path, body: impl FnOnce() -> T) -> T {
// The cache dir is redirected through its test override instead of
// repointing the process-global `$HOME` (#37): unrelated test threads
// resolve `$HOME` at call time and a substituted value made them fail
// inside the fake home. CROFT_RELAY_KEY stays an env var — it is
// croft-specific and `relay_dir` is its only reader, so no unrelated
// reader can race on it. The restore is RAII so a panicking `body`
// cannot leak the redirected globals into later relay tests.
struct RestoreRelayGlobals {
prev_key: Option<std::ffi::OsString>,
}
impl Drop for RestoreRelayGlobals {
fn drop(&mut self) {
*crate::app::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = None;
// SAFETY: relay tests hold relay_test_lock, serializing this
// mutation.
unsafe {
match self.prev_key.take() {
Some(k) => std::env::set_var("CROFT_RELAY_KEY", k),
None => std::env::remove_var("CROFT_RELAY_KEY"),
}
}
}
}
let _restore = RestoreRelayGlobals {
prev_key: std::env::var_os("CROFT_RELAY_KEY"),
};
*crate::app::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() =
Some(home.join(".cache").join("croft"));
// SAFETY: relay tests hold relay_test_lock, serializing this mutation.
unsafe {
std::env::set_var("CROFT_RELAY_KEY", TEST_RELAY_KEY);
}
body()
}
#[test]
fn remote_launched_drop_queues_pull_request_via_relay_log() {
let _guard = relay_test_lock().lock().unwrap();
// The user dragged a Finder file onto a remote-launched croft. The Mac path
// doesn't exist on the remote box, but the session is a `croft remote` child
// (CROFT_REMOTE_AUTOUPDATE set) whose local parent runs a drop pump, so the
// drop is recorded in the identity-derived relay log (no env path needed)
// instead of being pasted into the editor.
let workspace = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Explorer);
app.focus_pane(Pane::Tree);
let (log, _) = with_relay_home(home.path(), || {
let log = app.relay_log_path().expect("relay log path derivable");
app.handle_paste("/Users/vitali/Documents/foo.txt\n");
(log, ())
});
let written = std::fs::read_to_string(&log).expect("relay log was written");
assert!(
written.starts_with("pull\t"),
"relay log entry must be a pull request, got: {written:?}",
);
assert!(
written.contains("/Users/vitali/Documents/foo.txt"),
"relay log must carry the foreign path, got: {written:?}",
);
assert_eq!(app.pending_remote_pulls.len(), 1);
}
/// #538, half one: Cmd+C inside a program that tracks the mouse.
///
/// Claude Code turns mouse tracking on, so a left-drag inside it is FORWARDED
/// to the child and croft deliberately clears its own selection (#474). Cmd+C
/// then found no selection and returned in SILENCE — the user pressed copy,
/// nothing reached the clipboard, and nothing said why or what would work.
#[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);
// The child explicitly REQUESTS click and drag tracking (?1002 button-drag,
// ?1006 SGR), which is what makes the drag below the child's rather than
// croft's. A program that never asks still selects on a plain drag.
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;
// The user drags across the TUI's output, which is the child's gesture.
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
);
}
/// #538, half two: what "the clipboard" means when croft runs on a remote box.
///
/// The user's clipboard is on the machine they are typing at, not on the Linux
/// box croft runs on. A copy there wrote the REMOTE box's clipboard (usually no
/// tool at all in an SSH session) and fell back to OSC 52, which the host
/// terminal may silently refuse — while the status line claimed success either
/// way. The drop relay already pulls the local clipboard for paste; this is the
/// same road in the other direction.
#[test]
fn copying_on_a_relay_session_pushes_the_text_to_the_local_clipboard() {
let _guard = relay_test_lock().lock().unwrap();
let tmp = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// A silent child, so the grid holds exactly what the test feeds it.
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from("sleep 60")],
tmp.path(),
)
.unwrap();
app.show_terminal = true;
app.focus_pane(Pane::Terminal);
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let inner = app.terminals[0].last_inner;
app.terminals[0].feed_bytes_for_test(b"copy-me-538\r\n");
let (lines, top) = app.terminals[0].grid_lines();
let vrow = (top
+ lines
.iter()
.position(|l| l.starts_with("copy-me-538"))
.expect("the fed text reached the grid") as i32) as u16;
app.terminals[0].start_selection_at(inner.x, inner.y + vrow);
app.terminals[0].extend_selection_to(inner.x + 20, inner.y + vrow);
let expected = app.terminals[0].selection_text();
assert!(
expected.contains("copy-me-538"),
"precondition: the selection covers the fed text, got {expected:?}"
);
// Opt in explicitly. The flag is inert under cfg(test) precisely so that
// this test's CROFT_RELAY_KEY cannot reroute a concurrent test's copy.
app.is_relay_session = true;
let (log, inbox_for_assert) = with_relay_home(home.path(), || {
let log = app.relay_log_path().expect("relay log path derivable");
let inbox = app.relay_inbox_path().expect("relay inbox path derivable");
app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER))
.unwrap();
(log, inbox)
});
let written = std::fs::read_to_string(&log).expect("relay log was written");
assert!(
written.starts_with("copy\t"),
"a copy on a relay session must queue a copy request, got {written:?}"
);
// The line carries an ID ONLY: a path on the wire would let anything that
// can write this log point the pump at a FIFO or outside the relay.
let request_id = written
.trim_end()
.split('\t')
.nth(1)
.expect("the request carries an id");
assert_eq!(
written.trim_end().split('\t').count(),
2,
"no path belongs on the wire, got {written:?}"
);
let payload_path = inbox_for_assert.join(format!("{request_id}.txt"));
let payload = std::fs::read_to_string(&payload_path).expect("the payload file was written");
assert_eq!(
payload, expected,
"the payload must be exactly what was selected"
);
assert!(
app.status.contains("local"),
"and the status must say WHERE it went, got {:?}",
app.status
);
}
#[test]
fn pure_path_payload_distinguishes_finder_drag_from_text_paste() {
// A genuine Finder drag carries only absolute path tokens.
assert!(super::is_pure_path_payload("/Users/v/Documents/foo.txt"));
assert!(super::is_pure_path_payload("/Users/v/a.txt /Users/v/b.txt"));
assert!(super::is_pure_path_payload("'/Users/v/with space.txt'"));
// Text pastes that merely contain a path always carry a non-path token, so
// they must NOT be hijacked into a relay pull.
assert!(!super::is_pure_path_payload("cat /etc/hosts"));
assert!(!super::is_pure_path_payload("see /Users/v/foo.txt please"));
assert!(!super::is_pure_path_payload("relative/path.txt"));
assert!(!super::is_pure_path_payload(""));
}
#[test]
fn remote_finder_drag_queues_pull_without_tree_focus() {
let _guard = relay_test_lock().lock().unwrap();
// A drop does not move keyboard focus to the Explorer tree, so a focus-only
// gate dropped drags whenever the user had last clicked the terminal or
// editor. A pure-path payload must be recognised regardless of focus.
let workspace = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Explorer);
app.focus_pane(Pane::Editor); // focus is NOT on the tree
let log = with_relay_home(home.path(), || {
let log = app.relay_log_path().expect("relay log path derivable");
app.handle_paste("/Users/vitali/Documents/dragged.txt\n");
log
});
let written = std::fs::read_to_string(&log).expect("relay log was written");
assert!(
written.starts_with("pull\t") && written.contains("/Users/vitali/Documents/dragged.txt"),
"a pure-path drag must queue a pull even without tree focus, got: {written:?}",
);
assert_eq!(app.pending_remote_pulls.len(), 1);
}
#[test]
fn drain_remote_pulls_imports_file_when_relay_signals_ok() {
let _guard = relay_test_lock().lock().unwrap();
let workspace = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Explorer);
app.focus_pane(Pane::Tree);
let request_dir = with_relay_home(home.path(), || {
let inbox = app.relay_inbox_path().expect("relay inbox derivable");
let request_dir = inbox.join("test-req-1");
std::fs::create_dir_all(&request_dir).unwrap();
std::fs::write(request_dir.join("foo.txt"), "payload").unwrap();
std::fs::write(request_dir.join(".ok"), b"").unwrap();
app.pending_remote_pulls.push(PendingRemotePull {
request_id: String::from("test-req-1"),
src_display: String::from("/Users/v/Docs/foo.txt"),
basename: String::from("foo.txt"),
dest_dir: workspace.path().to_path_buf(),
started_at: std::time::Instant::now(),
kind: RemotePullKind::File,
});
let changed = app.drain_remote_pulls();
assert!(changed);
request_dir
});
assert!(app.pending_remote_pulls.is_empty());
let landed = workspace.path().join("foo.txt");
assert!(landed.exists(), "file should land in workspace");
assert_eq!(std::fs::read_to_string(&landed).unwrap(), "payload");
assert!(
!request_dir.exists(),
"relay request dir must be cleaned up after import",
);
assert!(app.status.contains("Pulled"));
}
#[test]
fn drain_remote_pulls_surfaces_relay_error_message() {
let _guard = relay_test_lock().lock().unwrap();
let workspace = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
with_relay_home(home.path(), || {
let inbox = app.relay_inbox_path().expect("relay inbox derivable");
let request_dir = inbox.join("req-2");
std::fs::create_dir_all(&request_dir).unwrap();
std::fs::write(request_dir.join(".err"), b"scp exited with 1").unwrap();
app.pending_remote_pulls.push(PendingRemotePull {
request_id: String::from("req-2"),
src_display: String::from("/Users/v/missing.txt"),
basename: String::from("missing.txt"),
dest_dir: workspace.path().to_path_buf(),
started_at: std::time::Instant::now(),
kind: RemotePullKind::File,
});
let changed = app.drain_remote_pulls();
assert!(changed);
});
assert!(app.status.contains("scp exited with 1"));
}
#[test]
fn explorer_drop_on_terminal_focus_does_not_hijack_text_paste() {
// Regression guard: when sidebar is Explorer and focus is on the
// embedded terminal, pasting still goes to the terminal so the
// user can type a path into a shell command.
let workspace = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let src = outside.path().join("typed.txt");
std::fs::write(&src, "x").unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::Explorer);
app.show_terminal = true;
app.focus_pane(Pane::Terminal);
app.handle_paste(&format!("{}\n", src.display()));
assert!(
src.exists(),
"explorer-with-terminal-focus drop must NOT move the source",
);
assert!(!workspace.path().join("typed.txt").exists());
}
#[test]
fn closing_image_tab_requests_overlay_clear_on_next_render() {
// Repro for: opening a PNG/PDF then closing the tab leaves the
// OSC-1337 pixels bleeding through the welcome screen. The render
// path that swaps to welcome must mark the editor image overlay
// for clearing so the main loop wipes the screen.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.editor[0].set_test_state(
Some(String::from("dummy-osc")),
Some(EditorImageLayout {
cell_x: 0,
cell_y: 0,
cell_w: 10,
cell_h: 10,
path: tmp.path().join("doomed.png"),
page: 1,
generation: 0,
}),
true,
);
// Editor is blank-initial right after construction, so calling
// disable_editor_image directly mimics what render() does on
// the welcome branch.
app.disable_editor_image(0);
assert!(app.overlays.editor[0].image_is_none());
assert!(app.overlays.editor[0].layout_is_none());
assert!(
app.consume_editor_image_clear(),
"first call must report a pending clear"
);
assert!(
!app.consume_editor_image_clear(),
"second call must be a no-op"
);
}
#[test]
fn dragging_sidebar_splitter_resizes_sidebar() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Simulate a render so splitter coords are populated.
app.sidebar_splitter_x = Some(36); // activity(4) + sidebar(32) = 36
app.last_content_width = 60;
app.last_content_height = 20;
app.sidebar_width = 32;
// Mouse-down on the splitter column.
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 36,
row: 5,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.splitter_drag, Some(SplitterDrag::Sidebar));
// Drag right by 10 cells: column 46 -> sidebar should grow to 42.
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
column: 46,
row: 5,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.sidebar_width, 42);
// Mouse-up clears the drag state.
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
column: 46,
row: 5,
modifiers: KeyModifiers::NONE,
});
assert!(app.splitter_drag.is_none());
}
#[test]
fn sidebar_drag_grabs_one_column_left_of_seam() {
// The seam is a single column wide. To make it easier to grab (and
// to mirror the visible pair of borders the user sees), a click on
// the cell immediately to its left also starts the drag.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_splitter_x = Some(36);
app.last_content_width = 60;
app.last_content_height = 20;
app.sidebar_width = 32;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 35,
row: 5,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.splitter_drag, Some(SplitterDrag::Sidebar));
}
#[test]
fn a_stale_commit_graph_scrollbar_rect_cannot_deaden_the_splitter() {
// The COMMITS graph refreshes `last_scrollbar` only while it renders,
// i.e. only under the Source Control view. After switching to Explorer
// the stale rect used to keep punching a hole in the splitter grab
// zone: dragging the sidebar seam inside that band silently did
// nothing. The exemption must apply only while the graph is visible.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_splitter_x = Some(36);
app.last_content_width = 60;
app.last_content_height = 20;
app.sidebar_width = 32;
app.commit_graph.last_scrollbar = Rect {
x: 35,
y: 4,
width: 1,
height: 10,
};
app.sidebar_view = SidebarView::Explorer;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 35,
row: 5,
modifiers: KeyModifiers::NONE,
});
assert_eq!(
app.splitter_drag,
Some(SplitterDrag::Sidebar),
"a stale graph scrollbar rect must not deaden the seam outside Source Control"
);
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
column: 35,
row: 5,
modifiers: KeyModifiers::NONE,
});
// While the graph IS visible, its scrollbar still wins the cell.
app.sidebar_view = SidebarView::SourceControl;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 35,
row: 5,
modifiers: KeyModifiers::NONE,
});
assert!(
app.splitter_drag.is_none(),
"the live graph scrollbar keeps its exemption from the grab zone"
);
}
#[test]
fn welcome_paints_a_full_bordered_box_around_the_editor_area() {
// Without a visible envelope, users on the welcome page can't
// perceive that the explorer is resizable and can't see where the
// editor pane ends. Regression guard: the welcome render must
// paint a full Borders::ALL frame around `area` so all four edges
// are perceptible.
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();
let area = ratatui::layout::Rect::new(40, 0, 80, 40);
term.draw(|f| app.render_welcome(f, area)).unwrap();
let buf = term.backend().buffer();
let left = area.x;
let right = area.x + area.width - 1;
let top = area.y;
let bot = area.y + area.height - 1;
// Vertical edges: left and right columns must be vertical bars on
// most rows (corners use ─/└/┌/┘).
let mut left_bars = 0;
let mut right_bars = 0;
for y in (top + 1)..bot {
if buf[(left, y)].symbol() == "│" {
left_bars += 1;
}
if buf[(right, y)].symbol() == "│" {
right_bars += 1;
}
}
let inner_h = (bot - top - 1) as usize;
assert!(
left_bars >= inner_h / 2,
"left edge underpainted: {left_bars}"
);
assert!(
right_bars >= inner_h / 2,
"right edge underpainted: {right_bars}"
);
// Horizontal edges: top and bottom rows must be horizontal bars on
// most columns.
let mut top_bars = 0;
let mut bot_bars = 0;
for x in (left + 1)..right {
if buf[(x, top)].symbol() == "─" {
top_bars += 1;
}
if buf[(x, bot)].symbol() == "─" {
bot_bars += 1;
}
}
let inner_w = (right - left - 1) as usize;
assert!(top_bars >= inner_w / 2, "top edge underpainted: {top_bars}");
assert!(
bot_bars >= inner_w / 2,
"bottom edge underpainted: {bot_bars}"
);
// Corners.
assert_eq!(buf[(left, top)].symbol(), "┌");
assert_eq!(buf[(right, top)].symbol(), "┐");
assert_eq!(buf[(left, bot)].symbol(), "└");
assert_eq!(buf[(right, bot)].symbol(), "┘");
}
#[test]
fn sidebar_drag_clamps_to_minimum() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_splitter_x = Some(36);
app.last_content_width = 60;
app.last_content_height = 20;
app.sidebar_width = 32;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 36,
row: 5,
modifiers: KeyModifiers::NONE,
});
// Drag far to the left — sidebar should clamp to its min, not collapse.
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
column: 5,
row: 5,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.sidebar_width, SIDEBAR_WIDTH_MIN);
}
#[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); // bottom = 15 + 5 = 20
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.splitter_drag, Some(SplitterDrag::Terminal));
// Drag the splitter up to row 10: terminal height = 20 - 10 = 10.
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() {
// The terminal splitter sits on the terminal's top border row, but
// the editor / welcome bottom border row (one row above) is also a
// grabbable handle — symmetric with the sidebar's two-column zone.
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.splitter_drag, Some(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 split_terminal_appends_and_activates_new_one() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
assert_eq!(app.terminals.len(), 2);
assert_eq!(app.active_terminal, 1);
app.split_terminal().unwrap();
assert_eq!(app.terminals.len(), 3);
assert_eq!(app.active_terminal, 2);
}
#[test]
fn split_terminal_inserts_to_the_right_of_the_active_terminal_not_at_the_end() {
// Open three terminals so the strip is [T0, T1, T2] with T2
// active. Focus T0 (the left-most), split. The new terminal must
// land at index 1 — immediately to the right of where the user
// was looking — and T1/T2 must shift right to indices 2 and 3,
// matching the user's mental model that a new pane appears next
// to the one they're working in, not at the far right edge.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
app.split_terminal().unwrap();
let pid_t0 = app.terminals[0].pid();
let pid_t1 = app.terminals[1].pid();
let pid_t2 = app.terminals[2].pid();
app.active_terminal = 0;
app.split_terminal().unwrap();
assert_eq!(app.terminals.len(), 4);
assert_eq!(
app.active_terminal, 1,
"a split from the left-most terminal must focus the new one at index 1, not at the far right"
);
assert_eq!(
app.terminals[0].pid(),
pid_t0,
"the originally-active terminal must keep its slot"
);
assert_eq!(
app.terminals[2].pid(),
pid_t1,
"the old neighbour to the right must shift one slot right, not stay put"
);
assert_eq!(
app.terminals[3].pid(),
pid_t2,
"the right-most terminal must shift to the new right edge"
);
}
#[test]
fn close_active_terminal_drops_the_active_one() {
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.active_terminal, 2);
assert!(app.close_active_terminal());
assert_eq!(app.terminals.len(), 2);
assert_eq!(app.active_terminal, 1);
assert!(app.close_active_terminal());
assert_eq!(app.terminals.len(), 1);
assert_eq!(app.active_terminal, 0);
}
#[test]
fn close_active_terminal_refuses_to_drop_the_last_one() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(!app.close_active_terminal());
assert_eq!(app.terminals.len(), 1);
assert_eq!(app.active_terminal, 0);
}
#[test]
fn cycle_terminal_wraps_around() {
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.active_terminal = 0;
app.cycle_terminal();
assert_eq!(app.active_terminal, 1);
app.cycle_terminal();
assert_eq!(app.active_terminal, 2);
app.cycle_terminal();
assert_eq!(app.active_terminal, 0);
}
#[test]
fn cycle_terminal_back_wraps_around_to_the_left() {
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.active_terminal = 0;
app.cycle_terminal_back();
assert_eq!(
app.active_terminal, 2,
"cycle-back from the left edge must wrap to the right-most slot"
);
app.cycle_terminal_back();
assert_eq!(app.active_terminal, 1);
app.cycle_terminal_back();
assert_eq!(app.active_terminal, 0);
}
#[test]
fn cmd_left_bracket_cycles_to_the_previous_terminal() {
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.focus = Pane::Terminal;
app.active_terminal = 2;
let _ = app.handle_key(key(KeyCode::Char('['), KeyModifiers::SUPER));
assert_eq!(
app.active_terminal, 1,
"Cmd+[ must move focus one terminal to the left"
);
let _ = app.handle_key(key(KeyCode::Char('{'), KeyModifiers::SUPER));
assert_eq!(
app.active_terminal, 0,
"Cmd+{{ (shift-applied glyph) must also cycle back"
);
}
#[test]
fn cmd_right_bracket_cycles_to_the_next_terminal() {
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.focus = Pane::Terminal;
app.active_terminal = 0;
let _ = app.handle_key(key(KeyCode::Char(']'), KeyModifiers::SUPER));
assert_eq!(
app.active_terminal, 1,
"Cmd+] must move focus one terminal to the right"
);
let _ = app.handle_key(key(KeyCode::Char('}'), KeyModifiers::SUPER));
assert_eq!(
app.active_terminal, 2,
"Cmd+}} (shift-applied glyph) must also cycle forward"
);
}
#[test]
fn ctrl_shift_t_globally_splits_terminal() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert_eq!(app.terminals.len(), 1);
app.handle_key(key(
KeyCode::Char('T'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(app.terminals.len(), 2);
assert_eq!(app.active_terminal, 1);
}
#[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 clicking_terminal_add_button_splits() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminal_add_buttons = vec![Rect {
x: 50,
y: 30,
width: 3,
height: 1,
}];
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 51,
row: 30,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.terminals.len(), 2);
assert_eq!(app.active_terminal, 1);
}
#[test]
fn clicking_terminal_close_button_drops_active_terminal() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
assert_eq!(app.terminals.len(), 2);
assert_eq!(app.active_terminal, 1);
app.terminal_close_buttons = vec![
Rect {
x: 10,
y: 30,
width: 3,
height: 1,
},
Rect {
x: 50,
y: 30,
width: 3,
height: 1,
},
];
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 51,
row: 30,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.terminals.len(), 1);
}
#[test]
fn clicking_close_button_on_non_active_terminal_drops_that_specific_terminal() {
// The user has three terminals open with the rightmost (idx 2) active;
// clicking the [-] on the leftmost terminal must close idx 0, not the
// active one. Regression for "I would like to kill any of them, not
// only the right one."
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);
assert_eq!(app.active_terminal, 2);
let pid_left = app.terminals[0].pid();
let pid_right = app.terminals[2].pid();
app.terminal_close_buttons = vec![
Rect {
x: 10,
y: 30,
width: 3,
height: 1,
},
Rect {
x: 30,
y: 30,
width: 3,
height: 1,
},
Rect {
x: 50,
y: 30,
width: 3,
height: 1,
},
];
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 11,
row: 30,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.terminals.len(), 2);
assert!(
app.terminals.iter().all(|t| t.pid() != pid_left),
"the leftmost terminal (the one whose [-] was clicked) must be gone"
);
assert_eq!(
app.terminals[1].pid(),
pid_right,
"the formerly-rightmost terminal must remain"
);
assert_eq!(
app.active_terminal, 1,
"active terminal index must shift down so the same terminal stays active"
);
}
#[test]
fn each_terminal_paints_its_own_add_close_buttons_when_multiple_open() {
// Per-pane chrome: with N terminals visible there should be N [+] hit
// rects (one per pane) and, when N > 1, N [-] hit rects so the user
// can kill any one of them.
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.terminal_add_buttons.len(),
3,
"each terminal pane must record its own [+] hit rect"
);
assert_eq!(
app.terminal_close_buttons.len(),
3,
"each terminal pane must record its own [-] hit rect when more than one is open"
);
// Distinct columns: the buttons must sit on different panes.
let xs: std::collections::HashSet<u16> = app.terminal_add_buttons.iter().map(|r| r.x).collect();
assert_eq!(
xs.len(),
3,
"add-button rects must be on three distinct columns"
);
}
#[test]
fn clicking_terminal_maximize_button_maximizes_that_pane() {
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.active_terminal, 2);
app.terminal_max_buttons = vec![
Rect {
x: 10,
y: 30,
width: 3,
height: 1,
},
Rect {
x: 30,
y: 30,
width: 3,
height: 1,
},
Rect {
x: 50,
y: 30,
width: 3,
height: 1,
},
];
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 11,
row: 30,
modifiers: KeyModifiers::NONE,
});
assert!(
app.terminal_pane_maximized,
"the ⛶ click enters maximize mode"
);
assert_eq!(
app.active_terminal, 0,
"the pane whose ⛶ was clicked becomes the maximized one"
);
}
/// #510: a pane the frame does not paint must drop `last_inner` as well as
/// `last_area`.
///
/// `last_area` guards clicks and is cleared at six terminal-pane sites.
/// `last_inner` was assigned in exactly one place - inside `render` - and
/// cleared nowhere, so a hidden pane kept the rect it held under the PREVIOUS
/// layout. That rect anchors the terminal image overlay, which is emitted
/// after `terminal.draw()` with absolute cursor positioning and is bounded by
/// nothing else: `update_terminal_image_overlay` checks the payload against
/// the same stale rect, so every check passes and the write lands wherever
/// the old origin pointed - over a sibling pane, the sidebar, or the status
/// bar. Being a raw write rather than a buffer index it cannot panic, and
/// ratatui's diff has no record of the cells it touched, so nothing repairs
/// them on the next frame.
///
/// Maximize is the reachable route: it hands every non-active pane
/// `Rect::default()`, so the render loop skips them while they keep the split
/// column they occupied a frame earlier.
#[test]
fn a_hidden_pane_drops_last_inner_not_just_last_area() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
app.split_terminal().unwrap();
let backend = ratatui::backend::TestBackend::new(180, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
// Paint the split first, so every pane holds a real inner rect.
term.draw(|f| app.render(f)).unwrap();
let active = app.active_terminal;
let hidden = (0..app.terminals.len()).find(|i| *i != active).unwrap();
assert!(
app.terminals[hidden].last_inner.width > 0,
"precondition: the pane painted a real inner rect while split"
);
// Maximize, which stops painting it.
app.terminal_pane_maximized = true;
term.draw(|f| app.render(f)).unwrap();
assert_eq!(
app.terminals[hidden].last_inner,
Rect::default(),
"a pane the frame skipped must not keep an inner rect the overlay \
would anchor a raw write to"
);
}
/// The same invariant through the PUBLIC gesture rather than the flag, so a
/// regression that stops `toggle_terminal_pane_maximize` reaching this state
/// is caught too. Setting `terminal_pane_maximized` directly pins the render
/// loop; this pins the command.
#[test]
fn the_maximize_gesture_also_drops_a_hidden_panes_last_inner() {
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(180, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let active = app.active_terminal;
let hidden = (0..app.terminals.len()).find(|i| *i != active).unwrap();
assert!(app.terminals[hidden].last_inner.width > 0, "precondition");
app.toggle_terminal_pane_maximize();
term.draw(|f| app.render(f)).unwrap();
assert_eq!(
app.terminals[hidden].last_inner,
Rect::default(),
"the gesture, not just the flag, must drop the hidden pane's rect"
);
}
/// The collapse arm of the same condition. `t.collapsed && !maximized` is the
/// other route into that clear, and the maximize tests never reach it.
#[test]
fn a_collapsed_pane_drops_last_inner_too() {
let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
term.draw(|f| app.render(f)).unwrap();
assert!(app.terminals[1].last_inner.width > 0, "precondition");
app.toggle_terminal_collapse(1);
term.draw(|f| app.render(f)).unwrap();
assert_eq!(
app.terminals[1].last_inner,
Rect::default(),
"a folded pane keeps no rect for the overlay to anchor to"
);
}
#[test]
fn maximized_terminal_fills_width_and_lists_others_in_rail() {
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 active = app.active_terminal;
assert!(
app.terminals[active].last_area.width >= 100,
"the maximized pane must span (almost) the whole panel width, got {}",
app.terminals[active].last_area.width
);
for (i, t) in app.terminals.iter().enumerate() {
if i != active {
assert_eq!(
t.last_area,
Rect::default(),
"hidden pane {i} must drop its hit rect so clicks can't phantom-match"
);
}
}
assert_eq!(
app.terminal_rail_rects.len(),
3,
"the right-side rail lists every terminal"
);
let xs: std::collections::HashSet<u16> = app.terminal_rail_rects.iter().map(|r| r.x).collect();
assert_eq!(xs.len(), 1, "rail rows stack vertically in one column");
let ys: std::collections::HashSet<u16> = app.terminal_rail_rects.iter().map(|r| r.y).collect();
assert_eq!(ys.len(), 3, "each rail row sits on its own line");
// Index alignment: in maximize mode only the visible pane carries live
// button rects; the hidden panes hold empty placeholders so a button's
// position in the vec still names its terminal index.
assert_eq!(app.terminal_max_buttons.len(), 3);
let live: Vec<usize> = app
.terminal_max_buttons
.iter()
.enumerate()
.filter(|(_, r)| r.width > 0)
.map(|(i, _)| i)
.collect();
assert_eq!(
live,
vec![active],
"only the maximized pane paints a restore button"
);
}
#[test]
fn a_clamped_rail_never_paints_past_its_own_column() {
// The rail width is clamped at the call site to
// `content.width.saturating_sub(20)`, but the label was always rendered as
// a fixed 7 cells (space + icon + space + 4 chars). `Buffer::set_string`
// clips at the FRAME edge, not at the rail rect, so on a narrow panel the
// tail of the label lands on whatever is drawn to the right of the panel.
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;
// A label character no other widget can paint, so "this cell holds a label
// char" is proof of a bleed and not a coincidence with the panel's text.
app.terminals[0].set_manual_name(Some(String::from("§§§§")));
app.terminals[1].set_manual_name(Some(String::from("§§§§")));
// Wide enough that the buffer edge cannot mask the bleed, narrow enough
// that the clamp bites: the assertion is the rail's own right edge.
// The bleed is only observable when something is DRAWN to the right of the
// panel, so the secondary side bar must be up: the panel clips at the frame
// edge otherwise and the overrun is silently truncated.
let backend = ratatui::backend::TestBackend::new(80, 24);
let mut term = ratatui::Terminal::new(backend).unwrap();
app.secondary_side_bar_visible = true;
app.sidebar_width = 21;
term.draw(|f| app.render(f)).unwrap();
assert!(
app.terminal_rail_rects
.iter()
.any(|r| r.width < TERMINAL_RAIL_W),
"this layout must actually clamp the rail, or the test proves nothing"
);
let cell = |x: u16, y: u16| {
term.backend()
.buffer()
.cell(ratatui::layout::Position::new(x, y))
.unwrap()
.symbol()
.to_string()
};
for rail in &app.terminal_rail_rects {
let past = rail.x + rail.width;
// Inside the rail the label must actually be painted, or a future
// layout change could shrink the rail until nothing bleeds and the
// assertion below passes while the bug is fully restored.
let inside: String = (rail.x..past).map(|x| cell(x, rail.y)).collect();
assert!(
inside.contains('§'),
"the rail must paint some of its label, got {inside:?}"
);
// Every cell from the rail's right edge to the frame edge: not a fixed
// peephole, so the check survives any change to the pane constants.
let bleed: String = (past..80).map(|x| cell(x, rail.y)).collect();
assert!(
!bleed.contains('§'),
"the rail label bled past its own column into {bleed:?}"
);
}
}
#[test]
fn rail_is_a_fixed_narrow_column_showing_four_label_chars() {
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();
// The rail is a fixed, very narrow column: icon + exactly 4 label
// characters, regardless of how short or long the names are.
app.terminals[0].set_manual_name(Some(String::from("zsh")));
app.terminals[1].set_manual_name(Some(String::from("a-very-long-terminal-pane-name")));
term.draw(|f| app.render(f)).unwrap();
for r in &app.terminal_rail_rects {
assert_eq!(
r.width, TERMINAL_RAIL_W,
"the rail must always be exactly {TERMINAL_RAIL_W} cells wide"
);
}
// The long name is cut to its first 4 characters in the rail row.
let rail = app.terminal_rail_rects[1];
let cells: String = (rail.x..rail.x + rail.width)
.map(|x| {
term.backend()
.buffer()
.cell(ratatui::layout::Position::new(x, rail.y))
.unwrap()
.symbol()
.chars()
.next()
.unwrap()
})
.collect();
assert!(
cells.contains("a-ve") && !cells.contains("a-ver"),
"rail row must show exactly the first 4 label chars, got {cells:?}"
);
}
#[test]
fn clicking_rail_row_switches_terminal_and_stays_maximized() {
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 r = app.terminal_rail_rects[0];
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_eq!(app.active_terminal, 0, "the rail row picks its terminal");
assert!(
app.terminal_pane_maximized,
"shuffling via the rail stays in maximize mode"
);
term.draw(|f| app.render(f)).unwrap();
assert!(
app.terminals[0].last_area.width >= 100,
"the newly picked terminal now owns the maximized pane"
);
}
#[test]
fn a_long_pane_label_never_overpaints_the_maximize_button() {
// The header buttons lay out right-to-left, and the `⛶` added by this span
// is the leftmost of four, at `col.width - 13`. The pane pill's width
// budget still reserved room for three buttons, so a label that fills its
// budget painted straight over the glyph — worst with the broadcast `⇶`
// or a host accent, whose prefixes widen the pill by two more cells and
// erase it entirely. The button's hit rect stays live underneath, so those
// cells silently maximize instead of starting the drag-reorder the pill
// advertises.
//
// Both label characters are deliberate: `§` is one cell, so it pins the
// char budget, and `項` is two, so it pins that the CLIP is measured in
// display cells. A budget counted in chars passes the `§` case while a
// wide-character name still runs over the button.
for name in ["§".repeat(30), "項".repeat(30)] {
assert_pane_pill_clears_its_buttons(&name);
}
}
fn assert_pane_pill_clears_its_buttons(name: &str) {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for _ in 0..3 {
app.split_terminal().unwrap();
}
for t in app.terminals.iter_mut() {
t.set_manual_name(Some(String::from(name)));
}
// Broadcast is on so the pill wears its widest form.
app.broadcast_input = true;
let backend = ratatui::backend::TestBackend::new(140, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let glyph = name.chars().next().unwrap();
let cell = |x: u16, y: u16| {
term.backend()
.buffer()
.cell(ratatui::layout::Position::new(x, y))
.unwrap()
.symbol()
.to_string()
};
let mut checked = 0;
// Every button in the strip, not only `⛶`. Since #313 the leftmost is the
// `‹` collapse button, and checking the old leftmost alone would leave the
// new one free to be overpainted - the same bug this test exists for,
// three columns over.
let families: [(&str, &Vec<Rect>, char); 2] = [
("collapse", &app.terminal_collapse_buttons, '\u{eab5}'),
("maximize", &app.terminal_max_buttons, '\u{eb4c}'),
];
for (i, pill) in app.terminal_label_rects.iter().enumerate() {
let painted: Vec<(&str, Rect, char)> = families
.iter()
.filter(|(_, rects, _)| rects[i].width > 0)
.map(|(f, rects, want)| (*f, rects[i], *want))
.collect();
if painted.is_empty() {
continue;
}
// The pill has to run right up to the button strip, or a layout that
// simply left it short would pass this while the bug stands. Measured
// against the LEFTMOST button: the pill is clipped at the strip's
// edge, so asking it to also reach the rightmost would be asking it to
// be in two places at once.
//
// One cell of slack, and only one: a two-cell grapheme that would
// straddle the clip boundary is dropped whole rather than half-painted,
// so a `項` name legitimately stops one column short where a `§` name
// lands exactly on it. Two cells of slack would start admitting pills
// that were never long enough to threaten the buttons at all.
let leftmost = painted.iter().map(|(_, r, _)| r.x).min().unwrap();
assert!(
pill.width > 0 && pill.x + pill.width + 1 >= leftmost,
"pane {i}'s pill must reach the button strip for this to prove \
anything, pill={pill:?} strip starts at {leftmost}"
);
for (family, btn, want) in painted {
let cells: String = (btn.x..btn.x + btn.width).map(|x| cell(x, btn.y)).collect();
assert!(
!cells.contains(glyph),
"pane {i}'s {glyph:?} label painted over its {family} button: {cells:?}"
);
assert!(
cells.contains(want),
"pane {i}'s {family} glyph must survive a {glyph:?} label, got {cells:?}"
);
checked += 1;
}
}
assert!(
checked >= 4,
"this layout must paint both button families to test"
);
}
#[test]
fn the_profile_picker_anchors_under_the_pane_that_owns_the_caret() {
// Hidden panes push `Rect::default()` placeholders so a button's position
// in the vec names its terminal. The picker still anchored on `.first()`,
// which in maximize mode is the placeholder for terminal 0 whenever some
// other pane is the maximized one, dropping the dropdown at the window's
// top-left corner instead of under the caret it was opened from.
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;
assert_eq!(
app.active_terminal, 2,
"the newest pane is the maximized one"
);
let backend = ratatui::backend::TestBackend::new(180, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let caret = app.terminal_profile_buttons[2];
assert!(caret.width > 0, "the maximized pane paints a profile caret");
assert_eq!(
app.terminal_profile_buttons[0],
ratatui::layout::Rect::default(),
"the hidden pane holds a placeholder, which is what `.first()` found"
);
assert_eq!(
app.terminal_caret_origin(2),
(caret.x, caret.y + 1),
"the dropdown anchors under the caret that is actually on screen"
);
// Side by side every pane has a live caret, so anchoring on the first
// live one would hang every pane's dropdown under the leftmost.
app.terminal_pane_maximized = false;
term.draw(|f| app.render(f)).unwrap();
let rightmost = app.terminal_profile_buttons[2];
assert!(
rightmost.x > app.terminal_profile_buttons[0].x,
"the panes must really be side by side for this to prove anything"
);
assert_eq!(
app.terminal_caret_origin(2),
(rightmost.x, rightmost.y + 1),
"each pane's dropdown anchors under its OWN caret"
);
}
#[test]
fn a_rail_taller_than_the_panel_scrolls_instead_of_dropping_terminals() {
// The rail painted one row per terminal and stopped at the panel's bottom
// edge, so with more terminals than rows the tail simply vanished: no row,
// no hit rect, and if the active terminal was among them nothing in the
// rail was highlighted at all. The panel floor is 3 rows, so four panes
// are enough to reach this.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for _ in 0..5 {
app.split_terminal().unwrap();
}
app.terminal_pane_maximized = true;
app.terminal_height = Some(TERMINAL_HEIGHT_MIN);
let backend = ratatui::backend::TestBackend::new(180, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let live = |app: &App| -> usize {
app.terminal_rail_rects
.iter()
.filter(|r| r.width > 0)
.count()
};
assert!(
live(&app) < app.terminals.len(),
"this layout must actually overflow the rail, or the test proves nothing"
);
assert_eq!(
app.terminal_rail_rects.len(),
app.terminals.len(),
"off-window rows still hold a placeholder so a rect's position names \
its terminal"
);
// The active terminal is the last one, past the window's bottom edge.
assert!(
app.terminal_rail_rects[app.active_terminal].width > 0,
"the rail must scroll to keep the active terminal visible"
);
// The wheel reaches the terminals the window has scrolled past.
let rail = app.terminal_rail_area;
assert!(
rail.width > 0,
"the rail records its own area for the wheel"
);
for _ in 0..app.terminals.len() {
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::ScrollUp,
column: rail.x,
row: rail.y,
modifiers: KeyModifiers::NONE,
});
}
term.draw(|f| app.render(f)).unwrap();
assert!(
app.terminal_rail_rects[0].width > 0,
"scrolling the rail up must reach the first terminal"
);
}
#[test]
fn reordering_a_maximized_pane_keeps_its_rect_with_the_terminal() {
// `move_terminal` re-seats `last_area` in SLOT order, which is right for
// the even split, where a slot's geometry is positional. Maximize mode has
// exactly ONE live rect and it belongs to whichever pane was active at the
// last PAINT — not to the dragged terminal, since the press and the drag
// are drained together — so seating by slot left the pane the drag makes
// active holding an empty rect for the rest of the burst.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
app.split_terminal().unwrap();
for (i, t) in app.terminals.iter_mut().enumerate() {
t.set_manual_name(Some(format!("pane{i}")));
}
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();
assert_eq!(app.active_terminal, 2);
let pane = app.terminals[2].last_area;
assert!(
pane.width > 100,
"the maximized pane owns the panel's width"
);
// The real gesture: press rail row 0, drag onto row 2, with NO redraw in
// between — the main loop drains the whole burst before painting, so the
// live pane rect still belongs to whichever pane was active at the last
// paint, not to the one being dragged.
let press = app.terminal_rail_rects[0];
let target = app.terminal_rail_rects[2];
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: press.x + 1,
row: press.y,
modifiers: KeyModifiers::NONE,
});
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
column: target.x + 1,
row: target.y,
modifiers: KeyModifiers::NONE,
});
// The reorder must actually have happened: without this every assertion
// below also holds when the gesture is a no-op, since slot 2 already owned
// the pane before the drag.
assert_eq!(
app.terminals[2].label(),
"pane0",
"the dragged terminal must have moved from slot 0 to slot 2"
);
assert_eq!(app.active_terminal, 2, "the dragged terminal stays active");
assert_eq!(
app.terminals[2].last_area, pane,
"the live pane rect follows the pane the drag leaves active"
);
assert!(
app.terminals[..2].iter().all(|t| t.last_area.width == 0),
"the hidden panes keep empty rects"
);
// The whole point: the next motion report in this same burst must resolve
// to the pane that owns the panel, not to a hidden one.
assert_eq!(
app.terminal_at_pos(pane.x + pane.width / 2, pane.y + pane.height / 2),
Some(2),
"a hit inside the maximized pane names the active terminal"
);
}
#[test]
fn delete_line_deletes_every_carets_line() {
// Cmd+D (Add Selection to Next Match) and Cmd+Shift+K (Delete Line) landed
// in the same commit, but Delete Line only ever removed the primary
// cursor's line: `delete_lines` calls `clear_selection`, which clears the
// selection and leaves `carets` untouched. VS Code's deleteLines removes
// every cursor's line, so the two bindings must compose.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let file = tmp.path().join("a.txt");
std::fs::write(&file, "foo\nbar\nfoo\nbaz\n").unwrap();
app.editor.open(&file).unwrap();
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
// Cmd+D twice: the first selects the word under the cursor, the second
// adds the next match, demoting row 0 to a secondary caret.
app.start_select_next_occurrence();
app.start_select_next_occurrence();
assert_eq!(app.editor.carets.len(), 1, "row 0 is now a secondary caret");
assert_eq!(
app.editor.cursor_row, 2,
"the primary moved to the next match"
);
app.delete_current_line();
assert_eq!(
app.editor.lines,
vec![String::from("bar"), String::from("baz")],
"both matched lines go, not just the primary's"
);
assert!(
app.editor.carets.is_empty(),
"no stale caret is left painted on a line that no longer exists"
);
}
#[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.terminal_max_buttons[app.active_terminal];
assert!(r.width > 0, "the maximized pane 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.terminal_rail_rects.is_empty(),
"the rail disappears with the split restored"
);
}
#[test]
fn cmd_k_m_toggles_terminal_maximize() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('m'), KeyModifiers::NONE))
.unwrap();
assert!(
app.terminal_pane_maximized,
"Cmd+K M maximizes the active pane"
);
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('m'), KeyModifiers::NONE))
.unwrap();
assert!(
!app.terminal_pane_maximized,
"Cmd+K M again restores the split"
);
}
#[test]
fn closing_down_to_one_terminal_exits_maximize() {
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;
assert!(app.close_terminal_at(0));
assert!(
!app.terminal_pane_maximized,
"a lone terminal has nothing to maximize against; the flag resets"
);
}
#[test]
fn cwd_of_pid_on_self_returns_a_directory_under_tempdir() {
// The harness runs each test from the crate root by default, but
// we don't depend on that — we just need cwd_of_pid to round-trip
// *some* directory for the current process. lsof / /proc gives us
// the live cwd of the shell that started the test runner.
let pid = std::process::id();
match cwd_of_pid(pid) {
Some(p) => assert!(
p.is_dir(),
"cwd lookup must return a real directory, got {p:?}"
),
None => {
// Acceptable on platforms where neither /proc nor lsof
// resolve the cwd in the sandbox. The fallback in
// split_terminal handles that case; nothing to assert here.
}
}
}
#[test]
fn add_button_wins_over_terminal_splitter_on_same_row() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Splitter and button share the row, as they do in real layout.
app.terminal_splitter_y = Some(30);
app.terminal_add_buttons = vec![Rect {
x: 50,
y: 30,
width: 3,
height: 1,
}];
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: 51,
row: 30,
modifiers: KeyModifiers::NONE,
});
assert!(
app.splitter_drag.is_none(),
"click on [+] must not start a splitter drag"
);
assert_eq!(app.terminals.len(), 2);
}
#[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();
// Fresh App starts dirty so the first frame paints.
assert!(app.peek_terminals_dirty(), "fresh app should be dirty");
// Two consecutive peeks must both see the flag - peek must not clear.
assert!(
app.peek_terminals_dirty(),
"peek must not consume the dirty flag"
);
// Drain consumes it.
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 cmd_shift_g_no_longer_jumps_to_source_control() {
// Source Control is reached via Cmd+Shift+S; the old Cmd+Shift+G alias
// was removed so the chord stays free for the editor's vim-style
// "go to bottom of file".
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_key(key(
KeyCode::Char('G'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert_ne!(
app.sidebar_view,
SidebarView::SourceControl,
"Cmd+Shift+G must no longer route to Source Control"
);
}
#[test]
fn activity_bar_render_lays_out_run_debug_between_source_control_and_remote() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let bar = Rect {
x: 0,
y: 0,
width: ACTIVITY_BAR_WIDTH,
height: 30,
};
let backend = ratatui::backend::TestBackend::new(40, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render_activity_bar(f, bar)).unwrap();
let scm = app.sidebar_areas.source_control_icon;
let run = app.sidebar_areas.run_debug_icon;
let rem = app.sidebar_areas.remote_icon;
assert!(run.height > 0, "run-debug icon must claim a non-zero block");
assert!(
run.y > scm.y,
"run-debug must sit BELOW source-control (scm.y={}, run.y={})",
scm.y,
run.y
);
assert!(
run.y < rem.y,
"run-debug must sit ABOVE remote (run.y={}, rem.y={}) — VS Code's activity-bar order",
run.y,
rem.y
);
}
#[test]
fn click_on_run_debug_icon_switches_sidebar_to_run_debug() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let backend = ratatui::backend::TestBackend::new(80, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let run = app.sidebar_areas.run_debug_icon;
assert!(run.height > 0, "run-debug icon must be laid out");
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: run.x,
row: run.y,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.sidebar_view, SidebarView::RunDebug);
}
#[test]
fn run_spec_for_python_with_no_venv_falls_back_to_system_python3() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("script.py");
std::fs::write(&f, b"").unwrap();
let spec = App::run_spec_for(&f, tmp.path()).unwrap();
assert_eq!(spec.program, "python3");
assert_eq!(spec.args, vec![f.to_string_lossy().into_owned()]);
assert_eq!(spec.cwd, tmp.path());
}
#[test]
fn run_spec_for_node_picks_node_for_dot_js() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("server.js");
std::fs::write(&f, b"").unwrap();
let spec = App::run_spec_for(&f, tmp.path()).unwrap();
assert_eq!(spec.program, "node");
assert_eq!(spec.args, vec![f.to_string_lossy().into_owned()]);
}
#[test]
fn run_spec_for_bash_picks_bash_for_dot_sh() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("build.sh");
std::fs::write(&f, b"").unwrap();
let spec = App::run_spec_for(&f, tmp.path()).unwrap();
assert_eq!(spec.program, "bash");
assert_eq!(spec.args, vec![f.to_string_lossy().into_owned()]);
}
#[test]
fn run_spec_for_unknown_extension_returns_none() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("notes.txt");
std::fs::write(&f, b"").unwrap();
assert!(App::run_spec_for(&f, tmp.path()).is_none());
}
#[test]
fn run_spec_passes_apostrophe_paths_through_argv_unescaped() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("O'Reilly.py");
std::fs::write(&f, b"").unwrap();
let spec = App::run_spec_for(&f, tmp.path()).unwrap();
assert_eq!(
spec.args,
vec![f.to_string_lossy().into_owned()],
"argv carries the path verbatim — no shell quoting because no shell is invoked"
);
}
/// Drop a fake `bin/python` shim in `dir/.venv/bin/python` so the venv
/// detector finds an executable file. Returns the full path to the shim
/// for assertions.
fn make_venv(dir: &Path, venv_name: &str) -> PathBuf {
let bin = dir.join(venv_name).join("bin");
std::fs::create_dir_all(&bin).unwrap();
let py = bin.join("python");
std::fs::write(&py, b"#!/bin/sh\nexit 0\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = std::fs::metadata(&py).unwrap().permissions();
perms.set_mode(0o755);
std::fs::set_permissions(&py, perms).unwrap();
}
py
}
#[test]
fn run_spec_picks_dot_venv_python_in_the_file_directory_over_system_python3() {
// Reproduces the user-reported case: croft is opened on a parent
// directory, the file lives in a subfolder that owns a .venv, and
// running the file with system python3 misses the project's deps.
let tmp = tempfile::tempdir().unwrap();
let project = tmp.path().join("project");
std::fs::create_dir_all(&project).unwrap();
let venv_python = make_venv(&project, ".venv");
let f = project.join("main.py");
std::fs::write(&f, b"").unwrap();
let spec = App::run_spec_for(&f, tmp.path()).unwrap();
assert_eq!(
spec.program,
venv_python.to_string_lossy().into_owned(),
"venv interpreter must be the spawned program (looked for {})",
venv_python.display()
);
assert_eq!(spec.args, vec![f.to_string_lossy().into_owned()]);
assert_eq!(
spec.cwd, project,
"cwd must be the directory that owns the venv so relative imports / .env files resolve"
);
}
#[test]
fn run_spec_walks_up_from_file_dir_to_find_venv_in_an_ancestor() {
let tmp = tempfile::tempdir().unwrap();
let project = tmp.path().join("project");
let nested = project.join("src").join("pkg");
std::fs::create_dir_all(&nested).unwrap();
make_venv(&project, ".venv");
let f = nested.join("main.py");
std::fs::write(&f, b"").unwrap();
let spec = App::run_spec_for(&f, tmp.path()).unwrap();
assert!(
spec.program.ends_with(".venv/bin/python"),
"expected venv python program, got: {}",
spec.program
);
assert_eq!(spec.cwd, project);
}
#[test]
fn run_spec_also_picks_a_plain_venv_directory() {
let tmp = tempfile::tempdir().unwrap();
make_venv(tmp.path(), "venv");
let f = tmp.path().join("main.py");
std::fs::write(&f, b"").unwrap();
let spec = App::run_spec_for(&f, tmp.path()).unwrap();
assert!(
spec.program.ends_with("venv/bin/python"),
"expected plain-venv python program, got: {}",
spec.program
);
}
#[test]
fn run_spec_does_not_walk_above_workspace_root() {
let tmp = tempfile::tempdir().unwrap();
// venv lives ABOVE the workspace root — must be ignored.
make_venv(tmp.path(), ".venv");
let workspace = tmp.path().join("inner");
std::fs::create_dir_all(&workspace).unwrap();
let f = workspace.join("main.py");
std::fs::write(&f, b"").unwrap();
let spec = App::run_spec_for(&f, &workspace).unwrap();
assert_eq!(
spec.program, "python3",
"must NOT use a venv that sits above the workspace root, got: {}",
spec.program
);
}
#[test]
fn run_active_file_with_no_open_file_records_feedback_and_does_not_spawn_terminal() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let term_count_before = app.terminals.len();
app.run_active_file();
assert_eq!(
app.terminals.len(),
term_count_before,
"no file open: must NOT spawn an extra terminal"
);
assert!(app.run_debug.feedback_is_error);
assert!(app.run_debug.feedback.is_some());
}
#[test]
fn run_active_file_with_unknown_extension_records_feedback_and_does_not_spawn_terminal() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("notes.txt");
std::fs::write(&f, b"hi").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
let term_count_before = app.terminals.len();
app.run_active_file();
assert_eq!(app.terminals.len(), term_count_before);
assert!(app.run_debug.feedback_is_error);
}
#[test]
fn run_active_file_with_python_file_spawns_a_new_terminal_and_focuses_it() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("hello.py");
std::fs::write(&f, b"print('hi')\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
let term_count_before = app.terminals.len();
app.run_active_file();
assert_eq!(
app.terminals.len(),
term_count_before + 1,
"running a known extension must spawn a fresh terminal so the previous one's history isn't clobbered"
);
assert!(app.show_terminal, "terminal pane must become visible");
assert!(matches!(app.focus, Pane::Terminal));
assert!(!app.run_debug.feedback_is_error);
}
#[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 f9_relaunches_only_when_update_is_ready() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Not ready: F9 must not arm the re-exec.
let _ = app.handle_key(key(KeyCode::F(9), KeyModifiers::empty()));
assert!(!app.pending_reexec);
assert!(!app.quit);
// Ready: F9 arms the re-exec and quits the loop so `run` can exec.
app.update_status = UpdateStatus::Ready;
let _ = app.handle_key(key(KeyCode::F(9), KeyModifiers::empty()));
assert!(app.pending_reexec);
assert!(app.quit);
}
#[test]
fn bare_f10_reaches_the_shell_when_terminal_is_focused_with_no_debug_session() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// A pane that prints back the raw bytes it reads: F10 must arrive as
// \x1b[21~, which `cat -v` renders as ^[[21~. That sentinel never appears
// in the script text, so the echoed run-label header cannot fake a pass.
let script = "stty raw -echo; dd bs=1 count=5 2>/dev/null | cat -v; sleep 60";
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from(script)],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
let _ = app.handle_key(key(KeyCode::F(10), KeyModifiers::NONE));
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"F10 to reach the PTY rather than being swallowed",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("^[[21~"))
},
);
}
#[test]
fn bare_f9_reexecs_a_ready_update_even_when_the_terminal_is_focused() {
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::empty()));
assert!(
app.pending_reexec && app.quit,
"a landed update must still win F9 over PTY forwarding"
);
}
#[test]
fn session_state_round_trip_reopens_tabs_at_saved_cursor_and_active() {
let tmp = tempfile::tempdir().unwrap();
let file_a = tmp.path().join("a.txt");
let file_b = tmp.path().join("b.txt");
std::fs::write(&file_a, "line0\nline1\nline2\n").unwrap();
std::fs::write(&file_b, "only\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file_a).unwrap();
app.editor.open_pinned(&file_b).unwrap();
// Park the cursor on a.txt and make it the active tab.
let idx_a = app
.editor
.editors
.iter()
.position(|e| e.path.as_deref() == Some(file_a.as_path()))
.unwrap();
app.editor.editors[idx_a].cursor_row = 2;
app.editor.editors[idx_a].cursor_col = 3;
app.editor.select(idx_a);
let state = app.capture_session_state();
assert_eq!(state.tabs.len(), 2);
assert_eq!(
state.tabs[state.active_tab].path.as_deref(),
Some(file_a.as_path())
);
let mut restored = App::new(tmp.path().to_path_buf()).unwrap();
restored.apply_session_state(&state);
let restored_paths: Vec<_> = restored
.editor
.editors
.iter()
.filter_map(|e| e.path.clone())
.collect();
assert!(restored_paths.contains(&file_a));
assert!(restored_paths.contains(&file_b));
let active = &restored.editor.editors[restored.editor.active_index()];
assert_eq!(active.path.as_deref(), Some(file_a.as_path()));
assert_eq!(active.cursor_row, 2);
assert_eq!(active.cursor_col, 3);
}
#[test]
fn session_state_preserves_unsaved_buffer_contents() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("dirty.txt");
std::fs::write(&file, "saved\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
let idx = app.editor.active_index();
app.editor.editors[idx].lines = vec![String::from("edited unsaved")];
app.editor.editors[idx].dirty = true;
let state = app.capture_session_state();
let tab = state
.tabs
.iter()
.find(|t| t.path.as_ref() == Some(&file))
.unwrap();
assert!(tab.dirty);
assert_eq!(tab.unsaved_text.as_deref(), Some("edited unsaved"));
let mut restored = App::new(tmp.path().to_path_buf()).unwrap();
restored.apply_session_state(&state);
let ed = restored
.editor
.editors
.iter()
.find(|e| e.path.as_deref() == Some(file.as_path()))
.unwrap();
assert!(ed.dirty);
assert_eq!(ed.lines, vec![String::from("edited unsaved")]);
// On-disk file must be untouched by the capture/restore.
assert_eq!(std::fs::read_to_string(&file).unwrap(), "saved\n");
}
/// A relaunch carries the unsaved text of every split, not just the
/// focused one.
#[test]
fn session_state_keeps_unsaved_edits_from_every_split() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
let c = tmp.path().join("c.txt");
std::fs::write(&a, "a\n").unwrap();
std::fs::write(&c, "c\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.editor.lines = vec![String::from("edited a")];
app.editor.dirty = true;
app.focus_pane(Pane::Editor);
app.split_editor();
// The focused (right) group moves to another file and closes its copy.
app.editor.open_pinned(&c).unwrap();
app.editor.close_tab(0);
let state = app.capture_session_state();
let tab = state
.tabs
.iter()
.find(|t| t.path.as_ref() == Some(&a))
.expect("the left split's dirty tab is carried");
assert_eq!(tab.unsaved_text.as_deref(), Some("edited a"));
}
/// A self-update must not drop the only copy of unsaved text: neither an
/// untitled buffer's nor that of a file deleted while the update ran.
#[test]
fn session_state_keeps_unsaved_untitled_and_unreadable_buffers() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("gone.txt");
std::fs::write(&file, "saved\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.lines = vec![String::from("scratch notes")];
app.editor.dirty = true;
app.editor.open_pinned(&file).unwrap();
app.editor.lines = vec![String::from("edited gone")];
app.editor.dirty = true;
let state = app.capture_session_state();
assert_eq!(state.tabs.len(), 2);
std::fs::remove_file(&file).unwrap();
let mut restored = App::new(tmp.path().to_path_buf()).unwrap();
restored.apply_session_state(&state);
let eds = &restored.editor.editors;
let untitled = eds.iter().find(|e| e.path.is_none()).unwrap();
assert!(untitled.dirty);
assert_eq!(untitled.lines, vec![String::from("scratch notes")]);
let gone = eds
.iter()
.find(|e| e.path.as_deref() == Some(file.as_path()))
.unwrap();
assert!(gone.dirty);
assert_eq!(gone.lines, vec![String::from("edited gone")]);
assert_eq!(eds.len(), 2, "the blank initial tab is reused");
// A blank untitled buffer is not carried.
let blank = App::new(tmp.path().to_path_buf()).unwrap();
assert!(blank.capture_session_state().tabs.is_empty());
}
#[test]
fn build_tab_context_menu_items_includes_all_four_close_actions_in_the_middle_of_a_strip() {
// Right-click on tab 1 of 3 (i.e. a middle tab) should surface
// every close action — there's at least one tab on each side.
let items = build_tab_context_menu_items(1, 3, false, None, false, false, false);
assert_eq!(
menu_labels(&items),
[
"Close",
"Close Others",
"Close to the Right",
"Close Saved",
"Close All",
"Pin",
"Split Right",
"Split & Move",
"Move into New Window",
],
"all close actions must appear and in this order — mirrors VS Code's tab strip"
);
assert!(matches!(
menu_action_of(&items, "Close"),
Some(MenuAction::CloseTab(1))
));
assert!(matches!(
menu_action_of(&items, "Close Others"),
Some(MenuAction::CloseOtherTabs(1))
));
assert!(matches!(
menu_action_of(&items, "Close to the Right"),
Some(MenuAction::CloseTabsToRight(1))
));
assert!(matches!(
menu_action_of(&items, "Close Saved"),
Some(MenuAction::CloseSavedTabs)
));
assert!(matches!(
menu_action_of(&items, "Close All"),
Some(MenuAction::CloseAllTabs)
));
}
#[test]
fn build_tab_context_menu_items_hides_close_to_the_right_on_the_last_tab() {
// Last tab → "Close to the Right" would close zero tabs, so it
// must be suppressed (matches VS Code).
let items = build_tab_context_menu_items(2, 3, false, None, false, false, false);
assert_eq!(
menu_labels(&items),
[
"Close",
"Close Others",
"Close Saved",
"Close All",
"Pin",
"Split Right",
"Split & Move",
"Move into New Window",
],
"Close to the Right must be suppressed on the rightmost tab"
);
}
#[test]
fn build_tab_context_menu_items_hides_close_others_when_only_one_tab_is_open() {
let items = build_tab_context_menu_items(0, 1, false, None, false, false, false);
assert_eq!(
menu_labels(&items),
[
"Close",
"Close All",
"Pin",
"Split Right",
"Split & Move",
"Move into New Window",
],
"with a single tab, Close Others / Close to the Right / Close Saved are all no-ops and must be suppressed"
);
}
#[test]
fn build_tab_context_menu_items_includes_reveal_in_finder_only_with_a_path_and_enabled() {
let p = std::path::Path::new("/tmp/demo.rs");
// Local macOS with a real path: Reveal in Finder sits after Close All,
// before the split group — mirroring VS Code's lower-middle slot.
let items = build_tab_context_menu_items(0, 1, false, Some(p), true, false, false);
assert_eq!(
menu_labels(&items),
[
"Close",
"Close All",
"Copy Path",
"Copy Relative Path",
"Reveal in Finder",
"Reveal in Explorer View",
"Pin",
"Split Right",
"Split & Move",
"Move into New Window",
"Copy into New Window",
],
);
assert!(matches!(
menu_action_of(&items, "Reveal in Finder"),
Some(MenuAction::RevealInFinder(rp)) if rp == p
));
// Remote (or non-macOS) session: entry withheld even with a path.
let remote = build_tab_context_menu_items(0, 1, false, Some(p), false, false, false);
assert!(!menu_labels(&remote).contains(&"Reveal in Finder"));
// A blank/untitled buffer (no path) never offers it, even when enabled.
let blank = build_tab_context_menu_items(0, 1, false, None, true, false, false);
assert!(!menu_labels(&blank).contains(&"Reveal in Finder"));
}
#[test]
fn build_tab_context_menu_items_offers_reveal_in_explorer_for_any_path() {
let p = std::path::Path::new("/tmp/demo.rs");
// Reveal in Explorer View targets croft's own tree, present local and
// remote, so it shows for any path-bearing tab even when Finder is withheld.
let remote = build_tab_context_menu_items(0, 1, false, Some(p), false, false, false);
assert_eq!(
menu_labels(&remote),
[
"Close",
"Close All",
"Copy Path",
"Copy Relative Path",
"Reveal in Explorer View",
"Pin",
"Split Right",
"Split & Move",
"Move into New Window",
"Copy into New Window",
]
);
assert!(matches!(
menu_action_of(&remote, "Reveal in Explorer View"),
Some(MenuAction::RevealInExplorer(rp)) if rp == p
));
// A blank/untitled buffer (no path) has nothing to reveal.
let blank = build_tab_context_menu_items(0, 1, false, None, true, false, false);
assert!(!menu_labels(&blank).contains(&"Reveal in Explorer View"));
}
#[test]
fn build_tab_context_menu_items_offers_copy_path_for_any_path_local_or_remote() {
let p = std::path::Path::new("/tmp/demo.rs");
// Copy Path is a clipboard write, so it shows for a path-bearing tab even
// on a remote session where Reveal in Finder is withheld.
let remote = build_tab_context_menu_items(0, 1, false, Some(p), false, false, false);
assert_eq!(
menu_labels(&remote),
[
"Close",
"Close All",
"Copy Path",
"Copy Relative Path",
"Reveal in Explorer View",
"Pin",
"Split Right",
"Split & Move",
"Move into New Window",
"Copy into New Window",
]
);
assert!(matches!(
menu_action_of(&remote, "Copy Path"),
Some(MenuAction::CopyTabPath(cp)) if cp == p
));
assert!(matches!(
menu_action_of(&remote, "Copy Relative Path"),
Some(MenuAction::CopyTabRelativePath(cp)) if cp == p
));
// A blank/untitled buffer (no path) has nothing to copy.
let blank = build_tab_context_menu_items(0, 1, false, None, true, false, false);
assert!(!menu_labels(&blank).contains(&"Copy Path"));
assert!(!menu_labels(&blank).contains(&"Copy Relative Path"));
}
#[test]
fn build_tab_context_menu_items_offers_keep_open_only_for_a_preview_tab() {
let p = std::path::Path::new("/tmp/demo.rs");
// Preview tab (italic): "Keep Open" appears, carrying this tab's index, and
// sits just before the Pin / split group.
let preview = build_tab_context_menu_items(0, 1, false, Some(p), false, true, false);
assert!(matches!(
menu_action_of(&preview, "Keep Open"),
Some(MenuAction::KeepTabOpen(0))
));
let labels = menu_labels(&preview);
assert!(
labels.iter().position(|&s| s == "Keep Open") < labels.iter().position(|&s| s == "Pin")
);
// A permanent (non-preview) tab never offers it.
let permanent = build_tab_context_menu_items(0, 1, false, Some(p), false, false, false);
assert!(!menu_labels(&permanent).contains(&"Keep Open"));
}
#[test]
fn build_tab_context_menu_items_offers_pin_or_unpin_carrying_the_tab_index() {
let p = std::path::Path::new("/tmp/demo.rs");
// Unpinned tab reads "Pin"; pinned tab reads "Unpin". Either way the entry
// carries this tab's index and sits between Keep Open and the split group.
let unpinned = build_tab_context_menu_items(0, 1, false, Some(p), true, false, false);
assert!(matches!(
menu_action_of(&unpinned, "Pin"),
Some(MenuAction::ToggleTabPin(0))
));
let labels = menu_labels(&unpinned);
assert!(!labels.contains(&"Unpin"));
let keep = labels.iter().position(|&s| s == "Keep Open");
let pin_pos = labels.iter().position(|&s| s == "Pin");
let split = labels.iter().position(|&s| s == "Split Right");
assert!(keep < pin_pos && pin_pos < split);
let pinned = build_tab_context_menu_items(0, 1, false, Some(p), false, false, true);
assert!(matches!(
menu_action_of(&pinned, "Unpin"),
Some(MenuAction::ToggleTabPin(0))
));
assert!(!menu_labels(&pinned).contains(&"Pin"));
}
#[test]
fn tab_menu_groups_split_and_move_into_a_submenu() {
let items = build_tab_context_menu_items(0, 1, false, None, false, false, false);
// A flat top-level "Split Right" plus a "Split & Move" submenu.
assert!(items.iter().any(|e| matches!(
e,
MenuEntry::Item { label, action: MenuAction::SplitEditor } if label == "Split Right"
)));
let sub = items
.iter()
.find_map(|e| match e {
MenuEntry::Submenu { label, items } if label == "Split & Move" => Some(items),
_ => None,
})
.expect("a Split & Move submenu");
let labels: Vec<&str> = sub
.iter()
.map(|e| match e {
MenuEntry::Item { label, .. } => label.as_str(),
MenuEntry::Submenu { label, .. } => label.as_str(),
MenuEntry::Header(label) => label.as_str(),
MenuEntry::Separator => "---",
})
.collect();
assert_eq!(
labels,
[
"Split Up",
"Split Down",
"Split Left",
"Split Right",
"---",
"Move Above",
"Move Below",
"Move Left",
"Move Right",
"---",
"Split in Group",
]
);
// VS Code's vertical labels: Above = Up, Below = Down.
assert!(matches!(
&sub[5],
MenuEntry::Item {
action: MenuAction::MoveEditorUp,
..
}
));
assert!(matches!(
&sub[6],
MenuEntry::Item {
action: MenuAction::MoveEditorDown,
..
}
));
}
/// Open the editor tab menu into `app.context_menu` with the cursor on the
/// "Split & Move" submenu parent.
fn open_tab_menu_on_split_and_move(app: &mut App) {
let items = build_tab_context_menu_items(0, 1, false, None, false, false, false);
let sub_idx = items
.iter()
.position(|e| menu_label(e) == "Split & Move")
.unwrap();
app.context_menu = Some(ContextMenu {
origin: (0, 0),
items,
selected: sub_idx,
open_submenu: None,
submenu_selected: 0,
target_dir: std::path::PathBuf::from("/"),
});
}
#[test]
fn split_and_move_submenu_opens_and_down_skips_the_divider() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
open_tab_menu_on_split_and_move(&mut app);
// Right opens the submenu, selecting its first child (Split Up).
app.handle_menu_key(key(KeyCode::Right, KeyModifiers::NONE));
{
let m = app.context_menu.as_ref().unwrap();
assert!(m.open_submenu.is_some(), "Right opened the submenu");
assert_eq!(menu_label(m.cursor_entry().unwrap()), "Split Up");
}
// Down three times reaches "Split Right" (the last split before the
// divider); one more Down SKIPS the divider onto "Move Above".
for _ in 0..3 {
app.handle_menu_key(key(KeyCode::Down, KeyModifiers::NONE));
}
assert_eq!(
menu_label(app.context_menu.as_ref().unwrap().cursor_entry().unwrap()),
"Split Right"
);
app.handle_menu_key(key(KeyCode::Down, KeyModifiers::NONE));
assert_eq!(
menu_label(app.context_menu.as_ref().unwrap().cursor_entry().unwrap()),
"Move Above",
"Down must step over the divider, never land on it"
);
// Enter on a child dispatches its action and closes the whole menu.
app.handle_menu_key(key(KeyCode::Enter, KeyModifiers::NONE));
assert!(
app.context_menu.is_none(),
"Enter on a child closes the menu"
);
}
#[test]
fn split_and_move_submenu_left_and_esc_back_out_before_dismissing() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
open_tab_menu_on_split_and_move(&mut app);
app.handle_menu_key(key(KeyCode::Right, KeyModifiers::NONE));
// Left closes the submenu but keeps the menu open at the top level.
app.handle_menu_key(key(KeyCode::Left, KeyModifiers::NONE));
assert!(app.context_menu.as_ref().unwrap().open_submenu.is_none());
assert!(app.context_menu.is_some());
// Re-open; Esc backs out of the submenu first...
app.handle_menu_key(key(KeyCode::Right, KeyModifiers::NONE));
app.handle_menu_key(key(KeyCode::Esc, KeyModifiers::NONE));
assert!(app.context_menu.as_ref().unwrap().open_submenu.is_none());
assert!(
app.context_menu.is_some(),
"first Esc only closes the submenu"
);
// ...and a second Esc dismisses the whole menu.
app.handle_menu_key(key(KeyCode::Esc, KeyModifiers::NONE));
assert!(app.context_menu.is_none(), "second Esc dismisses the menu");
}
#[test]
fn copy_path_key_is_opt_cmd_c_and_disjoint_from_copy_and_relative_path() {
// Cmd+Opt+C (and Ctrl+Opt+C) copy the absolute path.
assert!(is_copy_path_key(key(
KeyCode::Char('c'),
KeyModifiers::SUPER | KeyModifiers::ALT
)));
assert!(is_copy_path_key(key(
KeyCode::Char('c'),
KeyModifiers::CONTROL | KeyModifiers::ALT
)));
// Plain Cmd+C is Copy-selection, not Copy Path.
assert!(!is_copy_path_key(key(
KeyCode::Char('c'),
KeyModifiers::SUPER
)));
// Cmd+Opt+Shift+C is Copy Relative Path: the Shift variant must route there,
// not collide with the absolute Copy Path.
let shift_variant = key(
KeyCode::Char('c'),
KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
);
assert!(!is_copy_path_key(shift_variant));
assert!(is_copy_relative_path_key(shift_variant));
// ...and Copy Relative Path must NOT fire on the no-Shift Copy Path chord.
assert!(!is_copy_relative_path_key(key(
KeyCode::Char('c'),
KeyModifiers::SUPER | KeyModifiers::ALT
)));
}
#[test]
fn cmd_k_enter_reaches_run_test_at_cursor_not_keep_open() {
// Cmd+K Enter is DOCUMENTED as run-test-at-cursor, but an undocumented
// earlier Keep Open arm shadowed it from the day it shipped. The chord
// must reach the Testing handler; Keep Open lives on the tab menu only.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f = tmp.path().join("a.rs");
std::fs::write(&f, "x").unwrap();
app.editor.open_preview(&f).unwrap();
let idx = app.editor.active_index();
assert!(app.editor.is_preview(idx), "opened as a preview tab");
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
assert!(app.cmd_k_leader.is_some(), "Cmd+K arms the chord leader");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.status, "Run Test at Cursor: no function at the caret",
"the chord must land in the Testing handler"
);
assert!(
app.editor.is_preview(app.editor.active_index()),
"Keep Open no longer owns the chord, so the preview stays a preview"
);
}
#[test]
fn cmd_k_shift_p_keeps_the_preview_tab_open_and_the_menu_says_so() {
// Keep Open lost its Cmd+K Enter chord to run-test-at-cursor, but the
// tab menu kept advertising "⌘K ⏎" — a hint that now starts a test run.
// The action lives on Cmd+K ⇧P (sibling of Cmd+K P pin), and the menu
// label must say exactly that.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f = tmp.path().join("a.rs");
std::fs::write(&f, "x").unwrap();
app.editor.open_preview(&f).unwrap();
let idx = app.editor.active_index();
assert!(app.editor.is_preview(idx), "opened as a preview tab");
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('P'), KeyModifiers::SHIFT))
.unwrap();
assert!(
!app.editor.is_preview(app.editor.active_index()),
"Cmd+K Shift+P promotes the preview to a kept-open tab"
);
assert_eq!(app.status, "Kept tab open");
assert_eq!(
shortcut_for(&MenuAction::KeepTabOpen(0)),
Some("⌘K ⇧P"),
"the tab menu must advertise the chord that actually works"
);
}
#[test]
fn debug_a_cargo_test_builds_off_the_ui_thread() {
// A cold `cargo test --no-run` takes minutes; running it on the UI
// thread froze the whole TUI (no keys, no redraw, no PTY pumping, no
// cancel) and the "Building…" status could never even paint before the
// launch overwrote it. The request must return immediately and the
// result arrive through the tick drain.
let tmp = tempfile::tempdir().unwrap();
// A Cargo project cargo rejects instantly (no src/), so the background
// build fails fast and deterministically.
std::fs::write(
tmp.path().join("Cargo.toml"),
"[package]\nname = \"x\"\nversion = \"0.0.0\"\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.start_test_binary_build(tmp.path().to_path_buf(), String::from("my_case"), None);
assert_eq!(
app.status, "Building test binary for my_case",
"the request returns with the progress status showing"
);
// A second request while one is pending is refused, not stacked.
app.start_test_binary_build(tmp.path().to_path_buf(), String::from("other"), None);
assert_eq!(app.status, "A test binary is already building");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
while !app.drain_pending_test_debug() {
assert!(
std::time::Instant::now() < deadline,
"the build result never arrived through the drain"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert!(
app.status.starts_with("Test build failed"),
"a broken crate surfaces the build error, got: {}",
app.status
);
assert!(
app.pending_test_debug.is_none(),
"the pending slot frees for the next request"
);
}
#[test]
fn a_test_binary_that_finishes_after_a_workspace_change_is_discarded() {
// Re-rooting the Explorer while `cargo test --no-run` runs used to make
// the drain launch the OLD workspace's binary with the NEW workspace's
// cwd and breakpoint context. A finished build whose originating root no
// longer matches the current workspace must be dropped, not launched.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let (tx, rx) = std::sync::mpsc::channel();
app.pending_test_debug = Some((
rx,
String::from("my_case"),
std::path::PathBuf::from("/somewhere/else"),
));
tx.send(Ok(std::path::PathBuf::from(
"/somewhere/else/target/debug/deps/x-abc123",
)))
.unwrap();
assert!(
app.drain_pending_test_debug(),
"the drain consumed the result"
);
assert!(
app.debug_sessions.is_empty(),
"no debugger may launch for a foreign workspace's binary"
);
assert!(
app.status.contains("workspace changed"),
"status explains the discarded build, got: {}",
app.status
);
assert!(
app.pending_test_debug.is_none(),
"the pending slot frees for the next request"
);
}
#[test]
fn cmd_k_p_pins_then_unpins_the_active_tab() {
// Pin moved to Cmd+K P: its old Shift+Enter chord now debugs the test
// at the caret.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f = tmp.path().join("a.rs");
std::fs::write(&f, "x").unwrap();
app.editor.open_pinned(&f).unwrap();
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::NONE))
.unwrap();
assert!(
app.editor.is_pinned(app.editor.active_index()),
"Cmd+K P pins the active tab"
);
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::NONE))
.unwrap();
assert!(
!app.editor.is_pinned(app.editor.active_index()),
"a second Cmd+K P unpins it"
);
}
#[test]
fn relative_clipboard_text_is_relative_inside_root_and_absolute_outside() {
use std::path::Path;
// Inside the workspace root: drop the root prefix.
assert_eq!(
relative_clipboard_text(Path::new("/ws/src/a.rs"), Path::new("/ws")),
"src/a.rs"
);
// Outside the root: fall back to the absolute path, never a `../` walk.
assert_eq!(
relative_clipboard_text(Path::new("/other/a.rs"), Path::new("/ws")),
"/other/a.rs"
);
// The root itself relativizes to empty.
assert_eq!(
relative_clipboard_text(Path::new("/ws"), Path::new("/ws")),
""
);
}
#[test]
fn zoxide_jump_key_is_cmd_z_only_and_never_ctrl_z_or_redo() {
// Cmd+Z (SUPER) opens the Explorer jump popup. Ctrl+Z must NOT — it
// is the shell suspend in the terminal, and the editor's undo lives on
// Ctrl/Cmd+Z in its own (editor-focused) path. Cmd+Shift+Z is the
// reserved redo chord. Cmd+J stays free for terminal manipulation.
assert!(is_tree_zoxide_jump_key(key(
KeyCode::Char('z'),
KeyModifiers::SUPER
)));
assert!(
is_tree_zoxide_jump_key(key(KeyCode::Char('Z'), KeyModifiers::SUPER)),
"letter match must be case-insensitive"
);
assert!(
!is_tree_zoxide_jump_key(key(KeyCode::Char('z'), KeyModifiers::CONTROL)),
"Ctrl+Z must not open the popup; it is shell suspend / editor undo"
);
assert!(
!is_tree_zoxide_jump_key(key(
KeyCode::Char('z'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)),
"Cmd+Shift+Z is reserved for redo and must not open the popup"
);
assert!(
!is_tree_zoxide_jump_key(key(KeyCode::Char('j'), KeyModifiers::SUPER)),
"Cmd+J must stay free for terminal manipulation"
);
}
#[test]
fn zoxide_jump_popup_anchors_over_the_explorer_column_not_centered() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.handle_explorer_shortcut(key(KeyCode::Char('z'), KeyModifiers::SUPER));
assert!(app.zoxide_jump.is_some(), "precondition: popup is open");
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let popup = app.zoxide_jump.as_ref().unwrap().last_rect;
// The Explorer tree renders inside the sidebar column; the popup must
// share that column's left edge (anchored over the Explorer), not be
// centered on the 120-wide frame (which would put x near ~30).
assert_eq!(
popup.x, app.tree.last_area.x,
"jump popup must be left-anchored to the Explorer column, got x={} vs sidebar x={}",
popup.x, app.tree.last_area.x
);
assert!(
popup.y <= app.tree.last_area.y,
"jump popup must drop from the top of the Explorer, not be vertically centered"
);
}
#[test]
fn a_zoxide_row_re_roots_under_the_same_key_as_the_add_branch() {
// A zoxide row is a bare line from its database, so it can name a
// directory in a spelling nothing else in croft uses (a symlinked
// `/var/…` for `/private/var/…`). Both branches of the jump must land on
// the same spelling: the folder store keys on
// `roots.primary().display()`, so two spellings of one directory would
// file and restore under different keys.
let tmp = tempfile::tempdir().unwrap();
let real = tmp.path().canonicalize().unwrap().join("real");
std::fs::create_dir(&real).unwrap();
let link = tmp.path().canonicalize().unwrap().join("link");
std::os::unix::fs::symlink(&real, &link).unwrap();
// Jump mode: re-root onto the symlinked spelling.
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mut jump = crate::widgets::zoxide_jump::ZoxideJump::new();
jump.set_results(Some(vec![link.clone()]));
app.zoxide_jump = Some(jump);
app.zoxide_add_folder = false;
app.apply_zoxide_jump_selection();
let jumped = app.roots.primary().to_path_buf();
// Add mode: the same row through the other branch.
let mut app2 = App::new(tmp.path().to_path_buf()).unwrap();
let mut jump2 = crate::widgets::zoxide_jump::ZoxideJump::new();
jump2.set_results(Some(vec![link.clone()]));
app2.zoxide_jump = Some(jump2);
app2.zoxide_add_folder = true;
app2.apply_zoxide_jump_selection();
let added = app2
.roots
.iter()
.find(|r| r.ends_with("real") || r.ends_with("link"))
.expect("the folder was added")
.to_path_buf();
assert_eq!(
jumped, added,
"both branches of one gesture must store the same spelling"
);
assert_eq!(
jumped,
link.canonicalize().unwrap(),
"and it is the canonical one, so the folder store keys agree"
);
}
#[test]
fn cmd_z_in_explorer_opens_the_zoxide_jump_popup() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(
app.is_explorer_focused(),
"precondition: a fresh app is focused on the Explorer pane"
);
assert!(app.zoxide_jump.is_none(), "popup starts closed");
let handled = app.handle_explorer_shortcut(key(KeyCode::Char('z'), KeyModifiers::SUPER));
assert!(
handled,
"Cmd+Z must be consumed by the Explorer shortcut layer"
);
assert!(
app.zoxide_jump.is_some(),
"Cmd+Z in the Explorer must open the zoxide jump popup"
);
// Esc closes it again.
app.handle_zoxide_jump_key(key(KeyCode::Esc, KeyModifiers::NONE));
assert!(app.zoxide_jump.is_none(), "Esc must close the jump popup");
}
// --- Native modal (vim) editing -------------------------------------------
fn vim_app(content: &str) -> (App, tempfile::TempDir) {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("buf.txt");
std::fs::write(&f, content).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.focus = Pane::Editor;
app.vim.enabled = true;
(app, tmp)
}
fn vim_feed(app: &mut App, c: char) {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
fn vim_feed_str(app: &mut App, s: &str) {
for c in s.chars() {
vim_feed(app, c);
}
}
#[test]
fn a_replayed_key_cannot_start_a_recording() {
// The re-entrancy flag gates CAPTURE, not dispatch, so a replayed `q`
// used to reach the vim handler and leave the user silently recording
// after the replay returned — every later keystroke captured with no
// gesture having asked for it.
let (mut app, tmp) = vim_app("one\ntwo\n");
app.macros_path = tmp.path().join("macros.json");
// A register whose contents are themselves a recording gesture.
let mut hostile = crate::macros::Macro::default();
hostile.push_key(key(KeyCode::Char('q'), KeyModifiers::NONE));
hostile.push_key(key(KeyCode::Char('c'), KeyModifiers::NONE));
app.macro_registers.insert("b".into(), hostile);
vim_feed_str(&mut app, "@b");
assert!(
app.macro_recording.is_none(),
"replaying a recording gesture must not leave the editor recording"
);
}
#[test]
fn the_palette_and_vim_recorders_are_one_recording_not_two() {
// vim used to mirror the recording flag, so a palette Stop left `q`
// believing it was still recording: the next `q` re-saved the stale
// register and swallowed the key after it as a register name.
let (mut app, tmp) = vim_app("one\ntwo\n");
app.macros_path = tmp.path().join("macros.json");
// vim starts, palette stops.
vim_feed_str(&mut app, "qa");
assert!(app.macro_recording.is_some());
app.run_command(crate::widgets::command_palette::Command::MacroStartStopRecording);
assert!(app.macro_recording.is_none(), "the palette stopped it");
// A following `q` must START a fresh recording, not stop a phantom one.
vim_feed_str(&mut app, "qb");
assert_eq!(
app.macro_recording.as_ref().map(|r| r.register),
Some(Some('b')),
"vim sees the real state and opens register b"
);
// And the other direction: palette starts, a bare vim `q` stops.
app.run_command(crate::widgets::command_palette::Command::MacroStartStopRecording);
app.run_command(crate::widgets::command_palette::Command::MacroStartStopRecording);
assert!(app.macro_recording.is_some(), "palette started one");
vim_feed(&mut app, 'q');
assert!(
app.macro_recording.is_none(),
"a bare q stops what the palette started"
);
}
#[test]
fn saving_one_register_preserves_every_field_of_a_newer_crofts_steps() {
// `update_json_store` re-serialises the ENTIRE map on every save, so a
// fieldless catch-all would rewrite a newer croft's steps as
// `{"kind":"Unknown"}` the first time any unrelated register was
// stored — silently destroying them. Worse than refusing to save,
// because it is unrecoverable.
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("macros.json");
std::fs::write(
&path,
r#"{"b":{"steps":[{"kind":"Mouse","button":"left","x":3}]}}"#,
)
.unwrap();
let mut mine = crate::macros::Macro::default();
mine.push_key(key(KeyCode::Char('z'), KeyModifiers::NONE));
crate::macros::save_register(&path, "c", mine).unwrap();
let raw = std::fs::read_to_string(&path).unwrap();
assert!(
raw.contains("\"button\"") && raw.contains("\"left\""),
"the future step's own fields survive an unrelated save: {raw}"
);
assert!(
raw.contains("\"x\""),
"including every field, not just the tag: {raw}"
);
}
#[test]
fn a_replayed_keybinding_cannot_open_the_count_prompt() {
// `macro_replay_times` is a bindable id, so a replayed chord reaches it
// through keymap -> run_command. A prompt opening mid-replay swallows
// the macro's remaining keys into the count field, and `input_prompt`
// is checked ABOVE the macro tap, so a later Enter would submit the
// count and re-enter replay.
let (mut app, tmp) = vim_app("one\n");
app.macros_path = tmp.path().join("macros.json");
let mut m = crate::macros::Macro::default();
m.push_key(key(KeyCode::Char('x'), KeyModifiers::NONE));
app.macro_last = Some(m);
app.macro_replaying = true;
app.run_command(crate::widgets::command_palette::Command::MacroReplayTimes);
assert!(
app.input_prompt.is_none(),
"the count prompt must not open while a macro is replaying"
);
app.macro_replaying = false;
app.run_command(crate::widgets::command_palette::Command::MacroReplayTimes);
assert!(
app.input_prompt.is_some(),
"but it opens normally when nothing is replaying"
);
}
#[test]
fn a_macro_of_only_unknown_steps_reports_that_it_ran_nothing() {
// `is_empty()` tests the step list; a macro whose steps are all
// unreplayable is not empty but yields no keys, and reporting
// "Macro replayed" would tell the user a newer croft's macro ran.
let (mut app, tmp) = vim_app("one\n");
app.macros_path = tmp.path().join("macros.json");
let path = app.macros_path.clone();
std::fs::write(
&path,
r#"{"u":{"steps":[{"kind":"Mouse","button":"left"}]}}"#,
)
.unwrap();
app.macro_registers = crate::macros::load(&path);
vim_feed_str(&mut app, "@u");
assert!(
app.status.contains("no steps this version can replay"),
"an all-unknown macro says so, got {:?}",
app.status
);
assert_eq!(app.editor.lines[0], "one", "and nothing ran");
}
#[test]
fn an_unknown_step_kind_does_not_brick_the_whole_store() {
// A macros.json written by a newer croft must lose the step it names,
// not every register in the file — serde's tagged enums fail the WHOLE
// parse on an unknown tag without a catch-all, which would also block
// every future save (the store refuses to overwrite what it cannot read).
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("macros.json");
std::fs::write(
&path,
r#"{"a":{"steps":[{"kind":"Text","text":"hi"}]},
"b":{"steps":[{"kind":"Mouse","button":"left"}]}}"#,
)
.unwrap();
let loaded = crate::macros::load(&path);
assert!(
loaded.contains_key("a"),
"the readable register survives: {loaded:?}"
);
assert_eq!(
loaded.get("a").map(|m| m.len()),
Some(2),
"and still replays its own keys"
);
// The unknown step is inert rather than fatal.
assert_eq!(
loaded.get("b").map(|m| m.key_events().len()),
Some(0),
"an unknown step kind replays as nothing"
);
// Saves still work, so the store is not permanently locked.
assert!(
crate::macros::save_register(&path, "c", loaded.get("a").cloned().unwrap()).is_ok(),
"an unknown kind elsewhere in the file must not block writes"
);
}
#[test]
fn a_replay_aborts_visibly_and_keeps_earlier_iterations() {
// The issue requires an abort to leave prior iterations intact. Budget
// refusal is the reachable abort in a test: assert it refuses without
// running anything rather than spinning.
let (mut app, tmp) = vim_app("one\n");
app.macros_path = tmp.path().join("macros.json");
let mut big = crate::macros::Macro::default();
for _ in 0..10 {
big.push_key(key(KeyCode::Char('x'), KeyModifiers::NONE));
}
app.macro_registers.insert("z".into(), big);
let before = app.editor.lines[0].clone();
vim_feed_str(&mut app, "99999@z");
assert!(
app.status.contains("refused"),
"a replay past the budget is refused visibly, got {:?}",
app.status
);
assert_eq!(
app.editor.lines[0], before,
"and nothing ran, rather than half of it"
);
}
#[test]
fn a_count_before_a_closing_q_is_discarded_too() {
// The stop gesture takes the `'q'` arm rather than the register branch,
// so it needs its own take_count(): `3q` while recording must stop and
// discard the 3, not leave it to retarget the next motion.
let (mut app, tmp) = vim_app("aaaa\nbbbb\ncccc\ndddd\neeee\n");
app.macros_path = tmp.path().join("macros.json");
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
vim_feed_str(&mut app, "qa");
vim_feed_str(&mut app, "3q");
assert!(
app.macro_recording.is_none(),
"3q still stops the recording"
);
vim_feed(&mut app, 'j');
assert_eq!(
app.editor.cursor_row, 1,
"the discarded 3 must not make the next j move three rows"
);
}
#[test]
fn a_non_register_key_after_q_aborts_the_gesture() {
// The per-character handlers only see plain chars, so an arrow key after
// `q` used to return at the motion arms with `pending_record` still set —
// and the next letter typed would silently start a recording nobody
// asked for. Vim aborts the gesture on a non-register key.
let (mut app, tmp) = vim_app("one\ntwo\nthree\n");
app.macros_path = tmp.path().join("macros.json");
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
vim_feed(&mut app, 'q');
app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
.unwrap();
assert!(
app.macro_recording.is_none(),
"the arrow key aborts the pending register gesture"
);
// The following letter must be an ordinary motion, not a register name.
vim_feed(&mut app, 'j');
assert!(
app.macro_recording.is_none(),
"and does not retroactively start a recording"
);
}
#[test]
fn a_count_before_q_does_not_leak_into_the_recording() {
// Vim discards a count on `q`. Keeping it would silently retarget the
// recording's FIRST key — `3qa` then `j` moves three rows instead of one,
// and the wrong motion is what gets captured. A pending count is
// invisible, so the corruption only surfaces at replay.
let (mut app, tmp) = vim_app("aaaa\nbbbb\ncccc\ndddd\neeee\n");
app.macros_path = tmp.path().join("macros.json");
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
vim_feed_str(&mut app, "3qa");
vim_feed(&mut app, 'j');
assert_eq!(
app.editor.cursor_row, 1,
"the stale 3 must not make the recording's first j move three rows"
);
}
#[test]
fn vim_q_records_into_a_register_and_at_replays_it() {
// #255: `qa … q` records, `@a` replays, and the register survives as the
// "last macro" so `@@` repeats it.
let (mut app, tmp) = vim_app("one\ntwo\nthree\n");
app.macros_path = tmp.path().join("macros.json");
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
vim_feed_str(&mut app, "qa");
assert!(
app.macro_recording.is_some(),
"qa starts recording into a register"
);
assert_eq!(
app.macro_recording.as_ref().unwrap().register,
Some('a'),
"and remembers which one, for the status badge"
);
// Record "insert X at the line start, then go down a line".
vim_feed_str(&mut app, "IX");
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
vim_feed(&mut app, 'j');
vim_feed(&mut app, 'q');
assert!(app.macro_recording.is_none(), "the closing q stops");
assert_eq!(app.editor.lines[0], "Xone", "the recorded keys still ran");
// Replay once on line two.
vim_feed_str(&mut app, "@a");
assert_eq!(app.editor.lines[1], "Xtwo", "@a replays the register");
// `@@` repeats the same macro.
vim_feed_str(&mut app, "@@");
assert_eq!(app.editor.lines[2], "Xthree", "@@ repeats the last macro");
}
#[test]
fn vim_a_count_replays_the_macro_that_many_times() {
// `3@a` runs it three times, and a count before `@` is not swallowed by
// the register letter.
let (mut app, tmp) = vim_app("a\nb\nc\nd\n");
app.macros_path = tmp.path().join("macros.json");
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
vim_feed_str(&mut app, "qz");
vim_feed_str(&mut app, "IX");
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
vim_feed(&mut app, 'j');
vim_feed(&mut app, 'q');
vim_feed_str(&mut app, "3@z");
assert_eq!(
(
app.editor.lines[1].as_str(),
app.editor.lines[2].as_str(),
app.editor.lines[3].as_str()
),
("Xb", "Xc", "Xd"),
"3@z ran the macro three times"
);
}
#[test]
fn a_replayed_key_is_never_recorded_into_the_macro_producing_it() {
// Replay feeds keys back through handle_key, so without the re-entrancy
// guard a macro would grow while replaying and never terminate.
let (mut app, tmp) = vim_app("one\ntwo\n");
app.macros_path = tmp.path().join("macros.json");
vim_feed_str(&mut app, "qa");
vim_feed_str(&mut app, "IX");
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
vim_feed(&mut app, 'q');
let recorded_len = app.macro_registers.get("a").unwrap().len();
vim_feed_str(&mut app, "@a");
assert_eq!(
app.macro_registers.get("a").unwrap().len(),
recorded_len,
"replaying must not append to the register it is replaying"
);
}
#[test]
fn an_empty_recording_is_discarded_rather_than_clobbering_a_good_macro() {
let (mut app, tmp) = vim_app("x\n");
app.macros_path = tmp.path().join("macros.json");
vim_feed_str(&mut app, "qa");
vim_feed_str(&mut app, "IZ");
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
vim_feed(&mut app, 'q');
let good = app.macro_registers.get("a").cloned().unwrap();
// Start and immediately stop: nothing recorded.
vim_feed_str(&mut app, "qa");
vim_feed(&mut app, 'q');
assert_eq!(
app.macro_registers.get("a"),
Some(&good),
"an empty recording must not replace a useful register"
);
}
#[test]
fn a_macro_recorded_in_vim_mode_replays_from_the_palette() {
// The registers and the palette's "last macro" are one store, so the two
// entry points are interchangeable — the issue calls this out explicitly.
let (mut app, tmp) = vim_app("one\ntwo\n");
app.macros_path = tmp.path().join("macros.json");
vim_feed_str(&mut app, "qa");
vim_feed_str(&mut app, "IX");
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
vim_feed(&mut app, 'j');
vim_feed(&mut app, 'q');
app.run_command(crate::widgets::command_palette::Command::MacroReplayLast);
assert_eq!(
app.editor.lines[1], "Xtwo",
"the palette replays what vim recorded"
);
}
#[test]
fn a_register_survives_a_restart_through_macros_json() {
let (mut app, tmp) = vim_app("one\n");
let path = tmp.path().join("macros.json");
app.macros_path = path.clone();
vim_feed_str(&mut app, "qa");
vim_feed_str(&mut app, "IX");
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
vim_feed(&mut app, 'q');
// A fresh load of the store sees the register, which is what App::new does.
let reloaded = crate::macros::load(&path);
assert_eq!(
reloaded.get("a"),
app.macro_registers.get("a"),
"the register was persisted, not just held in memory"
);
}
#[test]
fn vim_dd_deletes_the_current_line() {
let (mut app, _t) = vim_app("alpha\nbeta\ngamma");
vim_feed_str(&mut app, "dd");
assert_eq!(app.editor.lines, vec!["beta", "gamma"]);
}
#[test]
fn vim_count_dd_deletes_multiple_lines() {
let (mut app, _t) = vim_app("a\nb\nc\nd");
vim_feed_str(&mut app, "2dd");
assert_eq!(app.editor.lines, vec!["c", "d"]);
}
#[test]
fn vim_x_deletes_char_under_cursor() {
let (mut app, _t) = vim_app("hello");
vim_feed(&mut app, 'x');
assert_eq!(app.editor.lines, vec!["ello"]);
}
#[test]
fn vim_dw_deletes_word_and_trailing_space() {
let (mut app, _t) = vim_app("foo bar");
vim_feed_str(&mut app, "dw");
assert_eq!(app.editor.lines, vec!["bar"]);
}
#[test]
fn vim_de_deletes_to_word_end_inclusive() {
let (mut app, _t) = vim_app("foo bar");
vim_feed_str(&mut app, "de");
assert_eq!(app.editor.lines, vec![" bar"]);
}
#[test]
fn vim_diw_deletes_inner_word() {
let (mut app, _t) = vim_app("foo bar baz");
// cursor on "foo"
vim_feed_str(&mut app, "diw");
assert_eq!(app.editor.lines, vec![" bar baz"]);
}
#[test]
fn vim_dollar_then_d_deletes_to_end_of_line() {
let (mut app, _t) = vim_app("hello world");
vim_feed_str(&mut app, "wd$");
assert_eq!(app.editor.lines, vec!["hello "]);
}
#[test]
fn vim_insert_types_text_then_esc_returns_to_normal() {
let (mut app, _t) = vim_app("bc");
vim_feed(&mut app, 'i');
vim_feed(&mut app, 'a');
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines, vec!["abc"]);
assert_eq!(app.vim.mode(), crate::vim::VimMode::Normal);
}
#[test]
fn vim_append_inserts_after_cursor() {
let (mut app, _t) = vim_app("ac");
vim_feed(&mut app, 'a'); // insert after the 'a'
vim_feed(&mut app, 'b');
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines, vec!["abc"]);
}
#[test]
fn vim_open_line_below_enters_insert_on_fresh_line() {
let (mut app, _t) = vim_app("first");
vim_feed(&mut app, 'o');
vim_feed_str(&mut app, "second");
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines, vec!["first", "second"]);
}
#[test]
fn vim_yank_line_then_paste_duplicates_it() {
let (mut app, _t) = vim_app("dup\ntail");
vim_feed_str(&mut app, "yy");
vim_feed(&mut app, 'p');
assert_eq!(app.editor.lines, vec!["dup", "dup", "tail"]);
}
#[test]
fn vim_visual_select_then_delete_removes_selection() {
let (mut app, _t) = vim_app("abcdef");
vim_feed(&mut app, 'v'); // visual at col 0 (covers 'a')
vim_feed(&mut app, 'l'); // extend to 'b'
vim_feed(&mut app, 'l'); // extend to 'c'
vim_feed(&mut app, 'd'); // delete a,b,c inclusive
assert_eq!(app.editor.lines, vec!["def"]);
}
#[test]
fn vim_normal_mode_swallows_plain_letters() {
let (mut app, _t) = vim_app("text");
vim_feed(&mut app, 'z'); // unmapped in Normal: must not be inserted
assert_eq!(app.editor.lines, vec!["text"]);
}
#[test]
fn vim_search_moves_cursor_to_match() {
let (mut app, _t) = vim_app("alpha needle omega");
vim_feed(&mut app, '/');
vim_feed_str(&mut app, "needle");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.cursor_row, 0);
assert_eq!(
app.editor.cursor_col, 6,
"cursor lands on the 'n' of needle"
);
}
#[test]
fn update_spinner_frame_cycles_through_all_frames_and_wraps() {
// Frame 0 at the start, advances one frame per UPDATE_SPINNER_FRAME_MS.
assert_eq!(update_spinner_frame(0), UPDATE_SPINNER_FRAMES[0]);
assert_eq!(
update_spinner_frame(UPDATE_SPINNER_FRAME_MS),
UPDATE_SPINNER_FRAMES[1]
);
assert_eq!(
update_spinner_frame(UPDATE_SPINNER_FRAME_MS * 5 + 50),
UPDATE_SPINNER_FRAMES[5],
"mid-frame elapsed still maps to the floor frame"
);
// Wraps back to frame 0 after a full cycle of all six frames.
let cycle = UPDATE_SPINNER_FRAME_MS * UPDATE_SPINNER_FRAMES.len() as u128;
assert_eq!(update_spinner_frame(cycle), UPDATE_SPINNER_FRAMES[0]);
assert_eq!(
update_spinner_frame(cycle + UPDATE_SPINNER_FRAME_MS),
UPDATE_SPINNER_FRAMES[1]
);
}
#[test]
fn vim_search_records_active_match_and_advances_with_n() {
// Two matches on one line: "x needle y needle z" -> cols 2 and 11.
let (mut app, _t) = vim_app("x needle y needle z");
vim_feed(&mut app, '/');
vim_feed_str(&mut app, "needle");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.active_search_match,
Some((0, 2, 6)),
"the match the cursor jumped to must be recorded as (row, col_chars, len_chars) so the renderer paints it orange while the other 'needle' stays yellow"
);
vim_feed(&mut app, 'n');
assert_eq!(
app.editor.active_search_match,
Some((0, 11, 6)),
"`n` advances the active match to the next occurrence"
);
}
#[test]
fn vim_gg_and_capital_g_jump_between_ends() {
let (mut app, _t) = vim_app("one\ntwo\nthree");
app.handle_key(key(KeyCode::Char('G'), KeyModifiers::SHIFT))
.unwrap();
assert_eq!(app.editor.cursor_row, 2);
vim_feed_str(&mut app, "gg");
assert_eq!(app.editor.cursor_row, 0);
}
#[test]
fn vim_toggle_works_from_any_pane_even_with_no_editor_focus() {
let (mut app, _t) = vim_app("abc");
app.vim.enabled = false;
// Focus the file tree, not the editor.
app.focus = Pane::Tree;
app.handle_key(key(KeyCode::Char('e'), KeyModifiers::SUPER))
.unwrap();
assert!(
app.vim.enabled,
"Cmd+E must toggle vim mode globally, from any pane, so it can be pre-armed before opening or focusing a file"
);
app.handle_key(key(KeyCode::Char('e'), KeyModifiers::SUPER))
.unwrap();
assert!(
!app.vim.enabled,
"a second Cmd+E from the tree toggles it back off"
);
}
#[test]
fn vim_toggle_off_clears_search_highlights() {
let (mut app, _t) = vim_app("x needle y needle z");
vim_feed(&mut app, '/');
vim_feed_str(&mut app, "needle");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(
app.editor.search_highlight.is_some(),
"precondition: a vim search leaves the match-highlight term set"
);
assert!(app.editor.active_search_match.is_some());
// Toggling vim mode off with Cmd+E is the only way to dismiss vim search
// highlights, so it must clear both the highlight term and the active match.
app.handle_key(key(KeyCode::Char('e'), KeyModifiers::SUPER))
.unwrap();
assert!(!app.vim.enabled);
assert!(
app.editor.search_highlight.is_none(),
"toggling vim off must clear the search-match highlight term so no matches stay painted"
);
assert!(
app.editor.active_search_match.is_none(),
"toggling vim off must clear the active-match marker too"
);
}
#[test]
fn vim_toggle_off_restores_plain_typing() {
let (mut app, _t) = vim_app("");
// Cmd+E turns modal editing off.
app.handle_key(key(KeyCode::Char('e'), KeyModifiers::SUPER))
.unwrap();
assert!(!app.vim.enabled);
vim_feed_str(&mut app, "hi");
assert_eq!(app.editor.lines, vec!["hi"]);
}
#[test]
fn vim_toggle_on_with_cmd_e_enables_modal_editing() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("buf.txt");
std::fs::write(&f, "abc").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.focus = Pane::Editor;
// Cmd+E from a plain editor turns modal editing on.
app.handle_key(key(KeyCode::Char('e'), KeyModifiers::SUPER))
.unwrap();
assert!(app.vim.enabled);
assert_eq!(app.vim.mode(), crate::vim::VimMode::Normal);
// A plain letter is now a Normal-mode command, not inserted text.
vim_feed(&mut app, 'x');
assert_eq!(app.editor.lines, vec!["bc"]);
}
#[test]
fn vim_ex_goto_line_number() {
let (mut app, _t) = vim_app("l1\nl2\nl3\nl4");
vim_feed(&mut app, ':');
vim_feed(&mut app, '3');
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.cursor_row, 2);
}
#[test]
fn vim_cmd_save_shortcut_still_works_in_normal_mode() {
// A Cmd-modified key must pass through to the editor's own handling
// rather than being swallowed by Normal mode.
let (mut app, _t) = vim_app("data");
vim_feed(&mut app, 'x'); // edit so the buffer is dirty: "ata"
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(app.editor.lines, vec!["ata"]);
assert!(
!app.editor.dirty,
"Cmd+S should have saved through Normal mode"
);
}
#[test]
fn rename_symbol_key_is_plain_f2_only() {
assert!(is_rename_symbol_key(key(KeyCode::F(2), KeyModifiers::NONE)));
// Modified F2 is Change All Occurrences, not Rename Symbol.
assert!(!is_rename_symbol_key(key(
KeyCode::F(2),
KeyModifiers::SUPER
)));
assert!(!is_rename_symbol_key(key(
KeyCode::F(2),
KeyModifiers::CONTROL
)));
assert!(!is_rename_symbol_key(key(
KeyCode::F(3),
KeyModifiers::NONE
)));
}
#[test]
fn format_document_key_is_cmd_opt_shift_f() {
// VS Code "Format Document" is Shift+Alt+F; croft forwards it as the
// Cmd+Opt+Shift+F chord (modifier byte 12) so it reaches the editor over
// iTerm2's GlobalKeyMap and Ghostty's csi: keybind alike.
assert!(is_format_document_key(key(
KeyCode::Char('F'),
KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT
)));
// Linux / Termux fold the command modifier onto Ctrl.
assert!(is_format_document_key(key(
KeyCode::Char('f'),
KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT
)));
// Any missing modifier, or a different letter, is not the chord.
assert!(!is_format_document_key(key(
KeyCode::Char('F'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
assert!(!is_format_document_key(key(
KeyCode::Char('g'),
KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT
)));
}
#[test]
fn change_all_occurrences_key_accepts_cmd_ctrl_or_alt_f2() {
// macOS Cmd, Linux Ctrl, and iTerm2's Cmd-folded-to-Meta (ALT) all fire.
assert!(is_change_all_occurrences_key(key(
KeyCode::F(2),
KeyModifiers::SUPER
)));
assert!(is_change_all_occurrences_key(key(
KeyCode::F(2),
KeyModifiers::CONTROL
)));
assert!(is_change_all_occurrences_key(key(
KeyCode::F(2),
KeyModifiers::ALT
)));
// Plain F2 stays Rename Symbol.
assert!(!is_change_all_occurrences_key(key(
KeyCode::F(2),
KeyModifiers::NONE
)));
}
#[test]
fn go_to_definition_key_is_f12_without_shift() {
assert!(is_go_to_definition_key(key(
KeyCode::F(12),
KeyModifiers::NONE
)));
// Alt+F12 is Peek Definition now (#115): the fold-noise tolerance the
// plain jump used to extend to a stray ALT bit moved onto the peek,
// which is the strictly less disruptive consumer.
assert!(!is_go_to_definition_key(key(
KeyCode::F(12),
KeyModifiers::ALT
)));
// Shift+F12 is Declaration, Ctrl+F12 is Type Definition, Cmd+F12 (SUPER) is
// Implementations; none of the three is Definition.
assert!(!is_go_to_definition_key(key(
KeyCode::F(12),
KeyModifiers::SHIFT
)));
assert!(!is_go_to_definition_key(key(
KeyCode::F(12),
KeyModifiers::CONTROL
)));
assert!(!is_go_to_definition_key(key(
KeyCode::F(12),
KeyModifiers::SUPER
)));
assert!(!is_go_to_definition_key(key(
KeyCode::F(11),
KeyModifiers::NONE
)));
}
#[test]
fn go_to_references_key_is_shift_f12() {
// VS Code's real binding: Shift+F12 = Go to References.
assert!(is_go_to_references_key(key(
KeyCode::F(12),
KeyModifiers::SHIFT
)));
// Plain F12 is Definition, not References.
assert!(!is_go_to_references_key(key(
KeyCode::F(12),
KeyModifiers::NONE
)));
// Ctrl+Shift+F12 is Declaration, not References; the Ctrl bit must split
// them when both Shift and Ctrl are reported.
assert!(!is_go_to_references_key(key(
KeyCode::F(12),
KeyModifiers::SHIFT | KeyModifiers::CONTROL
)));
// Cmd+F12 is Implementations.
assert!(!is_go_to_references_key(key(
KeyCode::F(12),
KeyModifiers::SHIFT | KeyModifiers::SUPER
)));
assert!(!is_go_to_references_key(key(
KeyCode::F(2),
KeyModifiers::SHIFT
)));
}
#[test]
fn go_to_declaration_key_is_ctrl_shift_f12() {
// Declaration moved off bare Shift+F12 (now References) to Ctrl+Shift+F12.
assert!(is_go_to_declaration_key(key(
KeyCode::F(12),
KeyModifiers::SHIFT | KeyModifiers::CONTROL
)));
// Plain F12 is Definition.
assert!(!is_go_to_declaration_key(key(
KeyCode::F(12),
KeyModifiers::NONE
)));
// Bare Shift+F12 is now References, not Declaration.
assert!(!is_go_to_declaration_key(key(
KeyCode::F(12),
KeyModifiers::SHIFT
)));
// Ctrl+F12 (no Shift) is Type Definition, not Declaration.
assert!(!is_go_to_declaration_key(key(
KeyCode::F(12),
KeyModifiers::CONTROL
)));
assert!(!is_go_to_declaration_key(key(
KeyCode::F(2),
KeyModifiers::SHIFT | KeyModifiers::CONTROL
)));
}
#[test]
fn go_to_type_definition_key_is_ctrl_f12() {
assert!(is_go_to_type_definition_key(key(
KeyCode::F(12),
KeyModifiers::CONTROL
)));
// Plain F12 (Definition) and Shift+F12 (References) are not Type Definition.
assert!(!is_go_to_type_definition_key(key(
KeyCode::F(12),
KeyModifiers::NONE
)));
assert!(!is_go_to_type_definition_key(key(
KeyCode::F(12),
KeyModifiers::SHIFT
)));
// Ctrl+Shift+F12 is Declaration, not Type Definition.
assert!(!is_go_to_type_definition_key(key(
KeyCode::F(12),
KeyModifiers::SHIFT | KeyModifiers::CONTROL
)));
assert!(!is_go_to_type_definition_key(key(
KeyCode::F(11),
KeyModifiers::CONTROL
)));
}
#[test]
fn go_to_implementation_key_is_cmd_f12() {
assert!(is_go_to_implementation_key(key(
KeyCode::F(12),
KeyModifiers::SUPER
)));
// Plain F12 (Definition), Shift+F12 (References) and Ctrl+F12 (Type
// Definition) are not Implementations.
assert!(!is_go_to_implementation_key(key(
KeyCode::F(12),
KeyModifiers::NONE
)));
assert!(!is_go_to_implementation_key(key(
KeyCode::F(12),
KeyModifiers::SHIFT
)));
assert!(!is_go_to_implementation_key(key(
KeyCode::F(12),
KeyModifiers::CONTROL
)));
assert!(!is_go_to_implementation_key(key(
KeyCode::F(11),
KeyModifiers::SUPER
)));
}
#[test]
fn implementation_picker_lists_every_target_as_a_jump_item() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let a = tmp.path().join("foo.rs");
let b = tmp.path().join("sub").join("bar.rs");
app.open_location_picker(
vec![(a.clone(), 4, 2), (b.clone(), 0, 0)],
"implementations",
);
let menu = app
.context_menu
.as_ref()
.expect("multiple implementations must open a picker, not silently pick the first");
assert_eq!(
menu.items.len(),
2,
"every implementor must get its own selectable row"
);
// Labels are workspace-relative path + 1-based line; actions jump straight
// to the resolved location.
assert_eq!(menu_label(&menu.items[0]), "foo.rs:5");
assert!(matches!(
menu.items[0].action(),
Some(MenuAction::GoToLocation { path, line: 4, col: 2 }) if path == &a
));
assert_eq!(
menu_label(&menu.items[1]),
format!("sub{}bar.rs:1", std::path::MAIN_SEPARATOR)
);
assert!(matches!(
menu.items[1].action(),
Some(MenuAction::GoToLocation { path, line: 0, col: 0 }) if path == &b
));
}
#[test]
fn shortcut_for_returns_expected_shortcuts_for_editor_symbol_actions() {
// Every editor symbol-menu row must advertise a working accelerator.
assert_eq!(
shortcut_for(&MenuAction::GoToDefinitionAt { row: 0, col: 0 }),
Some("F12")
);
assert_eq!(
shortcut_for(&MenuAction::GoToReferencesAt { row: 0, col: 0 }),
Some("⇧F12")
);
assert_eq!(
shortcut_for(&MenuAction::GoToDeclarationAt { row: 0, col: 0 }),
Some("⌃⇧F12")
);
assert_eq!(
shortcut_for(&MenuAction::GoToTypeDefinitionAt { row: 0, col: 0 }),
Some("⌃F12")
);
assert_eq!(
shortcut_for(&MenuAction::GoToImplementationAt { row: 0, col: 0 }),
Some("⌘F12")
);
assert_eq!(
shortcut_for(&MenuAction::RenameSymbolAt { row: 0, col: 0 }),
Some("F2")
);
assert_eq!(
shortcut_for(&MenuAction::ChangeAllOccurrencesAt { row: 0, col: 0 }),
Some("⌘F2")
);
}
#[test]
fn switching_sidebar_view_closes_the_open_commit_dropdown() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_sidebar_view(SidebarView::SourceControl);
app.commit_menu_open = true;
// Leaving Source Control must close the dropdown so it can't paint
// over the Run-Debug (or any other) sidebar view.
app.set_sidebar_view(SidebarView::RunDebug);
assert!(
!app.commit_menu_open,
"the commit dropdown must close when the sidebar view changes"
);
}
// --- Split editor (side-by-side panes) -----------------------------------
/// Seeding the Search panel from a terminal command must describe THAT
/// command: filter globs left over from an earlier manual search would
/// silently narrow the seeded results (the terminal scanned everything), and
/// the status line would still claim a faithful seed — feeding Replace All a
/// wrong subset.
#[test]
fn seeding_search_replaces_stale_include_and_exclude_filters() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.search.include = String::from("*.md");
app.search.exclude = String::from("vendor");
assert!(app.seed_search_from_command("rg TODO"));
assert_eq!(
app.search.include, "",
"a bare rg scanned everything; a stale include must not filter the seeded search"
);
assert_eq!(app.search.exclude, "");
assert!(app.seed_search_from_command("rg -g '*.rs' -g '!target' TODO"));
assert_eq!(app.search.include, "*.rs");
assert_eq!(app.search.exclude, "target");
}
/// A byte-range selection made in the Include field before the seed must not
/// survive into the (shorter) seeded text: the next keystroke used to
/// replace_range the stale span and panic out of bounds.
#[test]
fn seeding_search_cannot_leave_a_stale_field_selection() {
use crate::widgets::search::SearchField;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.search.include = String::from("**/*.rs,**/*.toml");
app.search.focus_field(SearchField::Include);
app.search.select_all_active();
assert!(app.seed_search_from_command("rg -g '*.md' TODO"));
assert_eq!(
app.search.field,
SearchField::Query,
"seeding hands focus to the query field it just filled"
);
app.search.type_char('x');
assert_eq!(app.search.include, "*.md", "the seeded include is intact");
}
/// Open a file into the focused editor group of a fresh App.
fn app_with_open_file(tmp: &std::path::Path, name: &str, body: &str) -> App {
let f = tmp.join(name);
std::fs::write(&f, body).unwrap();
let mut app = App::new(tmp.to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.focus_pane(Pane::Editor);
app
}
fn outline_sym(
name: &str,
kind: crate::lsp::manager::OutlineKind,
start: u32,
end: u32,
) -> crate::lsp::manager::OutlineSymbol {
crate::lsp::manager::OutlineSymbol {
name: name.to_string(),
detail: None,
kind,
depth: 0,
line: start,
character: 0,
range_start_line: start,
range_end_line: end,
}
}
#[test]
fn outline_symbols_apply_only_for_the_active_file() {
use crate::lsp::manager::OutlineKind;
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn a() {}\n");
let active = app.editor.path.clone().unwrap();
let syms = vec![outline_sym("a", OutlineKind::Function, 0, 0)];
// A reply for a file the user already navigated away from is dropped.
let other = tmp.path().join("b.rs");
assert!(
!app.apply_outline_symbols(other, 0, syms.clone()),
"a reply whose path is not the active editor file must be ignored"
);
assert!(app.outline.path.is_none(), "stale reply must not populate");
// A reply for the active file populates the outline.
assert!(app.apply_outline_symbols(active.clone(), 0, syms));
assert_eq!(app.outline.path.as_ref(), Some(&active));
assert!(!app.outline.is_empty());
}
#[test]
fn an_outline_reply_is_matched_by_request_not_by_the_larger_seq() {
use crate::lsp::manager::OutlineKind;
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn a() {}\n");
let active = app.editor.path.clone().unwrap();
// `seq` is a per-Editor counter, and a file landing in a FRESH editor group
// (a Cmd+\ split, or close-and-reopen) restarts it at zero. So the request
// actually outstanding can carry a far smaller number than a reply still in
// flight from the group the user left, and "the highest seq is the newest"
// is simply false. Anything that pre-selects replies by size before this
// guard sees them keeps the stale one; the guard then rejects it on the
// exact-match rule, and sync_outline never re-requests because its
// (path, seq) key has not moved — the outline stays tree-sitter-only until
// the next edit.
app.outline_synced = Some((active.clone(), Some(1)));
let stale = vec![outline_sym(
"from_the_old_group",
OutlineKind::Function,
0,
0,
)];
assert!(
!app.apply_outline_symbols(active.clone(), 40, stale),
"a bigger seq is a reply from a previous editor group, not a newer one"
);
assert!(app.outline.is_empty(), "the stale reply must not populate");
let fresh = vec![outline_sym("outstanding", OutlineKind::Function, 0, 0)];
assert!(
app.apply_outline_symbols(active.clone(), 1, fresh),
"the reply matching the outstanding request applies however small its seq"
);
assert!(!app.outline.is_empty());
}
#[test]
fn sync_outline_settles_empty_for_a_file_without_a_language_server() {
// A plain text file has no language server, so no documentSymbol reply will
// ever arrive. sync_outline must settle the panel to a loaded, empty state
// (rendering "No symbols") rather than leaving it spinning on "Loading".
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "notes.txt", "hello\nworld\n");
let active = app.editor.path.clone().unwrap();
app.sync_outline();
assert_eq!(app.outline.path.as_ref(), Some(&active));
assert!(app.outline.is_empty(), "no symbols for a non-served file");
assert!(
app.outline.loaded(),
"outline must be marked loaded so it shows 'No symbols', not 'Loading'"
);
}
#[test]
fn sync_outline_populates_from_tree_sitter_without_a_language_server() {
// Even with no LSP attached, opening a source file must fill the OUTLINE
// instantly from the buffer's own syntax tree (tree-sitter-first), so the
// panel never spins on "Loading" waiting for a cold server.
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(
tmp.path(),
"demo.rs",
"struct S;\n\nfn alpha() {}\n\nfn beta() {}\n",
);
app.sync_outline();
assert!(
app.outline.loaded(),
"syntactic outline settles immediately"
);
assert!(
!app.outline.is_empty(),
"tree-sitter must surface the struct and two functions"
);
}
#[test]
fn empty_lsp_reply_keeps_the_tree_sitter_outline() {
// A server that lacks documentSymbol (or replies before indexing) sends an
// empty outline. That must not blank symbols tree-sitter already painted.
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "demo.rs", "fn only() {}\n");
let active = app.editor.path.clone().unwrap();
app.sync_outline();
assert!(!app.outline.is_empty(), "tree-sitter painted the outline");
assert!(
!app.apply_outline_symbols(active, 0, Vec::new()),
"an empty LSP reply is ignored when an outline already exists"
);
assert!(
!app.outline.is_empty(),
"the tree-sitter outline survives the empty reply"
);
}
#[test]
fn clicking_the_outline_header_toggles_collapse() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn a() {}\n");
// Hermetic: ignore the user's real Outline-view pref (see scrollbar test).
app.explorer_views = Default::default();
let active = app.editor.path.clone().unwrap();
app.apply_outline_symbols(
active,
0,
vec![outline_sym(
"a",
crate::lsp::manager::OutlineKind::Function,
0,
0,
)],
);
assert!(app.outline.collapsed, "starts collapsed");
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let hdr = app.outline.last_area;
assert!(hdr.height > 0, "outline must have rendered");
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
hdr.x + 2,
hdr.y,
));
assert!(
!app.outline.collapsed,
"clicking the header expands the section"
);
}
#[test]
fn clicking_an_outline_row_jumps_the_editor_to_that_symbol() {
use crate::lsp::manager::OutlineKind;
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn a() {}\nfn b() {}\nfn c() {}\n");
// Hermetic: ignore the user's real Outline-view pref (see scrollbar test).
app.explorer_views = Default::default();
let active = app.editor.path.clone().unwrap();
app.outline.toggle_collapse(); // expand so rows render
app.apply_outline_symbols(
active,
0,
vec![
outline_sym("a", OutlineKind::Function, 0, 0),
outline_sym("b", OutlineKind::Function, 1, 1),
outline_sym("c", OutlineKind::Function, 2, 2),
],
);
app.editor.cursor_row = 0;
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.outline.last_area;
// Header occupies the first inner row; symbol rows follow. Click the
// second symbol ("b", line 1), which sits two rows below the header.
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
area.x + 2,
area.y + 2,
));
assert_eq!(
app.editor.cursor_row, 1,
"clicking the second outline row must move the editor caret to line 1"
);
}
#[test]
fn shift_tab_in_editor_dedents_the_current_python_line() {
let tmp = tempfile::tempdir().unwrap();
// Two 4-space levels so indent detection (#211) reads the file's step
// as 4; the old single 8-space jump now detects (correctly) as one
// 8-wide level.
let mut app = app_with_open_file(
tmp.path(),
"snippet.py",
"def f():\n if x:\n pass\n",
);
app.editor.cursor_row = 2;
app.editor.cursor_col = 8;
// Shift+Tab reaches the editor as BackTab.
app.handle_editor_key(key(KeyCode::BackTab, KeyModifiers::SHIFT));
assert_eq!(
app.editor.lines[2], " pass",
"Shift+Tab must outdent the line one level"
);
assert_eq!(app.editor.cursor_col, 4);
}
#[test]
fn tab_in_editor_indents_a_multiline_python_selection() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "block.py", "a = 1\nb = 2\n");
app.editor.cursor_row = 1;
app.editor.cursor_col = 5;
app.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: (0, 0),
head: (1, 5),
});
app.handle_editor_key(key(KeyCode::Tab, KeyModifiers::NONE));
assert_eq!(app.editor.lines[0], " a = 1");
assert_eq!(app.editor.lines[1], " b = 2");
}
#[test]
fn split_editor_duplicates_active_file_into_a_focused_right_group() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello\nworld\nthere");
let path = app.editor.path.clone().unwrap();
app.editor.cursor_row = 2;
app.split_editor();
assert!(
app.editor_layout.is_split(),
"split must create a second group"
);
assert_eq!(
app.editor_layout.active_dfs_index(),
1,
"the new (focused) group lands in the RIGHT column, mirroring VS Code"
);
// `editor` is always the focused group: it is the new right duplicate.
assert_eq!(
app.editor.path.as_deref(),
Some(path.as_path()),
"the duplicate shows the same file"
);
assert_eq!(
app.editor.cursor_row, 2,
"the duplicate opens at the source cursor position, not the top"
);
assert_eq!(
app.editor.tab_count(),
1,
"the new group holds exactly the file, with no stray blank tab"
);
// The original group survives in the left column.
let groups = app.editor_layout.inactive_groups();
assert_eq!(groups[0].path.as_deref(), Some(path.as_path()));
}
#[test]
fn split_down_makes_a_vertical_split_with_the_new_group_active_below() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello\nworld");
let path = app.editor.path.clone().unwrap();
app.split_editor_dir(editor_layout::SplitDir::Vertical, true);
assert!(app.editor_layout.is_split());
assert_eq!(
app.editor_layout.root_split_dir(),
Some(editor_layout::SplitDir::Vertical),
"Split Down stacks the groups vertically"
);
assert_eq!(
app.editor_layout.active_dfs_index(),
1,
"the new (focused) group is the LOWER leaf"
);
assert_eq!(app.editor.path.as_deref(), Some(path.as_path()));
let groups = app.editor_layout.inactive_groups();
assert_eq!(groups[0].path.as_deref(), Some(path.as_path()));
}
// Move/Copy into New Window spawn a REAL Ghostty window via `open`, so the
// happy path can't be exercised in a test without popping windows on the dev
// machine. These tests cover everything up to (and the shape of) the spawn:
// the refusal gates, the argv builder, and the `--open-file` launch open.
#[test]
fn new_window_is_refused_for_an_unsaved_buffer() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// A fresh app has a single blank, path-less buffer — nothing to hand off.
app.copy_into_new_window(0);
assert!(
app.status.contains("save the file first"),
"the refusal is explained: {}",
app.status
);
assert_eq!(app.editor.tab_count(), 1, "nothing was spawned or removed");
}
#[test]
fn new_window_is_refused_over_ssh_and_leaves_the_tab_in_place() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
// Over SSH croft runs on the headless host: there is no local window server.
app.is_remote = true;
let before = app.editor.tab_count();
app.move_into_new_window(app.editor.active_index());
assert!(
app.status.contains("not available over SSH"),
"the refusal is explained: {}",
app.status
);
assert_eq!(
app.editor.tab_count(),
before,
"Move is a no-op when it can't spawn — the file stays here"
);
assert!(app.editor.path.is_some());
}
#[cfg(target_os = "macos")]
#[test]
fn ghostty_open_argv_suppresses_the_stray_default_window() {
use std::ffi::OsStr;
let exe = std::path::Path::new("/usr/local/bin/croft");
let root = std::path::Path::new("/home/me/project");
let file = std::path::Path::new("/home/me/project/src/main.rs");
let argv = ghostty_open_argv(exe, root, file);
let argv: Vec<&OsStr> = argv.iter().map(|s| s.as_os_str()).collect();
assert_eq!(
argv,
[
OsStr::new("-na"),
OsStr::new("Ghostty"),
OsStr::new("--args"),
// Empirically: without this a fresh instance opens a 2nd window.
OsStr::new("--initial-window=false"),
OsStr::new("--quit-after-last-window-closed=true"),
OsStr::new("-e"),
OsStr::new("/usr/local/bin/croft"),
OsStr::new("/home/me/project"),
OsStr::new("--open-file"),
OsStr::new("/home/me/project/src/main.rs"),
// Opens focused on the file.
OsStr::new("--zen"),
],
"one Ghostty window, focused on the file, no stray default window"
);
}
#[cfg(target_os = "macos")]
#[test]
fn new_window_targets_the_host_terminal() {
// The new window matches whatever terminal croft runs in, not always Ghostty.
assert_eq!(
detect_host_terminal(Some("iTerm.app"), None),
HostTerminal::ITerm2
);
assert_eq!(
detect_host_terminal(Some("ghostty"), None),
HostTerminal::Ghostty
);
assert_eq!(
detect_host_terminal(Some("Apple_Terminal"), None),
HostTerminal::AppleTerminal
);
// Ghostty sometimes only exports TERM=xterm-ghostty.
assert_eq!(
detect_host_terminal(None, Some("xterm-ghostty")),
HostTerminal::Ghostty
);
// An unrecognised terminal is reported by name, not silently mishandled.
assert_eq!(
detect_host_terminal(Some("WezTerm"), None),
HostTerminal::Unknown("WezTerm".to_string())
);
}
#[cfg(target_os = "macos")]
#[test]
fn iterm2_and_terminal_scripts_shell_quote_paths_with_spaces() {
let exe = std::path::Path::new("/usr/local/bin/croft");
let root = std::path::Path::new("/home/me/My Project");
let file = std::path::Path::new("/home/me/My Project/a b.rs");
let iterm = iterm2_new_window_script(exe, root, file);
assert!(
iterm
.contains(r#"tell application "iTerm" to create window with default profile command "#),
"{iterm}"
);
// Each path single-quoted so the space survives the shell.
assert!(iterm.contains("'/home/me/My Project'"), "{iterm}");
assert!(iterm.contains("'/home/me/My Project/a b.rs'"), "{iterm}");
// The window opens focused on the file: --zen is part of the invocation.
assert!(iterm.contains("--zen"), "{iterm}");
let term = apple_terminal_new_window_script(exe, root, file);
assert!(
term.contains(r#"tell application "Terminal" to do script "#),
"{term}"
);
assert!(
term.contains("--open-file '/home/me/My Project/a b.rs' --zen"),
"{term}"
);
}
#[test]
fn zen_layout_collapses_explorer_and_terminal_and_survives_opening_a_file() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("hi.rs");
std::fs::write(&file, "fn main() {}").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Baseline: a normal launch shows both panes.
assert!(app.show_tree, "explorer visible by default");
assert!(app.show_terminal, "terminal visible by default");
// This is exactly what `run(.., zen = true)` does.
app.show_tree = false;
app.show_terminal = false;
app.open_file_at_launch(&file);
// Opening the file (which focuses the editor) must NOT re-show the chrome.
assert!(!app.show_tree, "--zen keeps the explorer collapsed");
assert!(!app.show_terminal, "--zen keeps the terminal collapsed");
assert_eq!(app.editor.path.as_deref(), Some(file.as_path()));
}
#[test]
fn open_file_at_launch_opens_the_file_and_focuses_the_editor() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("hi.rs");
std::fs::write(&file, "fn main() {}").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_file_at_launch(&file);
assert_eq!(
app.editor.path.as_deref(),
Some(file.as_path()),
"`croft --open-file <path>` opens that file on launch"
);
assert!(
app.focus == Pane::Editor,
"the editor takes focus on launch open"
);
}
#[test]
fn cmd_k_o_chords_route_to_the_new_window_actions() {
let tmp = tempfile::tempdir().unwrap();
// Blank/unsaved buffer: the chord is still handled, but the action refuses
// (no path), so no real window is spawned during the test.
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Cmd+K O -> Copy into New Window.
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('o'), KeyModifiers::NONE)));
assert!(
app.status.contains("save the file first"),
"Cmd+K O routes to Copy into New Window: {}",
app.status
);
// Cmd+K Shift+O -> Move into New Window.
app.status.clear();
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('o'), KeyModifiers::SHIFT)));
assert!(
app.status.contains("save the file first"),
"Cmd+K Shift+O routes to Move into New Window: {}",
app.status
);
}
#[test]
fn tab_menu_window_actions_carry_the_clicked_tab_index() {
let p = std::path::Path::new("/tmp/demo.rs");
let items = build_tab_context_menu_items(2, 3, false, Some(p), false, false, false);
assert!(matches!(
menu_action_of(&items, "Move into New Window"),
Some(MenuAction::MoveIntoNewWindow(2))
));
assert!(matches!(
menu_action_of(&items, "Copy into New Window"),
Some(MenuAction::CopyIntoNewWindow(2))
));
// Copy needs a real path; a blank buffer omits it but still offers Move.
let blank = build_tab_context_menu_items(0, 1, false, None, false, false, false);
assert!(menu_labels(&blank).contains(&"Move into New Window"));
assert!(!menu_labels(&blank).contains(&"Copy into New Window"));
}
#[test]
fn split_right_then_split_down_yields_three_tiled_groups() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.split_editor_dir(editor_layout::SplitDir::Horizontal, true); // Split Right
app.split_editor_dir(editor_layout::SplitDir::Vertical, true); // Split Down on the right group
assert_eq!(
app.editor_layout.leaf_count(),
3,
"repeated splitting builds a real grid, not a no-op"
);
// Left column full height; the right column is split top/bottom.
let rects = app
.editor_layout
.leaf_rects(ratatui::layout::Rect::new(0, 0, 100, 40), 10);
assert_eq!(rects.len(), 3);
assert_eq!(rects[0], ratatui::layout::Rect::new(0, 0, 50, 40));
assert_eq!(rects[1], ratatui::layout::Rect::new(50, 0, 50, 20));
assert_eq!(rects[2], ratatui::layout::Rect::new(50, 20, 50, 20));
// The newest (focused) group is the lower-right leaf.
assert_eq!(app.editor_layout.active_dfs_index(), 2);
}
/// There are physically two image-overlay slots (left/right column); any
/// layout other than the two-column split bakes the active group into slot 0.
/// The focused side must therefore never index past the array: clicking a PDF
/// in the lower-right group of a three-way split panicked with
/// index-out-of-bounds before this was clamped.
#[test]
fn focused_image_side_stays_within_the_two_overlay_slots() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.split_editor_dir(editor_layout::SplitDir::Horizontal, true);
app.split_editor_dir(editor_layout::SplitDir::Vertical, true);
assert_eq!(app.editor_layout.active_dfs_index(), 2);
assert!(
app.focused_image_side() < 2,
"focused_image_side must stay within overlays.editor"
);
}
/// In a grid of three or more groups the render path bakes the ACTIVE group
/// into overlay slot 0 (`update_editor_image_overlay(0, active_area)`), so
/// slot 0's image gate, layout key and baked pixels must all resolve to the
/// active group. They used to resolve to the depth-first-0 group instead:
/// a focused PDF in the third group either got no preview at all (when the
/// dfs-0 group held a text file) or was keyed under the dfs-0 group's path
/// and froze on its first baked page.
#[test]
fn slot_zero_of_a_grid_resolves_to_the_active_group() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.split_editor_dir(editor_layout::SplitDir::Horizontal, true);
app.split_editor_dir(editor_layout::SplitDir::Vertical, true);
let b = tmp.path().join("b.txt");
std::fs::write(&b, "B").unwrap();
app.editor.open_pinned(&b).unwrap();
assert_eq!(app.editor_layout.active_dfs_index(), 2);
assert_eq!(
app.group_on_side(0).and_then(|g| g.path.as_deref()),
Some(b.as_path()),
"slot 0 must be the active group in a 3+ grid"
);
assert!(
app.group_on_side(1).is_none(),
"slot 1 is dark in a 3+ grid; nothing may bake into it"
);
}
#[test]
fn move_right_with_no_neighbor_creates_a_new_group_with_the_moved_tab() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "A");
let b = tmp.path().join("b.txt");
std::fs::write(&b, "B").unwrap();
app.editor.open_pinned(&b).unwrap(); // active group: a.txt + b.txt, active = b
assert_eq!(app.editor.tab_count(), 2);
app.move_active_editor(editor_layout::Dir::Right);
assert_eq!(
app.editor_layout.leaf_count(),
2,
"no neighbour to the right → a new group is created for the moved tab"
);
assert_eq!(
app.editor.path.as_deref(),
Some(b.as_path()),
"the moved tab is active in the new group"
);
let groups = app.editor_layout.inactive_groups();
assert_eq!(groups.len(), 1);
assert!(
groups[0]
.iter_tabs()
.all(|e| e.path.as_deref() != Some(b.as_path())),
"the source group no longer holds the moved tab"
);
}
#[test]
fn move_left_into_an_existing_neighbor_relocates_and_collapses_the_emptied_source() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "A");
let a = tmp.path().join("a.txt");
app.split_editor_dir(editor_layout::SplitDir::Horizontal, true); // right group active, dup of a
let b = tmp.path().join("b.txt");
std::fs::write(&b, "B").unwrap();
app.editor.open_preview(&b).unwrap(); // right group now shows b (single tab)
assert_eq!(app.editor_layout.leaf_count(), 2);
app.move_active_editor(editor_layout::Dir::Left); // move b into the left (a) group
assert_eq!(
app.editor_layout.leaf_count(),
1,
"the emptied right group collapses away"
);
let paths: Vec<_> = app
.editor
.iter_tabs()
.filter_map(|e| e.path.clone())
.collect();
assert!(
paths.iter().any(|p| p == &a) && paths.iter().any(|p| p == &b),
"both a.txt and the moved b.txt now live in the surviving group: {paths:?}"
);
}
#[test]
fn split_in_group_opens_a_second_view_of_the_active_file_beside_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "A");
let a = tmp.path().join("a.txt");
app.split_in_group();
assert_eq!(app.editor_layout.leaf_count(), 2, "a second group appears");
assert_eq!(app.editor.path.as_deref(), Some(a.as_path()));
let groups = app.editor_layout.inactive_groups();
assert_eq!(
groups[0].path.as_deref(),
Some(a.as_path()),
"both groups show the same file"
);
}
#[test]
fn split_up_makes_a_vertical_split_with_the_new_group_active_above() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hi");
app.split_editor_dir(editor_layout::SplitDir::Vertical, false);
assert_eq!(
app.editor_layout.root_split_dir(),
Some(editor_layout::SplitDir::Vertical)
);
assert_eq!(
app.editor_layout.active_dfs_index(),
0,
"Split Up puts the new focused group in the UPPER leaf"
);
}
#[test]
fn split_left_makes_a_horizontal_split_with_the_new_group_active_left() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hi");
app.split_editor_dir(editor_layout::SplitDir::Horizontal, false);
assert_eq!(
app.editor_layout.root_split_dir(),
Some(editor_layout::SplitDir::Horizontal)
);
assert_eq!(
app.editor_layout.active_dfs_index(),
0,
"Split Left puts the new focused group in the LEFT leaf"
);
}
#[test]
fn cmd_k_backslash_chord_splits_the_editor_up() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hi");
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
assert!(app.cmd_k_leader.is_some(), "Cmd+K arms the chord leader");
app.handle_key(key(KeyCode::Char('\\'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(
app.editor_layout.root_split_dir(),
Some(editor_layout::SplitDir::Vertical),
"Cmd+K Cmd+\\ splits the editor vertically"
);
assert_eq!(
app.editor_layout.active_dfs_index(),
0,
"Cmd+K Cmd+\\ = Split Up (new group above); plain Cmd+\\ stays Split Right"
);
}
#[test]
fn cmd_k_shift_backslash_chord_splits_in_group() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hi");
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(
KeyCode::Char('\\'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(
app.editor_layout.leaf_count(),
2,
"Cmd+K Shift+Cmd+\\ (Split in Group) opens a second view beside the file"
);
}
#[test]
fn split_down_lays_the_groups_out_stacked_with_a_horizontal_seam() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hi");
app.split_editor_dir(editor_layout::SplitDir::Vertical, true);
let area = ratatui::layout::Rect::new(0, 0, 80, 24);
let rects = app.editor_layout.leaf_rects(area, 10);
assert_eq!(rects.len(), 2);
assert_eq!(
rects[0].x, rects[1].x,
"stacked groups share the same column"
);
assert!(
rects[0].y < rects[1].y,
"the two groups stack top over bottom"
);
assert_eq!(
rects[0].height + rects[1].height,
area.height,
"they tile the full height with the seam carrying no dedicated row"
);
}
#[test]
fn split_editor_refuses_a_blank_unsaved_buffer() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.split_editor();
assert!(
!app.editor_layout.is_split(),
"a blank buffer has no path to mirror, so split is refused"
);
}
#[test]
fn opening_a_file_in_the_split_replaces_the_duplicate_instead_of_stacking() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "first");
let b = tmp.path().join("b.txt");
std::fs::write(&b, "second").unwrap();
app.split_editor(); // right group = preview duplicate of a.txt
assert_eq!(app.editor.tab_count(), 1);
// Opening another file in the focused (right) column reuses the
// preview slot rather than leaving the duplicate pinned beside it.
app.editor.open_preview(&b).unwrap();
assert_eq!(
app.editor.tab_count(),
1,
"the right column swaps to the new file in place; the duplicate must not linger as a second tab"
);
assert_eq!(app.editor.path.as_deref(), Some(b.as_path()));
// The left column is untouched, giving a true side-by-side of two files.
let groups = app.editor_layout.inactive_groups();
let left = groups[0];
assert_eq!(left.tab_count(), 1);
assert_eq!(
left.path.as_deref(),
Some(tmp.path().join("a.txt").as_path())
);
}
#[test]
fn focus_editor_group_swaps_focus_but_keeps_physical_columns_fixed() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "left-original");
let original = app.editor.path.clone().unwrap();
app.split_editor(); // focus now on the right duplicate
assert_eq!(app.editor_layout.active_dfs_index(), 1);
// Move focus to the LEFT group (the original).
app.focus_editor_group(true);
assert_eq!(
app.editor_layout.active_dfs_index(),
0,
"focusing left makes the focused group the left column"
);
assert_eq!(
app.editor.path.as_deref(),
Some(original.as_path()),
"after the swap `editor` is the original left group"
);
assert!(
app.editor.focused && !app.editor_layout.inactive_groups()[0].focused,
"only the focused group's border lights up"
);
// Move focus back to the RIGHT group.
app.focus_editor_group(false);
assert_eq!(app.editor_layout.active_dfs_index(), 1);
assert_eq!(
app.editor.path.as_deref(),
Some(original.as_path()),
"both columns hold the same duplicated file, so the path is unchanged; \
the point is the swap is symmetric and never loses a group"
);
}
#[test]
fn closing_last_tab_in_focused_group_collapses_the_split() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "body");
app.split_editor();
assert!(app.editor_layout.is_split());
// Cmd+W closes the focused group's only tab -> the group empties and
// the split collapses back to the surviving column.
app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
.unwrap();
assert!(
!app.editor_layout.is_split(),
"emptying the focused group collapses the split"
);
assert_eq!(
app.editor_layout.active_dfs_index(),
0,
"the collapsed state resets to the single-column default"
);
assert!(app.editor_seams.is_empty());
}
#[test]
fn editor_image_overlay_is_dual_slot_and_clear_ors_both_columns() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let layout = |name: &str| EditorImageLayout {
cell_x: 0,
cell_y: 0,
cell_w: 10,
cell_h: 10,
path: tmp.path().join(name),
page: 1,
generation: 0,
};
// Both physical columns can hold an inline image at once.
app.overlays.editor[0].set_test_state(Some("left-osc".into()), Some(layout("l.png")), true);
app.overlays.editor[1].set_test_state(Some("right-osc".into()), Some(layout("r.png")), true);
assert_eq!(
app.editor_image_payload(0).map(|(o, _)| o),
Some("left-osc")
);
assert_eq!(
app.editor_image_payload(1).map(|(o, _)| o),
Some("right-osc")
);
// Disabling the right slot arms a clear; `consume_editor_image_clear`
// must report it even though the left slot is quiet.
app.disable_editor_image(1);
assert!(
app.consume_editor_image_clear(),
"a clear armed on either column must surface from the ORed consume"
);
assert!(
!app.consume_editor_image_clear(),
"the latch is one-shot and both slots were consumed"
);
}
#[test]
fn editor_split_key_is_cmd_backslash_only() {
assert!(is_editor_split_key(key(
KeyCode::Char('\\'),
KeyModifiers::SUPER
)));
// Bare backslash is a literal character, not a split.
assert!(!is_editor_split_key(key(
KeyCode::Char('\\'),
KeyModifiers::NONE
)));
// Modified variants are reserved for other (future) chords.
assert!(!is_editor_split_key(key(
KeyCode::Char('\\'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
}
#[test]
fn focus_group_keys_are_cmd_opt_arrows_disjoint_from_word_motion() {
assert!(is_focus_group_left_key(key(
KeyCode::Left,
KeyModifiers::SUPER | KeyModifiers::ALT
)));
assert!(is_focus_group_right_key(key(
KeyCode::Right,
KeyModifiers::SUPER | KeyModifiers::ALT
)));
// Plain Opt+Arrow is editor word-motion, NOT group focus.
assert!(!is_focus_group_left_key(key(
KeyCode::Left,
KeyModifiers::ALT
)));
assert!(!is_focus_group_right_key(key(
KeyCode::Right,
KeyModifiers::ALT
)));
}
#[test]
fn cmd_active_treats_super_as_command_everywhere() {
// Super is the command modifier on every platform, Termux or not.
assert!(cmd_active(KeyModifiers::SUPER, false));
assert!(cmd_active(KeyModifiers::SUPER, true));
}
#[test]
fn cmd_active_treats_ctrl_as_command_only_on_termux() {
// Termux (Android) has no Cmd key, so Ctrl stands in for it there
// (VS Code's Linux keymap). Off Termux, Ctrl is NOT the command key.
assert!(!cmd_active(KeyModifiers::CONTROL, false));
assert!(cmd_active(KeyModifiers::CONTROL, true));
}
#[test]
fn cmd_active_rejects_bare_modifiers() {
assert!(!cmd_active(KeyModifiers::NONE, true));
assert!(!cmd_active(KeyModifiers::ALT, true));
assert!(!cmd_active(KeyModifiers::SHIFT, true));
}
#[test]
fn editor_split_still_requires_super_off_termux() {
// Regression guard: with no Termux env present (the test process),
// Cmd+\ splits but Ctrl+\ does not — Ctrl+\ stays SIGQUIT for the shell.
assert!(is_editor_split_key(key(
KeyCode::Char('\\'),
KeyModifiers::SUPER
)));
assert!(!is_editor_split_key(key(
KeyCode::Char('\\'),
KeyModifiers::CONTROL
)));
}
#[test]
fn terminal_cycle_still_requires_super_off_termux() {
assert!(is_terminal_cycle_key(key(
KeyCode::Char(']'),
KeyModifiers::SUPER
)));
assert!(!is_terminal_cycle_key(key(
KeyCode::Char(']'),
KeyModifiers::CONTROL
)));
assert!(is_terminal_cycle_back_key(key(
KeyCode::Char('['),
KeyModifiers::SUPER
)));
}
fn diag(
start_char: u32,
end_char: u32,
severity: crate::lsp::manager::DiagnosticSeverity,
) -> crate::lsp::manager::Diagnostic {
crate::lsp::manager::Diagnostic {
start_line: 0,
start_char,
end_line: 0,
end_char,
severity,
message: String::from("test"),
}
}
#[test]
fn diagnostics_store_applies_to_the_active_editor_on_drain() {
use crate::lsp::manager::DiagnosticSeverity;
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("a.ts");
std::fs::write(&file, "const x = 1;\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
// Seed the store as if vtsls had published a diagnostic for this file.
let mut by_server = std::collections::HashMap::new();
by_server.insert(
String::from("vtsls"),
vec![diag(6, 7, DiagnosticSeverity::Error)],
);
app.lsp_diagnostics.insert(file.clone(), by_server);
// Nothing arrives on the channel, but the active file's diagnostics are
// unapplied (a "tab switch"), so the drain must push the stored set in.
let changed = app.drain_lsp_diagnostics();
assert!(
changed,
"applying the stored diagnostics must mark a redraw"
);
assert_eq!(app.editor.diagnostics_path(), Some(file.as_path()));
assert_eq!(
app.editor.diagnostic_spans_for_test()[0],
vec![(6, 7, DiagnosticSeverity::Error)],
);
}
#[test]
fn sync_markdown_lint_flags_a_second_top_level_heading() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("a.md");
std::fs::write(&file, "# Title\n\nBody.\n\n# Another\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
let changed = app.sync_markdown_lint();
assert!(changed, "a fresh markdown tab must lint on first sync");
assert_eq!(app.editor.diagnostics_path(), Some(file.as_path()));
assert!(
app.editor
.diagnostic_spans_for_test()
.iter()
.any(|line| !line.is_empty()),
"MD025 should have produced at least one squiggle"
);
let merged = app.merged_diagnostics(&file);
assert!(merged.iter().any(|d| d.message.contains("MD025")));
}
#[test]
fn sync_markdown_lint_is_quiet_for_a_clean_document_and_reruns_only_on_edit() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("clean.md");
std::fs::write(&file, "# Title\n\nA clean paragraph.\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
// A clean document has nothing to apply, so the first sync reports no
// change even though it did run the linter once.
assert!(!app.sync_markdown_lint());
assert!(
app.merged_diagnostics(&file).is_empty(),
"a clean document must not be flagged"
);
// Re-syncing an unchanged buffer must be a no-op (gated by edit_seq).
assert!(!app.sync_markdown_lint());
// The other half of this test's name: an EDIT must bump edit_seq, get the
// buffer re-linted, and surface the new violation. Without this the test
// passed on a linter that never ran a second time.
app.editor.goto_bottom();
app.editor
.insert_str_as("\n# Second Title\n", crate::provenance::Seat::Navigator);
assert!(
app.sync_markdown_lint(),
"an edit that introduces a second H1 must re-lint and report a change"
);
assert!(
app.merged_diagnostics(&file)
.iter()
.any(|d| d.message.contains("MD025")),
"the second H1 must be flagged after the edit"
);
}
/// Split panes hold separate buffers of one file, so after an edit in one
/// they carry different `edit_seq`s. The sync must settle on one pane per
/// path rather than alternate between the two, and must not report a change
/// when the diagnostics it stores are the ones already there: either would
/// re-lint and redraw on every tick forever.
#[test]
fn sync_markdown_lint_settles_after_a_split_pane_is_edited() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("doc.md");
std::fs::write(&file, "# Title\n\n# Second Title\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.split_editor();
app.editor.cursor_row = 0;
app.editor.cursor_col = 7;
app.editor.insert_char('!');
assert!(
app.sync_markdown_lint(),
"the first lint stores diagnostics"
);
assert!(
app.merged_diagnostics(&file)
.iter()
.any(|d| d.message.contains("MD025")),
"the edited pane still has two H1s"
);
assert!(
!app.sync_markdown_lint(),
"nothing changed since the last tick"
);
assert!(!app.sync_markdown_lint(), "and it stays settled");
}
/// Two panes can reach the same `edit_seq` with different text (one edit in
/// each). Switching which pane is linted must still lint it: the cursor has
/// to recognise a different buffer, not just a different sequence number.
#[test]
fn sync_markdown_lint_relints_a_pane_with_the_same_seq_but_other_text() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("doc.md");
std::fs::write(&file, "# Title\n\nplain\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.split_editor();
// One edit per pane: the focused pane gains an MD018 heading
// (`#Bad`), the other a harmless character, so both seqs match.
app.editor.cursor_row = 2;
app.editor.cursor_col = 0;
for c in "#Bad".chars() {
app.editor.insert_char(c);
}
let seq_bad = app.editor.edit_seq;
// The split put the new, focused pane on the right; move to the left one.
app.focus_editor_group(true);
app.editor.cursor_row = 2;
app.editor.cursor_col = 5;
// A split does not copy `edit_seq`, so type harmless text until this
// pane's count meets the other's.
while app.editor.edit_seq < seq_bad {
app.editor.insert_char('!');
}
assert_eq!(app.editor.edit_seq, seq_bad, "same seq, different text");
assert!(!app.editor.lines.iter().any(|l| l.starts_with("#B")));
let md018 = |app: &App| {
app.merged_diagnostics(&file)
.iter()
.any(|d| d.message.contains("MD018"))
};
// Lint with the `#Bad` pane focused (it is walked first) ...
app.focus_editor_group(false);
app.sync_markdown_lint();
assert!(md018(&app), "the focused pane has `#Bad`");
// ... then with the clean pane focused: same seq, other text.
app.focus_editor_group(true);
app.sync_markdown_lint();
assert!(
!md018(&app),
"the other pane has no MD018, so it must be re-linted"
);
}
/// A `.md` held by an INACTIVE split group must still be linted. The gather
/// loop used to walk only `self.editor`, so such a tab was never linted and
/// the cleanup below then dropped its stored diagnostics while it was still
/// open - the squiggles vanished from a pane that was plainly visible.
#[test]
fn sync_markdown_lint_covers_inactive_split_groups() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("doc.md");
std::fs::write(&file, "# Title\n\n# Second Title\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.split_editor(); // both groups hold doc.md; the new one is focused
// Move the ACTIVE group off the markdown file, so doc.md lives only in
// the inactive group - the case the gather loop missed. `open_pinned`
// ADDS a tab, so the old one has to be closed or the active group still
// holds doc.md and the bug never shows.
let other = tmp.path().join("other.txt");
std::fs::write(&other, "plain\n").unwrap();
app.editor.open_pinned(&other).unwrap();
let md_idx = app
.editor
.iter_tabs()
.position(|e| e.path.as_deref() == Some(file.as_path()))
.expect("the active group still holds doc.md before the close");
app.editor.close_tab(md_idx);
assert!(
!app.editor
.iter_tabs()
.any(|e| e.path.as_deref() == Some(file.as_path())),
"doc.md must now live ONLY in the inactive group"
);
let held_inactive = app
.editor_layout
.inactive_groups()
.into_iter()
.flat_map(|g| g.editors.iter())
.any(|e| e.path.as_deref() == Some(file.as_path()));
assert!(held_inactive, "the inactive group holds doc.md");
app.sync_markdown_lint();
assert!(
app.merged_diagnostics(&file)
.iter()
.any(|d| d.message.contains("MD025")),
"a markdown tab in an inactive pane must still be linted"
);
// And a second sync must not retire those diagnostics as "closed".
app.sync_markdown_lint();
assert!(
app.merged_diagnostics(&file)
.iter()
.any(|d| d.message.contains("MD025")),
"the tab is still open, so its diagnostics must survive the sweep"
);
}
#[test]
fn sync_markdown_lint_skips_non_markdown_files() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("a.rs");
std::fs::write(&file, "#Not a heading, this is Rust\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
assert!(!app.sync_markdown_lint());
assert!(app.merged_diagnostics(&file).is_empty());
}
#[test]
fn merged_diagnostics_layers_every_server_for_a_file() {
use crate::lsp::manager::DiagnosticSeverity;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let file = tmp.path().join("a.py");
let mut by_server = std::collections::HashMap::new();
by_server.insert(
String::from("ty"),
vec![diag(0, 1, DiagnosticSeverity::Error)],
);
by_server.insert(
String::from("ruff"),
vec![diag(2, 3, DiagnosticSeverity::Warning)],
);
app.lsp_diagnostics.insert(file.clone(), by_server);
let merged = app.merged_diagnostics(&file);
assert_eq!(
merged.len(),
2,
"both servers' diagnostics must survive the merge, not clobber each other"
);
}
#[test]
fn problems_panel_aggregates_the_store_across_files() {
use crate::lsp::manager::DiagnosticSeverity;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let a = tmp.path().join("a.rs");
let mut s1 = std::collections::HashMap::new();
s1.insert(
String::from("rustc"),
vec![
diag(0, 1, DiagnosticSeverity::Error),
diag(2, 3, DiagnosticSeverity::Warning),
],
);
app.lsp_diagnostics.insert(a, s1);
let b = tmp.path().join("b.rs");
let mut s2 = std::collections::HashMap::new();
s2.insert(
String::from("rustc"),
vec![diag(0, 1, DiagnosticSeverity::Error)],
);
app.lsp_diagnostics.insert(b, s2);
app.rebuild_problems();
assert_eq!(
app.problems.total_count(),
3,
"two files, three diagnostics"
);
assert_eq!(app.problems.error_count(), 2);
assert_eq!(app.problems.warning_count(), 1);
}
#[test]
fn renaming_a_terminal_pane_sets_and_clears_its_label() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.begin_rename_terminal(0);
match app.prompt.as_mut() {
Some(p) => {
assert!(matches!(p.kind, super::PromptKind::RenameTerminal(0)));
p.buffer = "logs".into();
}
None => panic!("rename prompt did not open"),
}
app.commit_prompt();
assert_eq!(
app.terminals[0].label(),
"logs",
"rename sets the manual name"
);
// A blank rename clears the manual name (falls back to the auto label).
app.begin_rename_terminal(0);
app.prompt.as_mut().unwrap().buffer = " ".into();
app.commit_prompt();
assert_ne!(
app.terminals[0].label(),
"logs",
"blank rename clears the name"
);
}
#[test]
fn a_second_pane_shows_its_label() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.bottom_panel_tab = BottomPanelTab::Terminal;
app.show_terminal = true;
// One pane => no label clutter; split to two, name the first.
app.split_terminal().unwrap();
app.terminals[0].set_manual_name(Some("server".into()));
draw(&mut app, 160, 50);
let buf_text: String = {
let backend = ratatui::backend::TestBackend::new(160, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
term.backend()
.buffer()
.content()
.iter()
.map(|c| c.symbol())
.collect()
};
assert!(
buf_text.contains("server"),
"the named pane shows its label"
);
}
#[test]
fn clicking_the_profile_caret_opens_an_anchored_shell_menu() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.bottom_panel_tab = BottomPanelTab::Terminal;
app.show_terminal = true;
draw(&mut app, 140, 50);
let caret = *app
.terminal_profile_buttons
.first()
.expect("the profile caret is rendered on the pane header");
assert!(app.context_menu.is_none());
left_click(&mut app, caret.x, caret.y);
let menu = app
.context_menu
.as_ref()
.expect("a context menu opens on caret click");
// Anchored at the caret (drops one row below it), not a centered modal.
assert_eq!(
menu.origin,
(caret.x, caret.y + 1),
"the menu anchors under the caret",
);
// Every row launches a shell profile.
assert!(!menu.items.is_empty(), "the menu lists shells");
assert!(
menu.items.iter().all(|e| matches!(
e,
MenuEntry::Item {
action: MenuAction::NewTerminalWithProfile(_),
..
}
)),
"every row opens a new terminal with a shell profile",
);
}
#[test]
fn opening_the_profile_menu_keeps_the_welcome_logo() {
// Regression guard for the welcome-logo bug: opening the terminal profile
// dropdown must NOT arm the welcome image clear — clearing it blanked the
// logo (the reported bug). The menu's own Clear paints over its cells, so
// the cached logo stays intact behind/around the dropdown.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.welcome.mark_displayed();
app.open_terminal_profile_picker(0);
assert!(app.context_menu.is_some(), "the menu opens");
assert!(
!app.consume_welcome_image_clear(),
"opening the profile menu must NOT evict the welcome logo",
);
}
#[test]
fn clicking_the_ports_tab_switches_the_panel_view() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let r = app.ports_tab_rect;
assert!(r.width > 0, "the PORTS tab must have a hit rect");
left_click(&mut app, r.x, r.y);
assert_eq!(
app.bottom_panel_tab,
BottomPanelTab::Ports,
"a click on the PORTS tab activates that view",
);
}
#[test]
fn a_detected_port_renders_in_the_ports_panel() {
use crate::widgets::ports::PortOrigin;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.bottom_panel_tab = BottomPanelTab::Ports;
app.ports
.upsert(3000, None, Some("node".into()), PortOrigin::Local);
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer().clone();
let text: String = buf.content().iter().map(|c| c.symbol()).collect();
assert!(text.contains("3000"), "the detected port is listed");
assert!(text.contains("node"), "its process is listed");
}
#[test]
fn opening_a_forwarded_remote_port_routes_to_the_local_browser_via_relay() {
use crate::widgets::ports::{PortOrigin, PortsPanel};
// On a remote session the local opener would run on the headless remote, so
// a forwarded port must re-open through the relay (lands on the local Mac).
let mut p = PortsPanel::new();
p.upsert(3000, None, None, PortOrigin::Remote("box".into()));
p.mark_forwarded(3000, 3001);
let entry = p.selected().unwrap();
match super::plan_port_open(entry, true) {
super::PortOpenAction::OpenViaRelay(url) => assert_eq!(url, "http://127.0.0.1:3001/"),
other => panic!("expected relay open, got {other:?}"),
}
}
#[test]
fn opening_an_unforwarded_remote_port_forwards_first() {
use crate::widgets::ports::{PortOrigin, PortsPanel};
let mut p = PortsPanel::new();
p.upsert(3000, None, None, PortOrigin::Remote("box".into()));
let entry = p.selected().unwrap();
assert!(matches!(
super::plan_port_open(entry, true),
super::PortOpenAction::Forward(3000)
));
}
#[test]
fn opening_a_local_port_opens_directly_not_via_relay() {
use crate::widgets::ports::{PortOrigin, PortsPanel};
let mut p = PortsPanel::new();
p.upsert(8000, None, None, PortOrigin::Local);
let entry = p.selected().unwrap();
match super::plan_port_open(entry, false) {
super::PortOpenAction::OpenDirect(url) => assert!(url.contains("8000"), "{url}"),
other => panic!("expected direct open, got {other:?}"),
}
}
#[test]
fn double_clicking_a_port_row_opens_it() {
use crate::widgets::ports::PortOrigin;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.bottom_panel_tab = BottomPanelTab::Ports;
// A remote, not-yet-forwarded port: opening it routes through the forward
// path, which sets an observable status without spawning a real browser.
app.ports
.upsert(3000, None, None, PortOrigin::Remote("box".into()));
draw(&mut app, 140, 50);
let x = app.ports.last_area.x + 2;
let y = app.ports.last_area.y + 1; // first data row
// A single click selects the row but takes no open action.
left_click(&mut app, x, y);
assert!(
!app.status.contains("orward"),
"a single click must not open the port: {}",
app.status
);
// A second click on the same row within the double-click window opens it.
left_click(&mut app, x, y);
assert!(
app.status.contains("orward"),
"a double click opens (forwards) the port: {}",
app.status
);
}
/// #317 beyond the terminal: the guard lives in `ClickTracker`, so every
/// surface that pairs clicks inherits it. The ports table is the cheapest one
/// to drive end to end, and it has a visible consequence - a double click
/// forwards the port - so a modified click that wrongly counted as half a
/// double would open something the user never double-clicked.
#[test]
fn a_modified_click_does_not_pair_with_a_plain_one_in_the_ports_table() {
use crate::widgets::ports::PortOrigin;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.bottom_panel_tab = BottomPanelTab::Ports;
app.ports
.upsert(3000, None, None, PortOrigin::Remote("box".into()));
draw(&mut app, 140, 50);
let x = app.ports.last_area.x + 2;
let y = app.ports.last_area.y + 1;
let click_with = |app: &mut App, modifiers| {
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: x,
row: y,
modifiers,
});
};
// A modified click must not ARM the pair: the plain click after it is the
// user's first ordinary click on that row, not the second half of a
// gesture they never made.
click_with(&mut app, KeyModifiers::CONTROL);
click_with(&mut app, KeyModifiers::empty());
assert!(
!app.status.contains("orward"),
"a plain click after a ctrl+click must not open the port: {}",
app.status
);
// And a modified click must not COMPLETE one either.
click_with(&mut app, KeyModifiers::empty());
app.status.clear();
click_with(&mut app, KeyModifiers::CONTROL);
assert!(
!app.status.contains("orward"),
"a ctrl+click must not complete a double-click: {}",
app.status
);
// The guard must not have cost the real gesture.
app.status.clear();
click_with(&mut app, KeyModifiers::empty());
click_with(&mut app, KeyModifiers::empty());
assert!(
app.status.contains("orward"),
"two ordinary clicks must still open the port: {}",
app.status
);
}
#[test]
fn clicking_the_port_toast_dismiss_button_clears_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.show_port_toast(3000, Some("node".into()));
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
// The render records the toast's clickable button rects; find Dismiss.
let dismiss = app
.port_toast
.as_ref()
.expect("toast is showing")
.buttons
.iter()
.find(|(_, a)| matches!(a, super::PortToastAction::Dismiss))
.map(|(r, _)| *r)
.expect("the toast has a dismiss button");
left_click(&mut app, dismiss.x, dismiss.y);
assert!(
app.port_toast.is_none(),
"clicking dismiss clears the toast"
);
}
/// #333: a newer release raises a bottom-LEFT popup that never captures
/// keys; Later dismisses it and remembers the version, so the same release
/// is not offered on the next launch.
#[test]
fn an_update_offer_raises_the_bottom_left_toast_and_later_dismisses_it() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.update_check = Some(crate::update_check::UpdateCheck::preloaded(Some(
"9.9.9".into(),
)));
assert!(app.poll_update_watch(), "the offer landing is a redraw");
let toast = app
.update_toast
.as_ref()
.expect("the offer raises the toast");
assert_eq!(toast.version, "9.9.9");
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buttons = app.update_toast.as_ref().unwrap().buttons.clone();
let update = buttons
.iter()
.find(|(_, a)| matches!(a, super::UpdateToastAction::Update))
.map(|(r, _)| *r)
.expect("an Update button");
assert!(update.x < 70, "the popup sits bottom-left: {update:?}");
assert!(update.y > 40, "the popup sits bottom-left: {update:?}");
let later = buttons
.iter()
.find(|(_, a)| matches!(a, super::UpdateToastAction::Later))
.map(|(r, _)| *r)
.expect("a Later button");
left_click(&mut app, later.x, later.y);
assert!(app.update_toast.is_none(), "Later clears the toast");
assert!(
app.staged_install.is_none(),
"Later stages nothing: the installed binary is untouched"
);
let cache =
crate::update_check::CheckCache::load(&home.path().join(".cache").join("croft"));
assert_eq!(
cache.dismissed.as_deref(),
Some("9.9.9"),
"Later is remembered"
);
});
}
/// #333: the three update producers share one event type; a drift
/// rebuild's Failed must not be charged to the staged release build, and a
/// drift Ready must not hand Relaunch a staged binary that was never built.
#[test]
fn update_events_are_charged_to_their_own_producer() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
update_events_are_charged_to_their_own_producer_body();
});
}
fn update_events_are_charged_to_their_own_producer_body() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let staged = tmp.path().join("never-built");
app.staged_install = Some(crate::update_check::StagedInstall::preloaded(
&[],
staged.clone(),
"9.9.9",
));
app.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[
crate::update_watch::UpdateEvent::Failed,
]));
assert!(app.poll_update_watch());
assert!(
app.staged_install.is_some(),
"the drift rebuild's failure leaves the staged build running"
);
assert!(
app.self_install.is_none(),
"the drift rebuild is the one that ended"
);
assert!(
app.status.contains("rebuild failed") && !app.status.contains("9.9.9"),
"the failure names the rebuild, not the release: {}",
app.status
);
app.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[
crate::update_watch::UpdateEvent::Ready,
]));
assert!(app.poll_update_watch());
assert_eq!(
app.update_status,
UpdateStatus::Ready,
"F9 is armed for the rebuild"
);
assert_eq!(
app.staged_update_binary(),
None,
"Relaunch must not swap in a staged binary that never landed"
);
assert!(
!app.update_toast.as_ref().is_some_and(|t| t.ready),
"the popup does not claim the release is ready"
);
// And F9 stays out of the rebuild path while the staged build holds
// cargo's lock (#245's latch, extended).
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.local_drift = Some(String::from("abc123"));
assert!(app.f9_update_armed(), "a drift hint arms F9");
app.staged_install = Some(crate::update_check::StagedInstall::preloaded(
&[],
staged,
"9.9.9",
));
assert!(!app.f9_update_armed(), "not while a staged build runs");
// A staged build that LANDED keeps its Relaunch through an unrelated
// rebuild, whatever that rebuild does: the staged channel delivers one
// Ready only, so the two lifecycles must never write each other's cell.
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let landed = tmp.path().join("landed");
std::fs::write(&landed, b"bin").unwrap();
app.staged_install = Some(crate::update_check::StagedInstall::preloaded(
&[
crate::update_watch::UpdateEvent::InProgress,
crate::update_watch::UpdateEvent::Ready,
],
landed.clone(),
"9.9.9",
));
assert!(app.poll_update_watch());
assert_eq!(
app.staged_update_binary().as_deref(),
Some(landed.as_path())
);
// The real sequence a drift rebuild emits: InProgress first, then its
// outcome. The staged binary stays swappable throughout.
app.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[
crate::update_watch::UpdateEvent::InProgress,
]));
assert!(app.poll_update_watch());
assert_eq!(
app.staged_update_binary().as_deref(),
Some(landed.as_path())
);
assert!(app.f9_update_armed(), "F9 still relaunches mid-rebuild");
app.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[
crate::update_watch::UpdateEvent::Failed,
]));
assert!(app.poll_update_watch());
assert_eq!(
app.staged_update_binary().as_deref(),
Some(landed.as_path())
);
assert!(app.f9_update_armed(), "and after the rebuild fails");
assert!(app.status.contains("rebuild failed"), "{}", app.status);
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let relaunch = app
.update_toast
.as_ref()
.expect("the ready toast")
.buttons
.iter()
.find(|(_, a)| matches!(a, super::UpdateToastAction::Relaunch))
.map(|(r, _)| *r)
.expect("a Relaunch button");
left_click(&mut app, relaunch.x, relaunch.y);
assert!(app.pending_reexec && app.quit, "Relaunch still fires");
// The symmetric case: a drift rebuild that landed survives a staged
// build failing.
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[
crate::update_watch::UpdateEvent::InProgress,
crate::update_watch::UpdateEvent::Ready,
]));
assert!(app.poll_update_watch());
app.staged_install = Some(crate::update_check::StagedInstall::preloaded(
&[
crate::update_watch::UpdateEvent::InProgress,
crate::update_watch::UpdateEvent::Failed,
],
tmp.path().join("nope"),
"9.9.9",
));
assert!(app.poll_update_watch());
assert_eq!(
app.update_status,
UpdateStatus::Ready,
"the rebuild's F9 is alive"
);
assert!(app.f9_update_armed());
assert_eq!(app.staged_update_binary(), None);
// Relaunch on the popup fires only for the STAGED readiness: with a
// drift Ready and no staged one, the click does nothing.
app.update_toast = Some(super::UpdateToast {
version: String::from("9.9.9"),
ready: true,
buttons: Vec::new(),
});
term.draw(|f| app.render(f)).unwrap();
let relaunch = app
.update_toast
.as_ref()
.unwrap()
.buttons
.iter()
.find(|(_, a)| matches!(a, super::UpdateToastAction::Relaunch))
.map(|(r, _)| *r)
.expect("a Relaunch button");
left_click(&mut app, relaunch.x, relaunch.y);
assert!(
!app.pending_reexec,
"no staged binary: Relaunch does not re-exec a rebuild"
);
}
/// #333: both corner popups can be up at once; they must not overlap.
#[test]
fn the_update_toast_stacks_above_the_port_toast() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.update_toast = Some(super::UpdateToast {
version: String::from("9.9.9"),
ready: false,
buttons: Vec::new(),
});
app.show_port_toast(3000, Some("node".into()));
let backend = ratatui::backend::TestBackend::new(60, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let update_row = app.update_toast.as_ref().unwrap().buttons[0].0.y;
let port_row = app.port_toast.as_ref().unwrap().buttons[0].0.y;
assert!(
update_row + 4 <= port_row,
"the update popup sits a full box above the port toast: {update_row} vs {port_row}"
);
}
/// #333: a staged build that lands turns the popup into a Relaunch offer,
/// and Relaunch is the same re-exec F9 arms - never automatic.
#[test]
fn a_staged_update_offers_relaunch_and_only_relaunch_re_execs() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let staged = tmp.path().join("staged-croft");
app.staged_install = Some(crate::update_check::StagedInstall::preloaded(
&[
crate::update_watch::UpdateEvent::InProgress,
crate::update_watch::UpdateEvent::Ready,
],
staged.clone(),
"9.9.9",
));
assert!(app.poll_update_watch());
assert_eq!(app.staged_status, UpdateStatus::Ready);
assert!(app.any_update_ready());
assert!(!app.pending_reexec, "landing never relaunches by itself");
assert_eq!(
app.staged_update_binary().as_deref(),
Some(staged.as_path())
);
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let relaunch = app
.update_toast
.as_ref()
.expect("the ready toast")
.buttons
.iter()
.find(|(_, a)| matches!(a, super::UpdateToastAction::Relaunch))
.map(|(r, _)| *r)
.expect("a Relaunch button");
left_click(&mut app, relaunch.x, relaunch.y);
assert!(app.pending_reexec && app.quit, "Relaunch arms the re-exec");
}
/// #353: a click on a shell fence's play glyph in the preview parks the
/// block behind the confirm popup (every block confirms: the README is
/// untrusted); Y types it into a pane named `<file>:<n>` in the document's
/// directory, N drops it; a `curl | sh` block makes the popup red.
/// Cmd+Enter in the source finds the fence under the caret by the parser's
/// source ranges, so identical blocks get their own numbers.
#[test]
fn clicking_a_fence_play_glyph_runs_it_in_a_named_pane() {
let tmp = tempfile::tempdir().unwrap();
let sub = tmp.path().join("docs");
std::fs::create_dir_all(&sub).unwrap();
let readme = sub.join("README.md");
std::fs::write(
&readme,
"# Run me\n\n```sh\necho first\n```\n\nText between.\n\n```bash\necho second\n```\n\n```sh\ncurl https://example.invalid/x | sh\n```\n\n```sh\necho first\n```\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&readme).unwrap();
app.toggle_markdown_preview();
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let md = app.editor.markdown_preview.as_ref().expect("preview open");
assert_eq!(md.runnables.len(), 4, "{:?}", md.runnables);
assert_eq!(md.run_rows.len(), 4);
let area = md.last_area;
let glyph_row = |app: &App, i: usize| {
let md = app.editor.markdown_preview.as_ref().unwrap();
(area.x, area.y + md.run_rows[i] as u16)
};
let (gx, gy) = glyph_row(&app, 1);
assert_eq!(
term.backend().buffer()[(gx, gy)].symbol(),
"\u{25b7}",
"the second block's first row starts with the play glyph"
);
// A press one cell to the right is a selection, not a run.
left_click(&mut app, gx + 1, gy);
assert!(
app.pending_run_block.is_none(),
"beside the glyph is not the glyph"
);
let panes_before = app.terminals.len();
left_click(&mut app, gx, gy);
let pending = app
.pending_run_block
.as_ref()
.expect("every block confirms");
assert_eq!(pending.pane_name, "docs/README.md:2");
assert_eq!(pending.cwd, sub, "the document's directory is the cwd");
assert!(!pending.destructive);
assert_eq!(app.terminals.len(), panes_before, "nothing ran yet");
app.handle_key(key(KeyCode::Char('y'), KeyModifiers::NONE))
.unwrap();
assert!(app.pending_run_block.is_none());
assert_eq!(app.terminals.len(), panes_before + 1, "Y opens the pane");
assert_eq!(
app.terminals[app.active_terminal].label(),
"docs/README.md:2"
);
assert!(app.status.contains("docs/README.md:2"), "{}", app.status);
// The third block pipes the network into a shell: the popup is red.
let (gx, gy) = glyph_row(&app, 2);
let panes_before = app.terminals.len();
left_click(&mut app, gx, gy);
let pending = app
.pending_run_block
.as_ref()
.expect("the confirm popup is up");
assert_eq!(pending.pane_name, "docs/README.md:3");
assert!(pending.destructive, "curl | sh turns the popup red");
term.draw(|f| app.render(f)).unwrap();
let painted: String = (0..40)
.flat_map(|y| (0..120).map(move |x| (x, y)))
.map(|(x, y)| term.backend().buffer()[(x, y)].symbol().to_string())
.collect();
assert!(
painted.contains("LOOKS DESTRUCTIVE"),
"the popup names the risk"
);
assert!(
painted.contains("curl https://example.invalid/x | sh"),
"and shows the block whole"
);
app.handle_key(key(KeyCode::Char('n'), KeyModifiers::NONE))
.unwrap();
assert!(app.pending_run_block.is_none(), "N drops it");
assert_eq!(app.terminals.len(), panes_before);
// Cmd+Enter in the source: the fence under the caret, by source range.
// The last block repeats the first's text and still gets its own number.
app.toggle_markdown_preview();
assert!(app.editor.markdown_preview.is_none());
app.focus_pane(super::Pane::Editor);
app.editor.cursor_row = 3; // "echo first"
app.handle_key(key(KeyCode::Enter, KeyModifiers::SUPER))
.unwrap();
let pending = app
.pending_run_block
.as_ref()
.expect("Cmd+Enter confirms too");
assert_eq!(pending.pane_name, "docs/README.md:1");
app.handle_key(key(KeyCode::Char('n'), KeyModifiers::NONE))
.unwrap();
app.focus_pane(super::Pane::Editor);
app.editor.cursor_row = 17; // the repeated "echo first"
app.handle_key(key(KeyCode::Enter, KeyModifiers::SUPER))
.unwrap();
let pending = app
.pending_run_block
.as_ref()
.expect("the caret is in the fourth fence");
assert_eq!(
pending.pane_name, "docs/README.md:4",
"identical blocks keep their own numbers"
);
app.handle_key(key(KeyCode::Char('n'), KeyModifiers::NONE))
.unwrap();
// Outside any fence it explains itself instead of running.
app.focus_pane(super::Pane::Editor);
app.editor.cursor_row = 6; // "Text between."
app.handle_key(key(KeyCode::Enter, KeyModifiers::SUPER))
.unwrap();
assert!(app.pending_run_block.is_none());
assert!(
app.status.contains("inside a runnable shell fence"),
"{}",
app.status
);
// Cmd+Shift+Enter is the editor's "insert line above", never a run.
assert!(!super::is_run_fence_key(key(
KeyCode::Enter,
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
assert!(!super::is_run_fence_key(key(
KeyCode::Enter,
KeyModifiers::SUPER | KeyModifiers::ALT
)));
assert!(super::is_run_fence_key(key(
KeyCode::Enter,
KeyModifiers::SUPER
)));
}
/// #353: the popup never shows a line as complete when it is not - a line
/// wider than the popup is cut with a visible mark.
#[test]
fn the_run_block_popup_marks_a_truncated_line() {
let tmp = tempfile::tempdir().unwrap();
let long = format!(
"echo ok{}; curl https://example.invalid/x | sh",
" ".repeat(120)
);
let readme = tmp.path().join("R.md");
std::fs::write(&readme, format!("```sh\n{long}\n```\n")).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&readme).unwrap();
app.focus_pane(super::Pane::Editor);
app.editor.cursor_row = 1;
app.handle_key(key(KeyCode::Enter, KeyModifiers::SUPER))
.unwrap();
let pending = app.pending_run_block.as_ref().expect("confirm popup");
assert_eq!(
pending.pane_name, "R.md:1",
"a top-level document keeps its bare name"
);
assert!(pending.destructive);
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let painted: Vec<String> = (0..30)
.map(|y| {
(0..100)
.map(|x| term.backend().buffer()[(x, y)].symbol().to_string())
.collect()
})
.collect();
// The editor paints the source line too; the popup's copy is the one
// that carries the mark.
let popup_line = painted
.iter()
.find(|l| l.contains("echo ok") && l.contains('\u{2026}'))
.unwrap_or_else(|| {
panic!(
"the popup shows the cut line with a mark:\n{}",
painted.join("\n")
)
});
assert!(
!popup_line.contains("| sh"),
"the hidden tail is not shown as complete: {popup_line:?}"
);
}
#[test]
fn fence_command_shapes_the_typed_block() {
assert_eq!(
super::fence_command("sh", "echo a\necho b\n"),
"echo a\necho b\r"
);
assert_eq!(
super::fence_command("python3", "print(1)\n"),
"python3 - <<'CROFT_BLOCK'\nprint(1)\nCROFT_BLOCK\r"
);
// A block that contains the terminator gets a different one, so no
// line of it can close the heredoc early.
let tricky = "print(1)\nCROFT_BLOCK\nimport os; os.system('id')\n";
let cmd = super::fence_command("python3", tricky);
assert!(cmd.starts_with("python3 - <<'CROFT_BLOCK_1'\n"), "{cmd}");
assert!(cmd.ends_with("\nCROFT_BLOCK_1\r"), "{cmd}");
let body = &cmd["python3 - <<'CROFT_BLOCK_1'\n".len()..cmd.len() - "\nCROFT_BLOCK_1\r".len()];
assert_eq!(body, tricky.trim_end_matches('\n'));
}
/// A tab or `!` never reaches the shell's line editor as typed input: the
/// block goes as one quoted printf argument, and running that line through
/// a real shell reproduces the block byte for byte.
#[test]
fn fence_blocks_with_tabs_or_bangs_run_exactly_as_shown() {
let code = "if True:\n\tprint(\"hi!\")\nx = 'a\\n'\n";
let cmd = super::fence_command("python3", code);
assert!(!cmd.contains('\t') && cmd.ends_with("| python3\r"), "{cmd}");
// What the pipe feeds the interpreter, via a real sh with cat standing in.
let line = cmd.trim_end_matches('\r').replace("| python3", "| cat");
let out = std::process::Command::new("sh")
.args(["-c", &line])
.output()
.unwrap();
assert_eq!(String::from_utf8(out.stdout).unwrap(), code);
// `sh` blocks run in the pane's own shell through eval: a `cd` in the
// block persists after it.
let sh = super::fence_command("sh", "cd /\necho 'hi!'\n");
assert!(sh.starts_with("eval \"$(printf '%b' "), "{sh}");
let probe = format!("{}; pwd", sh.trim_end_matches('\r'));
let out = std::process::Command::new("sh")
.args(["-c", &probe])
.output()
.unwrap();
assert_eq!(String::from_utf8(out.stdout).unwrap(), "hi!\n/\n");
}
/// #360: the built-in secret rules sit in the trigger set by default,
/// leave it when the setting is switched off, and come back on; a reveal
/// window lasts ten seconds and asks for a redraw when it closes.
#[test]
fn secret_redaction_toggles_the_builtin_rules_and_reveal_expires() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.secret_redaction, "on by default");
assert!(
app.triggers.has_redactions(),
"the built-in rules are loaded"
);
assert_eq!(
crate::triggers::mask_text("AKIAIOSFODNN7EXAMPLE", &app.triggers, false),
"\u{2022}".repeat(20)
);
app.toggle_secret_redaction();
assert!(!app.secret_redaction);
assert!(
!app.triggers.has_redactions(),
"off means no built-in rules"
);
app.toggle_secret_redaction();
assert!(app.triggers.has_redactions());
assert!(!app.redactions_revealed());
app.reveal_redacted_secrets();
assert!(app.redactions_revealed());
assert!(
!app.tick_redaction_reveal(),
"still inside the window: no change"
);
app.redaction_reveal_until = Some(std::time::Instant::now());
assert!(
app.tick_redaction_reveal(),
"the window closing is a redraw"
);
assert!(!app.redactions_revealed());
assert!(app.status.contains("masked again"));
// The chip reads what was PAINTED: a hidden panel paints nothing, so a
// stale count from the last visible frame must not survive it.
if let Some(t) = app.terminals.first_mut() {
t.redacted_on_screen = 3;
}
assert_eq!(app.redacted_on_screen(), 3);
app.show_terminal = false;
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.redacted_on_screen(), 0, "a hidden pane counts nothing");
app.show_terminal = true;
// The clipboard keeps the real value unless a rule says otherwise; the
// scrollback dump always masks.
assert_eq!(
app.terminal_text_for_copy(String::from("k=AKIAIOSFODNN7EXAMPLE")),
"k=AKIAIOSFODNN7EXAMPLE"
);
app.triggers = std::sync::Arc::new(crate::triggers::TriggerSet::from_json(
r#"[{ "regex": "AKIA[0-9A-Z]{16}", "action": "redact", "copy": "masked" }]"#,
));
assert_eq!(
app.terminal_text_for_copy(String::from("k=AKIAIOSFODNN7EXAMPLE")),
format!("k={}", "\u{2022}".repeat(20))
);
}
/// #360, byte level: the terminal session store is written to disk and
/// replayed next launch, so a key that was on screen must not be in it.
#[test]
fn the_session_store_holds_the_mask_not_the_key() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminal_session_path = tmp.path().join("terminal-sessions.json");
let term = crate::widgets::terminal::PtyTerminal::new_with_transcript(
tmp.path(),
&[String::from("key AKIAIOSFODNN7EXAMPLE end")],
)
.unwrap();
// The transcript is painted into the grid during the spawn, before
// the child can write, so the save sees it at once.
app.insert_terminal(term);
app.save_terminal_session();
let store = std::fs::read_to_string(&app.terminal_session_path).unwrap();
assert!(
!store.contains("AKIAIOSFODNN7EXAMPLE"),
"the key leaked to disk: {store}"
);
assert!(
store.contains("key \u{2022}"),
"the mask was stored in its place: {store}"
);
}
/// #360: quick-select offers no hint inside a masked span (a hex run or a
/// number there is a fragment of the secret), while hints elsewhere on
/// the screen survive. The masked token here is itself a hex run at a
/// word boundary, so without the filter it WOULD be a hint.
#[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 clicking_the_problems_tab_switches_the_panel_view() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert_eq!(app.bottom_panel_tab, BottomPanelTab::Terminal);
let r = app.problems_tab_rect;
assert!(r.width > 0, "the PROBLEMS tab must have a hit rect");
left_click(&mut app, r.x, r.y);
assert_eq!(
app.bottom_panel_tab,
BottomPanelTab::Problems,
"a click on the PROBLEMS tab activates that view",
);
// And the TERMINAL tab switches back.
let t = app.terminal_tab_rect;
left_click(&mut app, t.x, t.y);
assert_eq!(app.bottom_panel_tab, BottomPanelTab::Terminal);
}
#[test]
fn clicking_the_output_tab_switches_the_panel_view() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let r = app.output_tab_rect;
assert!(r.width > 0, "the OUTPUT tab must have a hit rect");
left_click(&mut app, r.x, r.y);
assert_eq!(
app.bottom_panel_tab,
BottomPanelTab::Output,
"a click on the OUTPUT tab activates that view",
);
}
#[test]
fn the_output_view_renders_a_pushed_channel_line() {
use crate::output::OutputLevel;
let ch = "app-output-render-test";
crate::output::push(ch, OutputLevel::Error, "boom-from-server");
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.bottom_panel_tab = BottomPanelTab::Output;
// Select our channel so the assertion is independent of other channels.
app.output.sync();
assert!(
app.output.select_by_name(ch),
"the pushed channel is present in the bus",
);
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let mut text = String::new();
for y in 0..50 {
for x in 0..140 {
text.push_str(buf[(x, y)].symbol());
}
}
assert!(
text.contains("boom-from-server"),
"the OUTPUT view renders the channel's line",
);
}
/// Issue #215: text in the rendered Markdown view must be selectable.
/// A drag over the preview selects what is on screen, Cmd+C copies the
/// RENDERED text (not the source), and Esc clears the selection.
#[test]
fn dragging_in_the_markdown_preview_selects_and_copies_rendered_text() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let md = tmp.path().join("doc.md");
std::fs::write(&md, "# Heading\n\nSome rendered body text here.\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&md).unwrap();
app.focus_pane(Pane::Editor);
// Cmd+Shift+V flips to the rendered preview.
app.handle_key(key(
KeyCode::Char('v'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert!(
app.editor.markdown_preview.is_some(),
"the preview must be up"
);
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
// Find the rendered row carrying the body text and drag across it.
let (area, row_idx, text) = {
let md = app.editor.markdown_preview.as_ref().unwrap();
let (i, t) = md
.rows
.iter()
.enumerate()
.map(|(i, cells)| (i as u16, cells.concat()))
.find(|(_, r)| r.contains("rendered body"))
.expect("the body text must be rendered");
(md.last_area, i, t)
};
let start_col = text.find("rendered").unwrap() as u16;
let end_col = start_col + "rendered".len() as u16 - 1;
let y = area.y + row_idx;
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
area.x + start_col,
y,
));
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
area.x + end_col,
y,
));
app.handle_mouse(mouse(
MouseEventKind::Up(MouseButton::Left),
area.x + end_col,
y,
));
assert_eq!(
app.editor
.markdown_preview
.as_ref()
.map(|md| md.selection_text())
.unwrap_or_default(),
"rendered",
"the drag must select the rendered word under the pointer"
);
// The selection paints: re-render and check the tinted cell.
term.draw(|frame| app.render(frame)).unwrap();
let sel_bg = app.theme.selection();
assert_eq!(
term.backend().buffer()[(area.x + start_col, y)].bg,
sel_bg,
"the selected cell must wear the selection background"
);
// Esc clears it.
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(
!app.editor
.markdown_preview
.as_ref()
.map(|md| md.has_selection())
.unwrap_or(false),
"Esc clears the preview selection"
);
}
/// Issue #212: typing in the focused Problems panel filters diagnostics
/// by text; Backspace pops a character; Esc clears the filter before it
/// gives the pane back to the editor.
#[test]
fn typing_in_the_problems_panel_filters_and_esc_clears_before_leaving() {
use crate::lsp::manager::{Diagnostic, DiagnosticSeverity};
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("hello.rs");
std::fs::write(&file, "fn a() {}\nfn b() {}\nfn run() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mut by_server = std::collections::HashMap::new();
by_server.insert(
String::from("rustc"),
vec![
Diagnostic {
start_line: 0,
start_char: 0,
end_line: 0,
end_char: 1,
severity: DiagnosticSeverity::Error,
message: String::from("mismatched types"),
},
Diagnostic {
start_line: 2,
start_char: 3,
end_line: 2,
end_char: 6,
severity: DiagnosticSeverity::Warning,
message: String::from("function `run` is never used"),
},
],
);
app.lsp_diagnostics.insert(file.clone(), by_server);
app.rebuild_problems();
app.bottom_panel_tab = BottomPanelTab::Problems;
app.focus_pane(Pane::Terminal);
for c in "mismatch".chars() {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
assert_eq!(
app.problems.text_filter, "mismatch",
"plain typing must reach the panel's filter"
);
app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.problems.text_filter, "mismatc", "Backspace pops");
// Esc clears the filter but keeps the pane focused.
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(app.problems.text_filter.is_empty(), "Esc clears the filter");
assert!(
app.focus == Pane::Terminal,
"the first Esc only clears; the pane keeps focus"
);
// A second Esc, with nothing to clear, hands the pane back.
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(app.focus == Pane::Editor, "the second Esc leaves the panel");
}
#[test]
fn clicking_a_problem_row_opens_that_file_at_the_line() {
use crate::lsp::manager::DiagnosticSeverity;
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("hello.rs");
std::fs::write(&file, "fn a() {}\nfn b() {}\nfn run() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mut by_server = std::collections::HashMap::new();
by_server.insert(
String::from("rustc"),
vec![crate::lsp::manager::Diagnostic {
start_line: 2,
start_char: 3,
end_line: 2,
end_char: 6,
severity: DiagnosticSeverity::Warning,
message: String::from("function `run` is never used"),
}],
);
app.lsp_diagnostics.insert(file.clone(), by_server);
app.rebuild_problems();
app.bottom_panel_tab = BottomPanelTab::Problems;
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
// Row 0 is the toolbar, row 1 the file header, row 2 the diagnostic.
let list = app.problems.last_area;
left_click(&mut app, list.x + 4, list.y + 2);
assert_eq!(
app.editor.path.as_deref(),
Some(file.as_path()),
"clicking the row opens the file",
);
assert_eq!(app.editor.cursor_row, 2, "and jumps to the diagnostic line");
}
#[test]
fn the_problems_count_paints_an_orange_pill_in_the_tab_strip() {
use crate::lsp::manager::DiagnosticSeverity;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let a = tmp.path().join("a.rs");
let mut s1 = std::collections::HashMap::new();
s1.insert(
String::from("rustc"),
vec![diag(0, 1, DiagnosticSeverity::Error)],
);
app.lsp_diagnostics.insert(a, s1);
app.rebuild_problems();
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
// Somewhere along the PROBLEMS tab the count badge fills with the brand
// gradient's orange corner, the "circle" the user asked for.
let strip = app.problems_tab_rect;
let orange = crate::gradient::rgb_color(crate::gradient::GRAD_TR);
let painted = (strip.x..strip.x + strip.width).any(|x| buf[(x, strip.y)].bg == orange);
assert!(painted, "the problem count wears an orange pill");
// And the rounded right cap of the pill sits in brand orange foreground.
let cap_r = (strip.x..strip.x + strip.width)
.any(|x| buf[(x, strip.y)].symbol() == "\u{e0b4}" && buf[(x, strip.y)].fg == orange);
assert!(cap_r, "the pill has a rounded orange right cap");
}
#[test]
fn the_active_panel_tab_is_underlined() {
use ratatui::style::Modifier;
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();
// TERMINAL is active by default: its label underlines like a VS Code tab,
// but the underline hugs the word, not the padded hit rect.
let t = app.terminal_tab_rect;
let buf = term.backend().buffer();
let underlined = (t.x..t.x + t.width)
.filter(|&x| buf[(x, t.y)].modifier.contains(Modifier::UNDERLINED))
.count();
assert_eq!(
underlined,
"TERMINAL".len(),
"underline spans only the word"
);
assert!(
!buf[(t.x, t.y)].modifier.contains(Modifier::UNDERLINED),
"the leading pad space is not underlined",
);
assert!(
!buf[(t.x + t.width - 1, t.y)]
.modifier
.contains(Modifier::UNDERLINED),
"the trailing pad space is not underlined",
);
}
// ---------------------------------------------------------------------------
// On-screen keyboard (Termux touch typing)
// ---------------------------------------------------------------------------
fn left_click(app: &mut App, column: u16, row: u16) {
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column,
row,
modifiers: KeyModifiers::empty(),
});
}
fn 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();
}
#[test]
fn osk_auto_shows_on_terminal_tap_and_only_when_armed() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.osk_auto = true;
draw(&mut app, 80, 40);
let t = app.terminals[0].last_area;
assert!(t.width > 0 && t.height > 0, "terminal pane must be visible");
left_click(&mut app, t.x + t.width / 2, t.y + t.height / 2);
assert!(
app.osk.is_some(),
"a tap in the terminal must raise the on-screen keyboard on Termux"
);
// Desktop terminals (auto flag off) keep the band hidden on the same tap.
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.osk_auto = false;
draw(&mut app, 80, 40);
let t = app.terminals[0].last_area;
left_click(&mut app, t.x + t.width / 2, t.y + t.height / 2);
assert!(app.osk.is_none());
}
#[test]
fn osk_auto_shows_on_editor_tap() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("notes.txt");
std::fs::write(&path, "hello\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.osk_auto = true;
app.editor.open_preview(&path).unwrap();
app.focus_pane(Pane::Editor);
draw(&mut app, 80, 40);
let e = app.editor.last_area;
left_click(&mut app, e.x + e.width / 2, e.y + e.height / 2);
assert!(
app.osk.is_some(),
"a tap in the editor text area must raise the on-screen keyboard"
);
}
#[test]
fn osk_reserves_bottom_band_above_status_bar() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.osk = Some(crate::widgets::osk::Osk::new());
draw(&mut app, 80, 40);
let band = app.osk.as_ref().unwrap().last_area;
assert_eq!(
band.height,
crate::widgets::osk::band_height(40),
"band height scales with the frame for thumb-sized keys"
);
assert_eq!(
band.y + band.height,
40 - 1,
"keyboard docks directly above the status bar"
);
assert_eq!(band.width, 80, "keyboard spans the full frame width");
// Default focus is the sidebar, not the terminal, so the terminal pane
// folds away entirely and its space goes to the keyboard.
assert_eq!(
app.terminals[0].last_area,
Rect::default(),
"non-focused terminal must fold away (and not phantom-hit-test) while the keyboard is up"
);
}
#[test]
fn osk_with_editor_focus_hides_terminal_and_keeps_editor() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("notes.txt");
std::fs::write(&path, "hello\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_preview(&path).unwrap();
app.focus_pane(Pane::Editor);
app.osk = Some(crate::widgets::osk::Osk::new());
draw(&mut app, 80, 40);
let band = app.osk.as_ref().unwrap().last_area;
assert!(band.height > 0);
assert_eq!(app.terminals[0].last_area, Rect::default());
let e = app.editor.last_full_area;
assert!(
e.height > 0,
"the editor must stay visible while typing into it"
);
assert!(
e.y + e.height <= band.y,
"editor must end above the keyboard band"
);
}
#[test]
fn osk_with_terminal_focus_bumps_terminal_above_keyboard() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("notes.txt");
std::fs::write(&path, "hello\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_preview(&path).unwrap();
app.focus_pane(Pane::Terminal);
app.osk = Some(crate::widgets::osk::Osk::new());
draw(&mut app, 80, 40);
let band = app.osk.as_ref().unwrap().last_area;
let t = app.terminals[0].last_area;
assert!(
t.height > 0,
"the terminal must stay visible while typing into it"
);
assert_eq!(
t.y + t.height,
band.y,
"terminal rides directly on top of the keyboard"
);
assert_eq!(
t.y, 1,
"the panel group claims the editor's space from the top; the terminal \
body sits one row down, under the panel tab strip (PROBLEMS / TERMINAL)",
);
assert_eq!(
app.editor.last_area.height, 0,
"the open editor folds away while typing into the terminal"
);
}
#[test]
fn osk_tap_types_into_focused_editor() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("notes.txt");
std::fs::write(&path, "").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.osk_auto = true;
app.editor.open_preview(&path).unwrap();
app.focus_pane(Pane::Editor);
draw(&mut app, 80, 40);
let e = app.editor.last_area;
left_click(&mut app, e.x + 1, e.y + 1);
assert!(app.osk.is_some());
// Second frame lays the keyboard band out so its keys are tappable.
draw(&mut app, 80, 40);
let r = app
.osk
.as_ref()
.unwrap()
.rect_for(crate::widgets::osk::OskKey::Char('a'))
.expect("lower layer exposes the letter a");
left_click(&mut app, r.x + r.width / 2, r.y);
assert_eq!(
app.editor.lines[0], "a",
"an OSK letter tap must reach the editor buffer like a keystroke"
);
}
#[test]
fn osk_hide_key_dismisses_the_band() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.osk = Some(crate::widgets::osk::Osk::new());
draw(&mut app, 80, 40);
let r = app
.osk
.as_ref()
.unwrap()
.rect_for(crate::widgets::osk::OskKey::Hide)
.expect("hide key is always present");
left_click(&mut app, r.x + r.width / 2, r.y);
assert!(app.osk.is_none(), "the hide key must dismiss the keyboard");
}
#[test]
fn osk_tap_types_into_file_finder_query() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.osk = Some(crate::widgets::osk::Osk::new());
app.open_file_finder();
draw(&mut app, 80, 40);
let r = app
.osk
.as_ref()
.unwrap()
.rect_for(crate::widgets::osk::OskKey::Char('a'))
.unwrap();
left_click(&mut app, r.x + r.width / 2, r.y);
assert_eq!(
app.file_finder.as_ref().unwrap().query,
"a",
"OSK taps must route into open modals, not be swallowed by their mouse gates"
);
}
/// Render once and return (title 'T' cell coords, add-button rect).
fn terminal_header_probe(app: &mut App) -> Rect {
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.terminal().last_area;
assert!(
area.width > 20 && area.height > 2,
"terminal pane must render"
);
app.terminal_add_buttons[0]
}
#[test]
fn black_theme_terminal_buttons_are_teal_icons_not_navy_chips() {
use crate::gradient::{INNER_ACCENT, rgb_color};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let add = terminal_header_probe(&mut app);
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let plus = (add.x + 1, add.y);
assert_eq!(buf[plus].symbol(), "+");
assert_eq!(buf[plus].fg, rgb_color(INNER_ACCENT));
assert_ne!(
buf[plus].bg,
Color::Rgb(0x1e, 0x3a, 0x6e),
"Black theme must not paint the navy chip behind the + button"
);
}
#[test]
fn black_theme_terminal_button_hover_paints_teal_pill() {
use crate::gradient::{POPUP_SEL_BG, rgb_color};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let add = terminal_header_probe(&mut app);
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Moved,
column: add.x + 1,
row: add.y,
modifiers: KeyModifiers::NONE,
});
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let plus = (add.x + 1, add.y);
assert_eq!(
buf[plus].bg,
rgb_color(POPUP_SEL_BG),
"hovered button wears the teal pill"
);
assert_eq!(buf[plus].fg, Color::White);
}
#[test]
fn hovering_a_non_selected_activity_icon_emits_its_hovered_variant() {
use ratatui::layout::Rect;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Distinguishable payloads so the emitted set reveals which variant won.
app.overlays.activity.set_images(ActivityBarImages {
explorer_active: "EA".into(),
explorer_inactive: "EI".into(),
explorer_hovered: "EH".into(),
search_active: "SA".into(),
search_inactive: "SI".into(),
search_hovered: "SH".into(),
source_control_active: "CA".into(),
source_control_inactive: "CI".into(),
source_control_hovered: "CH".into(),
remote_active: "RA".into(),
remote_inactive: "RI".into(),
remote_hovered: "RH".into(),
run_debug_active: "DA".into(),
run_debug_inactive: "DI".into(),
run_debug_hovered: "DH".into(),
extensions_active: "XA".into(),
extensions_inactive: "XI".into(),
extensions_hovered: "XH".into(),
testing_active: "TA".into(),
testing_inactive: "TI".into(),
testing_hovered: "TH".into(),
codeql_active: "CA".into(),
codeql_inactive: "CI".into(),
codeql_hovered: "CH".into(),
settings_active: "GA".into(),
settings_inactive: "GI".into(),
settings_hovered: "GH".into(),
layout_sidebar_on: "LS".into(),
layout_sidebar_on_hover: "LSh".into(),
layout_sidebar_off: "LF".into(),
layout_sidebar_off_hover: "LFh".into(),
layout_panel_on: "LP".into(),
layout_panel_on_hover: "LPh".into(),
layout_panel_off: "LQ".into(),
layout_panel_off_hover: "LQh".into(),
layout_customize: "LC".into(),
layout_customize_hover: "LCh".into(),
});
// Every view icon needs a non-empty block or the emit early-returns.
app.sidebar_areas.explorer_icon = Rect::new(0, 0, 2, 1);
app.sidebar_areas.search_icon = Rect::new(0, 2, 2, 1);
app.sidebar_areas.source_control_icon = Rect::new(0, 4, 2, 1);
app.sidebar_areas.remote_icon = Rect::new(0, 6, 2, 1);
app.sidebar_areas.run_debug_icon = Rect::new(0, 8, 2, 1);
app.sidebar_areas.extensions_icon = Rect::new(0, 10, 2, 1);
app.sidebar_areas.testing_icon = Rect::new(0, 12, 2, 1);
app.sidebar_view = SidebarView::Explorer;
// Hover Search, a non-selected icon.
app.hovered_activity_icon = Some(ActivityIcon::Search);
let emitted: Vec<&str> = app
.pending_activity_image_overlays()
.into_iter()
.map(|(_, s)| s)
.collect();
assert!(
emitted.contains(&"SH"),
"the hovered search icon emits its hovered variant"
);
assert!(
!emitted.contains(&"SI"),
"search drops its resting variant while hovered"
);
assert!(
emitted.contains(&"EA"),
"the selected explorer view still wins with its active variant"
);
}
#[test]
fn moving_over_an_activity_icon_marks_it_hovered_and_redirties_the_overlay() {
use ratatui::layout::Rect;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_areas.search_icon = Rect::new(0, 4, 2, 2);
// Baseline: no hover, icons already emitted (clean).
app.hovered_activity_icon = None;
app.overlays.activity.mark_emitted();
assert!(!app.overlays.activity.dirty());
let moved = |col: u16, row: u16| crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Moved,
column: col,
row,
modifiers: KeyModifiers::NONE,
};
// Pointer enters the search icon (rows 4..6).
app.handle_mouse(moved(0, 5));
assert_eq!(app.hovered_activity_icon, Some(ActivityIcon::Search));
assert!(
app.overlays.activity.dirty(),
"entering an icon re-emits the swapped image"
);
// Drifting within the same icon costs nothing: no re-dirty.
app.overlays.activity.mark_emitted();
app.handle_mouse(moved(1, 4));
assert_eq!(app.hovered_activity_icon, Some(ActivityIcon::Search));
assert!(
!app.overlays.activity.dirty(),
"drifting within one icon does not re-emit"
);
// Leaving the bar clears the hover and re-emits the resting icon.
app.handle_mouse(moved(40, 20));
assert_eq!(app.hovered_activity_icon, None);
assert!(
app.overlays.activity.dirty(),
"leaving the icon re-emits its resting variant"
);
}
#[test]
fn dark_blue_theme_terminal_button_keeps_navy_chip() {
// Croft Dark keeps its coherent all-blue look: navy chip on the pane's
// add/close buttons, exactly as before the Black-theme restyle. (The pane
// no longer carries a TERMINAL title — the panel tab strip labels it.)
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.theme = crate::theme::Theme::DARK_BLUE;
app.sync_focus_flags();
let add = terminal_header_probe(&mut app);
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let navy = Color::Rgb(0x1e, 0x3a, 0x6e);
assert_eq!(buf[(add.x + 1, add.y)].bg, navy);
}
/// A long fixed note for the welcome-card tests: the live notes are rewritten
/// every version bump (`src/release_notes/<version>.md`), so pinning against
/// them would let a future one-line note quietly gut these tests. The distinctive final word is the
/// clip detector.
fn long_test_note() -> Vec<crate::release_notes::ReleaseNote> {
vec![crate::release_notes::ReleaseNote {
kind: crate::release_notes::NoteKind::Fix,
summary: "A deliberately long highlight that wraps across several rows at \
every sane width so the card's height measure and its paint pass \
are both exercised, ending in a distinctive final token that no \
other part of the interface paints: cardclip-endcap.",
}]
}
#[test]
fn welcome_release_note_never_clips_its_final_line() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.welcome.set_test_notes(long_test_note());
// Give the card room: with the sidebar and panel up, narrow widths
// height-starve the welcome area and the card clamps legitimately —
// that clamp is not what this test pins. Full-window welcome isolates
// the wrap arithmetic.
app.show_tree = false;
app.show_terminal = false;
// Sweep widths: the card clips only where the measure-time wrap and the
// paint-time wrap disagree on the line count, which is width-dependent.
for width in (60u16..=180).step_by(2) {
let backend = ratatui::backend::TestBackend::new(width, 50);
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");
// Skip widths where the card itself is absent (too narrow for
// the welcome stack) — only a partially painted card is a bug.
if !text.contains("deliberately") {
continue;
}
assert!(
text.contains("cardclip-endcap."),
"at {width} cols the release-note card clips its final line \
(measure and paint must wrap at the same width)"
);
}
}
#[test]
fn welcome_logo_shrinks_before_the_release_note_card_clips() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.welcome.set_test_notes(long_test_note());
// Default layout — sidebar and panel visible — at a common window size.
// The welcome area is height-starved here, and the logo must yield rows
// (down to its 4-row minimum) before the card is allowed to clip: a
// full-height logo above a release note cut off mid-sentence is the
// wrong trade (#99, observed at 140x40).
let backend = ratatui::backend::TestBackend::new(140, 40);
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("deliberately"),
"precondition: the release-note card must paint at 140x40"
);
assert!(
text.contains("cardclip-endcap."),
"at 140x40 the card clips its final line while the logo still \
occupies its maximum height — the logo must shrink first"
);
}
#[test]
fn status_transient_keeps_its_tail_when_longer_than_the_bar() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// A transient whose informative part is the tail, longer than the room
// left of the right cluster at 140 cols. The right cluster paints over
// the left paragraph, so an unelided message loses exactly its tail —
// for "Opened <deep absolute path>" that was the filename (#100).
let deep: String = "directory-segment/".repeat(7);
app.status = format!("Opened /{deep}main.rs");
let backend = ratatui::backend::TestBackend::new(140, 40);
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 last_row: String = (a.x..a.x + a.width)
.map(|x| buf[(x, a.y + a.height - 1)].symbol().to_string())
.collect();
assert!(
last_row.contains("main.rs"),
"an over-long status transient must middle-elide so its tail stays \
visible; the bar showed: {last_row:?}"
);
assert!(
last_row.contains("Ln 1, Col 1"),
"the right cluster must still paint: {last_row:?}"
);
}
#[test]
fn status_path_speaks_workspace_relative_inside_the_root() {
let tmp = tempfile::tempdir().unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
let inside = tmp.path().join("src").join("main.rs");
assert_eq!(
app.status_path(&inside),
format!("src{}main.rs", std::path::MAIN_SEPARATOR),
"paths under the workspace root must render root-relative, like tabs \
and breadcrumbs"
);
let outside = std::path::Path::new("/etc/hosts");
assert_eq!(
app.status_path(outside),
"/etc/hosts",
"paths outside the root keep their absolute form"
);
}
/// Render the app at 140x50 and clone the buffer for color probing.
fn render_buf(app: &mut App) -> ratatui::buffer::Buffer {
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
term.backend().buffer().clone()
}
fn count_bg(buf: &ratatui::buffer::Buffer, c: Color) -> usize {
let a = buf.area;
(a.y..a.y + a.height)
.flat_map(|y| (a.x..a.x + a.width).map(move |x| (x, y)))
.filter(|&(x, y)| buf[(x, y)].bg == c)
.count()
}
#[test]
fn black_theme_paints_no_legacy_navy_or_button_blue_in_any_sidebar_view() {
// The Black theme replaced the old blue accent with the brand teal, so
// no frame may keep the legacy navy chips (#1e3a6e) or the VS Code
// button blue (#0967b8): sidebar titles, remote header buttons, the
// active editor tab, and the Initialize / Run and Debug buttons all
// restyle together.
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("probe.txt");
std::fs::write(&f, "alpha\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
let navy = Color::Rgb(0x1e, 0x3a, 0x6e);
let button_blue = Color::Rgb(0x09, 0x67, 0xb8);
for view in [
SidebarView::Explorer,
SidebarView::Search,
SidebarView::SourceControl,
SidebarView::Remote,
SidebarView::RunDebug,
] {
app.sidebar_view = view;
let buf = render_buf(&mut app);
assert_eq!(
count_bg(&buf, navy),
0,
"legacy navy chip leaked into {view:?} under the Black theme"
);
assert_eq!(
count_bg(&buf, button_blue),
0,
"legacy button blue leaked into {view:?} under the Black theme"
);
}
}
#[test]
fn black_theme_sidebar_titles_are_chipless_brand_headers() {
use crate::gradient::{PANEL_TITLE_FG, rgb_color};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let buf = render_buf(&mut app);
let tree = app.tree.last_area;
assert_eq!(buf[(tree.x + 2, tree.y)].symbol(), "E");
assert_eq!(buf[(tree.x + 2, tree.y)].fg, rgb_color(PANEL_TITLE_FG));
app.sidebar_view = SidebarView::Remote;
let buf = render_buf(&mut app);
let remote = app.remote.last_area;
assert_eq!(buf[(remote.x + 2, remote.y)].symbol(), "R");
assert_eq!(buf[(remote.x + 2, remote.y)].fg, rgb_color(PANEL_TITLE_FG));
}
#[test]
fn black_theme_remote_header_buttons_are_near_white_icons() {
use crate::gradient::{PANEL_TITLE_FG, rgb_color};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_view = SidebarView::Remote;
let buf = render_buf(&mut app);
let add = app.remote.header_add_btn;
assert!(add.width > 0, "remote header add button must render");
// The snug pill paints the glyph at the rect origin (the highlight wraps
// exactly that one cell), so probe there rather than the rect centre.
// 863cc5c moved header view-action icons off the brand teal to the
// near-white PANEL_TITLE_FG, matching VS Code's light `icon.foreground`.
assert_eq!(buf[(add.x, add.y)].fg, rgb_color(PANEL_TITLE_FG));
}
#[test]
fn black_theme_active_editor_tab_wears_the_teal_selection_fill() {
use crate::gradient::{POPUP_SEL_BG, rgb_color};
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("probe.txt");
std::fs::write(&f, "alpha\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
let buf = render_buf(&mut app);
assert!(
count_bg(&buf, rgb_color(POPUP_SEL_BG)) > 0,
"active tab must wear the muted teal fill under the Black theme"
);
}
#[test]
fn black_theme_action_buttons_wear_the_brand_teal_fill() {
use crate::gradient::{PRIMARY_BTN_BG, rgb_color};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_view = SidebarView::SourceControl;
let buf = render_buf(&mut app);
let init = app.source_control.last_init_repo_button_area;
assert!(
init.width > 0,
"Initialize button must render outside a repo"
);
assert_eq!(
buf[(init.x + init.width / 2, init.y + init.height / 2)].bg,
rgb_color(PRIMARY_BTN_BG)
);
app.sidebar_view = SidebarView::RunDebug;
let buf = render_buf(&mut app);
let run = app.run_debug.last_button_area;
assert!(run.width > 0, "Run and Debug button must render");
assert_eq!(
buf[(run.x + run.width / 2, run.y + run.height / 2)].bg,
rgb_color(PRIMARY_BTN_BG)
);
}
#[test]
fn dark_blue_theme_keeps_the_legacy_blue_chrome() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("probe.txt");
std::fs::write(&f, "alpha\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.theme = crate::theme::Theme::DARK_BLUE;
app.sync_focus_flags();
app.editor.open_pinned(&f).unwrap();
let buf = render_buf(&mut app);
let navy = Color::Rgb(0x1e, 0x3a, 0x6e);
let tree = app.tree.last_area;
assert_eq!(
buf[(tree.x + 2, tree.y)].bg,
navy,
"EXPLORER chip stays navy"
);
assert!(count_bg(&buf, navy) > 0, "active tab stays navy");
app.sidebar_view = SidebarView::RunDebug;
let buf = render_buf(&mut app);
let run = app.run_debug.last_button_area;
assert_eq!(
buf[(run.x + run.width / 2, run.y + run.height / 2)].bg,
Color::Rgb(0x09, 0x67, 0xb8),
"Run and Debug button stays VS Code blue under Croft Dark"
);
}
// ---- New VS Code feature keybinding predicates ----
#[test]
fn command_palette_key_is_cmd_or_ctrl_shift_p() {
assert!(is_command_palette_key(key(
KeyCode::Char('p'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
assert!(is_command_palette_key(key(
KeyCode::Char('p'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT
)));
// Cmd+P (no Shift) is Quick Open, not the palette.
assert!(!is_command_palette_key(key(
KeyCode::Char('p'),
KeyModifiers::SUPER
)));
// Alt disqualifies it.
assert!(!is_command_palette_key(key(
KeyCode::Char('p'),
KeyModifiers::SUPER | KeyModifiers::SHIFT | KeyModifiers::ALT
)));
}
#[test]
fn go_to_symbol_key_is_cmd_or_ctrl_shift_o() {
assert!(is_go_to_symbol_key(key(
KeyCode::Char('o'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
assert!(is_go_to_symbol_key(key(
KeyCode::Char('o'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT
)));
// Cmd+O (no Shift) is open-line-below, not Go to Symbol.
assert!(!is_go_to_symbol_key(key(
KeyCode::Char('o'),
KeyModifiers::SUPER
)));
}
#[test]
fn open_line_above_relocated_from_cmd_shift_o_to_cmd_shift_enter() {
// The VS Code-correct chord: Cmd/Ctrl+Shift+Enter inserts a line above.
assert!(is_editor_open_line_above_key(key(
KeyCode::Enter,
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
assert!(is_editor_open_line_above_key(key(
KeyCode::Enter,
KeyModifiers::CONTROL | KeyModifiers::SHIFT
)));
// Cmd+Shift+O no longer triggers it (it now opens Go to Symbol).
assert!(!is_editor_open_line_above_key(key(
KeyCode::Char('o'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
}
#[test]
fn toggle_line_comment_key_is_cmd_or_ctrl_slash() {
assert!(is_toggle_line_comment_key(key(
KeyCode::Char('/'),
KeyModifiers::SUPER
)));
assert!(is_toggle_line_comment_key(key(
KeyCode::Char('/'),
KeyModifiers::CONTROL
)));
assert!(!is_toggle_line_comment_key(key(
KeyCode::Char('/'),
KeyModifiers::NONE
)));
assert!(!is_toggle_line_comment_key(key(
KeyCode::Char('/'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
}
#[test]
fn toggle_block_comment_key_is_shift_alt_a() {
assert!(is_toggle_block_comment_key(key(
KeyCode::Char('a'),
KeyModifiers::SHIFT | KeyModifiers::ALT
)));
assert!(is_toggle_block_comment_key(key(
KeyCode::Char('A'),
KeyModifiers::SHIFT | KeyModifiers::ALT
)));
// Alt alone (no Shift) is not the chord.
assert!(!is_toggle_block_comment_key(key(
KeyCode::Char('a'),
KeyModifiers::ALT
)));
// The command modifier disqualifies it.
assert!(!is_toggle_block_comment_key(key(
KeyCode::Char('a'),
KeyModifiers::SHIFT | KeyModifiers::ALT | KeyModifiers::SUPER
)));
}
#[test]
fn toggle_wrap_key_is_alt_z() {
assert!(is_toggle_wrap_key(key(
KeyCode::Char('z'),
KeyModifiers::ALT
)));
assert!(!is_toggle_wrap_key(key(
KeyCode::Char('z'),
KeyModifiers::ALT | KeyModifiers::SHIFT
)));
assert!(!is_toggle_wrap_key(key(
KeyCode::Char('z'),
KeyModifiers::NONE
)));
}
#[test]
fn cmd_shift_p_opens_command_palette() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.command_palette.is_none());
app.handle_key(key(
KeyCode::Char('p'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert!(
app.command_palette.is_some(),
"Cmd+Shift+P must open the command palette"
);
// Esc closes it.
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(app.command_palette.is_none());
}
#[test]
fn running_move_line_down_command_reorders_buffer() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.lines = vec!["a".to_string(), "b".to_string(), "c".to_string()];
app.editor.cursor_row = 0;
app.run_command(crate::widgets::command_palette::Command::MoveLineDown);
assert_eq!(app.editor.lines, vec!["b", "a", "c"]);
}
/// When a debug session ends after breakpoints were set but none was ever hit,
/// the feedback says so explicitly rather than the opaque "Debug session ended".
#[test]
fn debug_end_message_flags_a_program_that_exited_without_hitting_a_breakpoint() {
assert_eq!(
debug_end_message(true, false),
"Program exited without hitting a breakpoint"
);
// A breakpoint was hit (ever_stopped), or none were set: plain end message.
assert_eq!(debug_end_message(true, true), "Debug session ended");
assert_eq!(debug_end_message(false, false), "Debug session ended");
}
/// The debug console (program output) stays visible after the session ends, so a
/// fast-exiting program's output/errors aren't wiped before the user can read
/// them. A fresh idle panel (no ended session) shows no console.
#[test]
fn debug_console_is_retained_after_the_session_ends() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.debug_console = vec![String::from("hello from program"), String::from("all done")];
app.run_debug.session_ended = true;
app.refresh_debug_panel();
assert!(
app.run_debug
.console_tail
.contains(&String::from("all done")),
"the ended session's console output must stay visible"
);
// A fresh idle panel (never ran, or a new run reset the flag) shows nothing.
app.run_debug.session_ended = false;
app.refresh_debug_panel();
assert!(
app.run_debug.console_tail.is_empty(),
"the idle Run panel must not show stale console output"
);
}
#[test]
fn explorer_views_menu_omits_dependencies_in_a_folder_with_no_manifest() {
// A plain folder carries no package manifest, so the DEPENDENCIES view is
// not offered at all — mirroring how rust-analyzer's "Rust Dependencies"
// view simply does not exist outside a Rust project. The other four views
// are always available, each with a checkmark reflecting its visibility.
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("main.rs"), "fn main() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_explorer_views_menu();
let menu = app.context_menu.as_ref().expect("menu must open");
assert_eq!(
menu.items.len(),
ExplorerView::ALL.len() - 1,
"the Dependencies row is dropped when no manifest is present"
);
assert!(
!menu
.items
.iter()
.any(|e| menu_label(e).contains("Dependencies")),
"no dependency toggle in a manifest-less folder: {:?}",
menu.items
);
for entry in &menu.items {
let label = menu_label(entry);
let checked = label.starts_with('\u{2713}');
// Every listed row names an always-available view and its check glyph
// matches that view's current visibility.
let view = ExplorerView::ALL
.iter()
.find(|v| label.contains(v.label()))
.unwrap_or_else(|| panic!("unrecognized menu row {label:?}"));
assert_eq!(checked, app.explorer_views.is_visible(*view));
}
}
#[test]
fn explorer_views_menu_labels_dependencies_for_the_detected_ecosystem() {
// A Cargo workspace makes the DEPENDENCIES view appear, labeled for the
// detected ecosystem ("Rust Dependencies"), so the menu is language-aware
// rather than hardcoded.
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("Cargo.toml"),
"[package]\nname = \"x\"\nversion = \"0.1.0\"\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_explorer_views_menu();
let menu = app.context_menu.as_ref().expect("menu must open");
assert_eq!(menu.items.len(), ExplorerView::ALL.len());
assert!(
menu.items
.iter()
.any(|e| menu_label(e).contains("Rust Dependencies")),
"a Cargo root labels the view 'Rust Dependencies': {:?}",
menu.items
);
}
#[test]
fn toggling_an_explorer_view_flips_and_persists_its_visibility() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let before = app.explorer_views.is_visible(ExplorerView::Outline);
app.toggle_explorer_view(ExplorerView::Outline);
assert_eq!(
app.explorer_views.is_visible(ExplorerView::Outline),
!before,
"toggling Outline must flip its visibility"
);
}
// --- Customize Layout: pure chrome geometry -------------------------------
fn main_band() -> Rect {
Rect {
x: 0,
y: 0,
width: 100,
height: 30,
}
}
#[test]
fn chrome_left_position_orders_activity_primary_editor_secondary() {
let l = compute_chrome_layout(main_band(), true, true, true, SideBarPosition::Left, 20, 30);
let a = l.activity.expect("activity shown");
let p = l.primary_side.expect("primary shown");
let s = l.secondary_side.expect("secondary shown");
assert_eq!(a.x, 0, "activity bar hugs the left edge");
assert_eq!(a.width, ACTIVITY_BAR_WIDTH);
assert_eq!(
p.x,
a.x + a.width,
"primary side bar follows the activity bar"
);
assert_eq!(p.width, 20);
assert_eq!(
l.right.x,
p.x + p.width,
"editor follows the primary side bar"
);
assert_eq!(
s.x,
l.right.x + l.right.width,
"secondary is on the far right"
);
assert_eq!(
l.sidebar_splitter_x,
Some(l.right.x),
"seam is the editor's left edge"
);
// Every column tiles the band exactly, no gaps or overlaps.
assert_eq!(a.width + p.width + l.right.width + s.width, 100);
}
#[test]
fn chrome_right_position_mirrors_to_secondary_editor_primary_activity() {
let l = compute_chrome_layout(
main_band(),
true,
true,
true,
SideBarPosition::Right,
20,
30,
);
let s = l.secondary_side.expect("secondary shown");
let p = l.primary_side.expect("primary shown");
let a = l.activity.expect("activity shown");
assert_eq!(
s.x, 0,
"secondary hugs the left when the primary is on the right"
);
assert_eq!(l.right.x, s.x + s.width, "editor follows the secondary");
assert_eq!(
p.x,
l.right.x + l.right.width,
"primary side bar follows the editor"
);
assert_eq!(a.x, p.x + p.width, "activity bar is on the far right");
assert_eq!(
l.sidebar_splitter_x,
Some(p.x),
"seam is the editor's right edge"
);
assert_eq!(s.width + l.right.width + p.width + a.width, 100);
}
#[test]
fn chrome_hidden_regions_consume_no_width() {
let l = compute_chrome_layout(
main_band(),
false,
false,
false,
SideBarPosition::Left,
20,
30,
);
assert!(l.activity.is_none());
assert!(l.primary_side.is_none());
assert!(l.secondary_side.is_none());
assert_eq!(l.sidebar_splitter_x, None, "no seam without a side bar");
assert_eq!(l.right.x, 0, "editor reclaims the whole band");
assert_eq!(l.right.width, 100);
}
#[test]
fn chrome_narrow_frame_shrinks_primary_to_keep_editor_min() {
// activity(4) + primary wants 90 + editor needs RIGHT_PANE_MIN, in 100 wide.
let l = compute_chrome_layout(main_band(), true, true, false, SideBarPosition::Left, 90, 0);
assert_eq!(l.right.width, RIGHT_PANE_MIN, "editor keeps its minimum");
let p = l.primary_side.expect("primary still shown, just narrower");
assert_eq!(p.width, 100 - ACTIVITY_BAR_WIDTH - RIGHT_PANE_MIN);
}
#[test]
fn panel_band_center_and_justify_fill_the_band() {
let band = Rect {
x: 10,
y: 5,
width: 40,
height: 8,
};
assert_eq!(panel_band_rect(band, PanelAlignment::Center), band);
assert_eq!(panel_band_rect(band, PanelAlignment::Justify), band);
}
#[test]
fn panel_band_left_hugs_left_right_hugs_right() {
let band = Rect {
x: 10,
y: 5,
width: 60,
height: 8,
};
let left = panel_band_rect(band, PanelAlignment::Left);
assert_eq!(left.x, 10);
assert_eq!(left.width, 30);
let right = panel_band_rect(band, PanelAlignment::Right);
assert_eq!(
right.x,
10 + 60 - 30,
"right-aligned panel ends at the band's right edge"
);
assert_eq!(right.width, 30);
}
// --- Zen Mode snapshot / restore ------------------------------------------
#[test]
fn zen_mode_hides_all_chrome_then_restores_the_snapshot() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// A non-default starting layout so restore is meaningful.
app.show_tree = true;
app.show_terminal = false;
app.secondary_side_bar_visible = true;
app.activity_bar_visible = true;
app.status_bar_visible = true;
app.toggle_zen_mode();
assert!(app.zen_mode, "zen on");
assert!(!app.activity_bar_visible);
assert!(!app.status_bar_visible);
assert!(!app.show_tree);
assert!(!app.secondary_side_bar_visible);
assert!(!app.show_terminal);
app.toggle_zen_mode();
assert!(!app.zen_mode, "zen off");
assert!(app.show_tree, "restored prior side bar");
assert!(!app.show_terminal, "restored prior (hidden) panel");
assert!(
app.secondary_side_bar_visible,
"restored prior secondary bar"
);
assert!(app.activity_bar_visible);
assert!(app.status_bar_visible);
}
#[test]
fn secondary_side_bar_toggle_flips_visibility() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let before = app.secondary_side_bar_visible;
app.toggle_secondary_side_bar();
assert_eq!(app.secondary_side_bar_visible, !before);
}
#[test]
fn customize_layout_items_reflect_current_state_with_checks() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.activity_bar_visible = true;
app.status_bar_visible = false;
app.side_bar_position = SideBarPosition::Right;
app.panel_alignment = PanelAlignment::Justify;
let items = app.customize_layout_items();
// Activity Bar (on) gets a check; Status Bar (off) does not.
let activity = menu_label(&items[0]);
assert!(
activity.starts_with('\u{2713}'),
"Activity Bar checked: {activity}"
);
let status = menu_label(&items[4]);
assert!(
!status.starts_with('\u{2713}'),
"Status Bar unchecked: {status}"
);
// The active radio option carries the check.
let labels = menu_labels(&items);
assert!(
labels
.iter()
.any(|l| l.starts_with('\u{2713}') && l.contains("Right")),
"side-bar Right is checked"
);
assert!(
labels
.iter()
.any(|l| l.starts_with('\u{2713}') && l.contains("Justify")),
"panel Justify is checked"
);
}
#[test]
fn render_survives_every_customize_layout_combination() {
// Exercises the real render() path (not just the pure geometry) across the
// layout permutations so an out-of-bounds buffer write in any branch
// (side bar right, secondary bar, hidden chrome, every panel alignment)
// panics here rather than in front of the user.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let aligns = [
PanelAlignment::Left,
PanelAlignment::Center,
PanelAlignment::Right,
PanelAlignment::Justify,
];
for &pos in &[SideBarPosition::Left, SideBarPosition::Right] {
for &activity in &[true, false] {
for &secondary in &[true, false] {
for &status in &[true, false] {
for &align in &aligns {
app.side_bar_position = pos;
app.activity_bar_visible = activity;
app.secondary_side_bar_visible = secondary;
app.status_bar_visible = status;
app.panel_alignment = align;
for size in [(120u16, 40u16), (40, 12)] {
let backend = ratatui::backend::TestBackend::new(size.0, size.1);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).expect("render must not panic");
}
}
}
}
}
}
// And in Zen Mode (all chrome hidden) at a tiny size.
app.toggle_zen_mode();
let backend = ratatui::backend::TestBackend::new(30, 8);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f))
.expect("zen render must not panic");
}
#[test]
fn layout_toolbar_emits_2x_inline_images_reflecting_on_off_state() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mut imgs = dummy_activity_images();
imgs.layout_sidebar_on = "SIDE_ON".into();
imgs.layout_sidebar_on_hover = "SIDE_ON_H".into();
imgs.layout_sidebar_off = "SIDE_OFF".into();
imgs.layout_panel_on = "PANEL_ON".into();
imgs.layout_panel_off = "PANEL_OFF".into();
imgs.layout_customize = "CUSTOMIZE".into();
imgs.layout_customize_hover = "CUSTOMIZE_H".into();
app.overlays.activity.set_images(imgs);
// Place the toolbar (4 cells wide each), zero the activity bar so only the
// layout icons survive the width filter.
app.sidebar_areas = SidebarAreas::default();
app.layout_icon_areas = LayoutIconAreas {
toggle_side_bar: Rect::new(50, 0, LAYOUT_ICON_CELLS_W, LAYOUT_ICON_CELLS_H),
toggle_panel: Rect::new(55, 0, LAYOUT_ICON_CELLS_W, LAYOUT_ICON_CELLS_H),
customize: Rect::new(60, 0, LAYOUT_ICON_CELLS_W, LAYOUT_ICON_CELLS_H),
};
app.show_tree = true;
app.show_terminal = false;
app.pointer_cell = None;
let overlays = app.pending_activity_image_overlays();
// Side bar shown -> the filled (ON) image; panel hidden -> the hollow (OFF).
assert!(
overlays
.iter()
.any(|(pos, s)| *pos == (50, 0) && *s == "SIDE_ON"),
"side-bar icon emits the ON image when shown"
);
assert!(
overlays
.iter()
.any(|(pos, s)| *pos == (55, 0) && *s == "PANEL_OFF"),
"panel icon emits the OFF image when hidden"
);
assert!(
overlays
.iter()
.any(|(pos, s)| *pos == (60, 0) && *s == "CUSTOMIZE"),
"customize icon always emits its image"
);
// Pointer over the customize icon -> the brighter hover variant.
app.pointer_cell = Some((61, 0));
let overlays = app.pending_activity_image_overlays();
assert!(
overlays
.iter()
.any(|(pos, s)| *pos == (60, 0) && *s == "CUSTOMIZE_H"),
"customize icon emits the hover image under the pointer"
);
assert!(
overlays
.iter()
.any(|(pos, s)| *pos == (50, 0) && *s == "SIDE_ON"),
"a non-hovered icon keeps its resting image"
);
// Pointer over the side-bar icon, side bar shown -> the ON hover variant.
app.pointer_cell = Some((51, 0));
let overlays = app.pending_activity_image_overlays();
assert!(
overlays
.iter()
.any(|(pos, s)| *pos == (50, 0) && *s == "SIDE_ON_H"),
"side-bar icon emits the ON hover image under the pointer"
);
// Flip both visibilities: the images swap to match.
app.pointer_cell = None;
app.show_tree = false;
app.show_terminal = true;
let overlays = app.pending_activity_image_overlays();
assert!(
overlays
.iter()
.any(|(p, s)| *p == (50, 0) && *s == "SIDE_OFF")
);
assert!(
overlays
.iter()
.any(|(p, s)| *p == (55, 0) && *s == "PANEL_ON")
);
}
#[test]
fn clicking_the_customize_icon_opens_the_customize_layout_popup() {
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 cust = app.layout_icon_areas.customize;
assert!(cust.width > 0, "the customize icon must be laid out");
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
column: cust.x,
row: cust.y,
modifiers: KeyModifiers::NONE,
});
let menu = app.context_menu.as_ref().expect("customize popup opens");
assert!(
matches!(
menu.items.first(),
Some(MenuEntry::Item {
action: MenuAction::ToggleActivityBar,
..
})
),
"the popup is the Customize Layout menu"
);
// And the icon advertises itself on hover.
assert_eq!(app.ui_tooltip_at(cust.x, cust.y), Some("Customize Layout"));
}
#[test]
fn clicking_the_side_bar_icon_toggles_the_primary_side_bar() {
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 side = app.layout_icon_areas.toggle_side_bar;
assert!(side.width > 0);
let before = app.show_tree;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
column: side.x,
row: side.y,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.show_tree, !before, "the side-bar icon flips show_tree");
}
#[test]
fn secondary_sidebar_chord_is_alt_cmd_b_not_plain_cmd_b() {
assert!(is_secondary_sidebar_toggle_key(key(
KeyCode::Char('b'),
KeyModifiers::SUPER | KeyModifiers::ALT
)));
assert!(!is_secondary_sidebar_toggle_key(key(
KeyCode::Char('b'),
KeyModifiers::SUPER
)));
// Plain Cmd+B stays the PRIMARY side-bar toggle, never the secondary.
assert!(!is_sidebar_toggle_key(key(
KeyCode::Char('b'),
KeyModifiers::SUPER | KeyModifiers::ALT
)));
}
#[test]
fn unsaved_count_tracks_dirty_editors() {
// The Explorer activity badge mirrors VS Code: the count of open editors
// with unsaved edits. A freshly-opened blank buffer is clean; one edit
// makes it count as a single unsaved file.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert_eq!(app.unsaved_count(), 0, "a fresh blank buffer is clean");
app.editor.insert_char('x');
assert_eq!(
app.unsaved_count(),
1,
"an edited buffer counts as one unsaved file"
);
}
fn sym(
name: &str,
kind: crate::lsp::manager::OutlineKind,
depth: u16,
start: u32,
end: u32,
) -> crate::lsp::manager::OutlineSymbol {
crate::lsp::manager::OutlineSymbol {
name: name.to_string(),
detail: None,
kind,
depth,
line: start,
character: 0,
range_start_line: start,
range_end_line: end,
}
}
#[test]
fn breadcrumb_symbol_chain_returns_enclosing_symbols_outermost_first() {
use crate::lsp::manager::OutlineKind;
let symbols = vec![
sym("Widget", OutlineKind::Class, 0, 0, 20),
sym("build", OutlineKind::Method, 1, 2, 8),
sym("paint", OutlineKind::Method, 1, 10, 18),
];
// Caret on line 4 sits inside Widget::build.
let chain = breadcrumb_symbol_chain(&symbols, 4);
assert_eq!(chain, vec![0, 1], "outermost (Widget) then inner (build)");
// Caret on line 15 sits inside Widget::paint.
assert_eq!(breadcrumb_symbol_chain(&symbols, 15), vec![0, 2]);
// Caret on line 0 (the class header) is inside the class only.
assert_eq!(breadcrumb_symbol_chain(&symbols, 0), vec![0]);
// Caret past every symbol has no scope chain.
assert!(breadcrumb_symbol_chain(&symbols, 30).is_empty());
}
#[test]
fn cmd_d_selects_word_then_adds_the_next_match_as_a_caret() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("a.rs");
std::fs::write(&f, "foo foo foo\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_col = 1; // inside the first "foo"
app.handle_key(key(KeyCode::Char('d'), KeyModifiers::SUPER))
.unwrap();
assert!(
app.editor.selection.is_some() && !app.editor.has_multi_cursor(),
"first Cmd+D selects the word only"
);
app.handle_key(key(KeyCode::Char('d'), KeyModifiers::SUPER))
.unwrap();
assert!(
app.editor.has_multi_cursor(),
"second Cmd+D adds the next match as a caret"
);
}
#[test]
fn cmd_shift_k_deletes_the_current_line() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("a.rs");
std::fs::write(&f, "one\ntwo\nthree\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 1; // the "two" line
app.handle_key(key(
KeyCode::Char('k'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert_eq!(
app.editor.lines,
vec!["one".to_string(), "three".to_string()],
"Cmd+Shift+K removes the cursor's line"
);
}
#[test]
fn build_sticky_lines_pins_enclosing_headers_scrolled_above_the_viewport() {
use crate::lsp::manager::OutlineKind;
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("m.rs");
std::fs::write(&f, "x\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
app.outline.set_symbols(
f.clone(),
vec![
sym("Widget", OutlineKind::Class, 0, 0, 40),
sym("build", OutlineKind::Method, 1, 10, 30),
],
);
// Scrolled deep inside build: both the class and method headers are above.
app.editor.scroll = 20;
assert_eq!(app.build_sticky_lines(), vec![0, 10], "outermost first");
// Scrolled inside the class but above the method: only the class pins.
app.editor.scroll = 5;
assert_eq!(app.build_sticky_lines(), vec![0]);
// Parked on the class header itself: nothing is scrolled off, so no pins.
app.editor.scroll = 0;
assert!(app.build_sticky_lines().is_empty());
}
#[test]
fn build_breadcrumbs_lists_path_segments_then_the_symbol_chain() {
use crate::lsp::manager::OutlineKind;
let tmp = tempfile::tempdir().unwrap();
let sub = tmp.path().join("src");
std::fs::create_dir_all(&sub).unwrap();
let f = sub.join("m.rs");
std::fs::write(&f, "fn a() {}\nfn b() {\n x\n}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
app.outline
.set_symbols(f.clone(), vec![sym("b", OutlineKind::Function, 0, 1, 3)]);
app.editor.cursor_row = 2; // inside fn b
let crumbs = app.build_breadcrumbs();
let labels: Vec<&str> = crumbs.iter().map(|c| c.label.as_str()).collect();
assert_eq!(labels, vec!["src", "m.rs", "b"]);
assert_eq!(crumbs[0].target, None, "path crumbs are informational");
assert_eq!(
crumbs[2].target,
Some((1, 0)),
"symbol crumb jumps to itself"
);
}
#[test]
fn toggle_format_on_save_command_flips_the_pref_and_reports_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.format_on_save = false;
app.run_command(crate::widgets::command_palette::Command::ToggleFormatOnSave);
assert!(app.format_on_save, "the command turns format-on-save on");
assert!(app.status.contains("on") || app.status.contains("On"));
app.run_command(crate::widgets::command_palette::Command::ToggleFormatOnSave);
assert!(!app.format_on_save, "the command toggles it back off");
}
#[test]
fn format_on_save_eligible_requires_pref_and_formatter_and_code_file() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("m.py");
std::fs::write(&f, "x=1\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
// Pref off: never eligible, even when a formatter is available.
app.format_on_save = false;
assert!(!app.format_on_save_eligible(true));
// Pref on but no formatter advertised: not eligible (would hang the save).
app.format_on_save = true;
assert!(!app.format_on_save_eligible(false));
// Pref on + formatter + a real code file: eligible.
assert!(app.format_on_save_eligible(true));
}
#[test]
fn a_second_save_while_a_format_is_in_flight_still_writes_the_first_file() {
// The latch holds ONE path and the manager tracks one format request id,
// so arming a second file abandons the first reply. Overwriting the latch
// therefore lost the first save outright: a.py stayed dirty and unwritten,
// with no error and no status.
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.py");
let b = tmp.path().join("b.py");
std::fs::write(&a, "a=1\n").unwrap();
std::fs::write(&b, "b=1\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.editor.insert_char('X');
app.arm_deferred_save(); // Cmd+S on a.py
// The user moves on and saves the other file before the first reply lands.
app.editor.open_pinned(&b).unwrap();
app.editor.insert_char('Y');
app.arm_deferred_save(); // Cmd+S on b.py
assert!(
std::fs::read_to_string(&a).unwrap().starts_with('X'),
"a.py's save must survive the second Cmd+S, got {:?}",
std::fs::read_to_string(&a).unwrap()
);
// b.py is still deferred, waiting on its own format reply.
assert_eq!(app.save_after_format.as_deref(), Some(b.as_path()));
app.complete_pending_save();
assert!(
std::fs::read_to_string(&b).unwrap().starts_with('Y'),
"and b.py lands when its reply arrives"
);
}
#[test]
fn a_deferred_format_save_writes_the_file_it_was_asked_to_save() {
// `save()` armed a bare bool and returned; the write happened later, from
// the format reply, through `write_current_to_disk` — which saves the
// ACTIVE tab. Switching tabs while the formatter thought left the file the
// user pressed Cmd+S on unwritten and still dirty, and wrote the other tab
// instead, snapshot and didSave included.
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.py");
let b = tmp.path().join("b.py");
std::fs::write(&a, "a=1\n").unwrap();
std::fs::write(&b, "b=1\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.editor.insert_char('X');
app.save_after_format = Some(a.clone());
// The formatter is still thinking; the user moves to the other file.
app.editor.open_pinned(&b).unwrap();
app.editor.insert_char('Y');
assert_eq!(
app.editor.path.as_deref(),
Some(b.as_path()),
"b.py is active"
);
app.complete_pending_save();
assert!(
std::fs::read_to_string(&a).unwrap().starts_with('X'),
"the file the save was asked for must be written, got {:?}",
std::fs::read_to_string(&a).unwrap()
);
assert_eq!(
std::fs::read_to_string(&b).unwrap(),
"b=1\n",
"the tab that merely happened to be active must NOT be written"
);
}
#[test]
fn complete_pending_save_writes_formatted_buffer_to_disk() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("m.py");
std::fs::write(&f, "x=1\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
// Simulate a format edit landing in the buffer, then the deferred save
// firing when the format response arrives.
app.editor.insert_char('y');
app.save_after_format = Some(f.clone());
app.complete_pending_save();
assert!(
app.save_after_format.is_none(),
"the deferred-save latch is consumed"
);
let on_disk = std::fs::read_to_string(&f).unwrap();
assert!(
on_disk.starts_with('y'),
"the buffer was written to disk, got {on_disk:?}"
);
// With the latch clear, a second call is a no-op (no re-save).
app.editor.insert_char('z');
app.complete_pending_save();
let unchanged = std::fs::read_to_string(&f).unwrap();
assert_eq!(unchanged, on_disk, "no write without the latch set");
}
#[test]
fn minimap_edit_rebakes_in_place_but_a_moved_strip_arms_the_clear() {
// Issue: every keystroke bumped `edit_seq`, the minimap layout signature
// mismatched, and `update_minimap_overlay` armed the full-screen clear
// latch - so the whole app blinked on every edit (a 2J + full redraw is
// one visible round trip over SSH). A content-only change re-emits the
// raster over the SAME cells (fixed Kitty id / same-cell OSC-1337 emit
// replaces in place), so only a moved or resized strip may arm the clear.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.cell_pixel = Some((8, 16));
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
app.editor.lines = (0..80).map(|i| format!("line {i}")).collect();
let strip = ratatui::layout::Rect {
x: 100,
y: 1,
width: 6,
height: 40,
};
app.update_minimap_overlay(strip);
assert!(app.minimap_image_payload().is_some(), "minimap must bake");
let _ = app.consume_minimap_image_clear();
app.mark_minimap_image_displayed();
app.editor.lines.push(String::from("one more line"));
app.editor.edit_seq += 1;
app.update_minimap_overlay(strip);
assert!(
!app.consume_minimap_image_clear(),
"a content-only minimap change must replace the image in place, not blank the screen"
);
assert!(
app.minimap_image_payload().is_some(),
"the rebaked raster must still be there to re-emit"
);
app.mark_minimap_image_displayed();
let moved = ratatui::layout::Rect { x: 60, ..strip };
app.update_minimap_overlay(moved);
assert!(
app.consume_minimap_image_clear(),
"a moved minimap strip must arm the eviction clear so no ghost remains"
);
}
#[test]
fn an_open_context_menu_hides_the_minimap_raster() {
// The raster is emitted at Kitty z=0 (above text) AFTER ratatui's diff, on
// every frame. The minimap's own right-click menu is anchored on the strip,
// so without a gate the raster paints back over the menu the user just
// opened. `cb0481b` fixed the same collision for the welcome logo. The gate
// has to be rect-precise, not "any menu is open": arming the clear latch
// for a menu elsewhere wipes and repaints the whole screen on the
// cell-buffer protocols.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.cell_pixel = Some((8, 16));
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
app.editor.lines = (0..80).map(|i| format!("line {i}")).collect();
let strip = ratatui::layout::Rect {
x: 100,
y: 1,
width: 6,
height: 40,
};
app.update_minimap_overlay(strip);
assert!(app.minimap_image_payload().is_some(), "minimap must bake");
let _ = app.consume_minimap_image_clear();
app.mark_minimap_image_displayed();
app.open_minimap_menu(102, 5);
app.update_minimap_overlay(strip);
assert!(
app.minimap_image_payload().is_none(),
"no re-emit while a menu covers the strip, or it repaints over the menu"
);
assert!(
app.consume_minimap_image_clear(),
"and the placed image must be evicted, not left on the Kitty layer"
);
app.context_menu = None;
app.update_minimap_overlay(strip);
assert!(
app.minimap_image_payload().is_some(),
"the minimap comes back once the menu closes"
);
// A menu is clamped to the frame, not snapped to its right edge, so a
// right-click far from the strip never reaches it.
app.mark_minimap_image_displayed();
app.open_minimap_menu(2, 5);
app.update_minimap_overlay(strip);
assert!(
app.minimap_image_payload().is_some(),
"a menu nowhere near the strip must leave the minimap alone"
);
assert!(
!app.consume_minimap_image_clear(),
"and must not arm the screen-wiping clear latch"
);
}
#[test]
fn relay_request_ids_are_unique_per_request() {
// `Instant::now().elapsed()` measures the gap between an instant and
// itself, so the id was `<kind>-<pid>-0` almost every time. The relay keys
// its remote inbox directory by request id, so two requests raised in the
// same second collided: the first reply satisfied both pending pulls and
// deleted the directory out from under the second, which then timed out
// 120s later - with its file already destroyed or its tunnel already up.
let ids: Vec<String> = (0..64).map(|_| App::relay_request_id("forward")).collect();
let unique: std::collections::HashSet<&String> = ids.iter().collect();
assert_eq!(unique.len(), ids.len(), "every request id must be distinct");
assert!(ids[0].starts_with("forward-"), "kind stays in the id");
}
#[test]
fn image_eviction_wipes_the_screen_only_on_cell_buffer_protocols() {
// The `terminal.clear()` the main loop fires when an image-clear latch is
// armed exists to evict CACHED IMAGE CELLS: iTerm2 OSC-1337 and sixel
// graphics live in the normal cell buffer, so only a `2J` removes them.
// Kitty graphics live on their own layer and are deleted by
// `evict_inline_images_on_clear` (delete-all-by-escape) without touching a
// single text cell - wiping the screen there blanks the whole app for a
// full SSH round trip on every latch (the "croft blinks while I type" bug).
use crate::iterm2_inline::InlineImageProtocol;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.inline_protocol = InlineImageProtocol::Kitty;
assert!(
!app.image_eviction_needs_screen_wipe(),
"Kitty images are deleted on their own layer; the text buffer must stay intact"
);
app.inline_protocol = InlineImageProtocol::ITerm2;
assert!(app.image_eviction_needs_screen_wipe());
app.inline_protocol = InlineImageProtocol::Sixel;
assert!(app.image_eviction_needs_screen_wipe());
app.inline_protocol = InlineImageProtocol::None;
assert!(app.image_eviction_needs_screen_wipe());
}
#[test]
fn resize_must_force_a_full_text_repaint_on_every_protocol() {
// dtach reattaches with `-r winch` precisely so the app repaints: after a
// reattach the physical screen is blank while ratatui's back buffer still
// says every cell is painted, so the diff alone emits nothing and only
// later-changing cells (status bar, cursor) ever appear - the "remote
// croft comes back all black" bug. The image-eviction wipe used to cover
// this by accident; Kitty skips that wipe (the typing-blink fix), so a
// WINCH must arm its own unconditional repaint.
use crate::iterm2_inline::InlineImageProtocol;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.inline_protocol = InlineImageProtocol::Kitty;
assert!(
!app.consume_resize_repaint(),
"no repaint owed before any resize"
);
app.on_resize();
assert!(
app.consume_resize_repaint(),
"a WINCH must force the full text repaint even where image eviction skips the wipe"
);
assert!(
!app.consume_resize_repaint(),
"the resize repaint latch is one-shot"
);
}
#[test]
fn drag_reorders_terminal_panes_and_active_follows_its_terminal() {
// Dragging a pane label (side-by-side) or a rail row (maximize mode)
// live-moves that terminal to the hovered slot. The reorder must keep
// `active_terminal` pinned to the same underlying terminal: the dragged
// pane stays active while it moves, and an unrelated active pane must not
// silently switch because its index shifted.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
app.split_terminal().unwrap();
for (i, name) in ["one", "two", "three"].iter().enumerate() {
app.terminals[i].set_manual_name(Some(name.to_string()));
}
app.active_terminal = 0;
app.move_terminal(0, 2);
let order: Vec<&str> = app.terminals.iter().map(|t| t.label()).collect();
assert_eq!(order, ["two", "three", "one"], "pane moved to the far slot");
assert_eq!(app.active_terminal, 2, "the dragged pane stays active");
app.active_terminal = 1; // "three"
app.move_terminal(2, 0); // drag "one" back to the front
let order: Vec<&str> = app.terminals.iter().map(|t| t.label()).collect();
assert_eq!(order, ["one", "two", "three"]);
assert_eq!(
app.terminals[app.active_terminal].label(),
"three",
"an unrelated active pane keeps its terminal when indices shift"
);
// Out-of-range and no-op moves must not disturb anything.
app.move_terminal(1, 1);
app.move_terminal(9, 0);
app.move_terminal(0, 9);
let order: Vec<&str> = app.terminals.iter().map(|t| t.label()).collect();
assert_eq!(order, ["one", "two", "three"]);
}
#[test]
fn a_semantic_token_reply_older_than_the_applied_one_is_dropped() {
// Two full requests can be in flight for one path at the SAME seq
// (sync_lsp plus a server-driven refresh), and the request retry loop
// emits an empty batch once its backoff runs out. Ordering by request
// generation is what stops that late empty loser from blanking a good
// overlay and being persisted to the content-keyed cache.
assert!(
crate::app::semantic_reply_is_current(None, 7),
"the first reply for a path always applies"
);
assert!(crate::app::semantic_reply_is_current(Some(7), 8));
assert!(
crate::app::semantic_reply_is_current(Some(7), 7),
"the same request re-delivered is not stale"
);
assert!(
!crate::app::semantic_reply_is_current(Some(8), 7),
"a reply from an older request must never overwrite a newer one"
);
}
#[test]
fn reordering_panes_defers_the_session_write_off_the_input_path() {
// move_terminal runs once per motion report during a drag. A full
// read-modify-write of the session file — plus a cwd syscall and a stat
// per pane — on each one violates the input-latency invariant, so the
// write is marked and flushed once per tick instead.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// The test-mode session path is per PROCESS, shared by every test in
// this binary: a concurrent test's save would recreate the file between
// the remove below and the non-existence assert. Absence is only
// provable on a path this test owns alone.
app.terminal_session_path = tmp.path().join("terminal-sessions.json");
app.split_terminal().unwrap();
let _ = std::fs::remove_file(&app.terminal_session_path);
app.move_terminal(0, 1);
assert!(
!app.terminal_session_path.exists(),
"the session write must not sit on the input path"
);
assert!(
app.terminal_session_dirty,
"the move is recorded as pending"
);
app.flush_terminal_session();
assert!(
app.terminal_session_path.exists(),
"the deferred write lands on the flush"
);
assert!(!app.terminal_session_dirty);
}
#[test]
fn a_drag_held_over_one_pane_does_not_flip_flop_between_frames() {
// The main loop drains the whole queued mouse burst before drawing, so
// several Drag events land with no redraw between them. Hit-testing
// must stay POSITIONAL across a move: `last_area` travels with the
// terminal object, so if the rects are not re-seated per slot, the
// second event swaps the panes straight back and the final order is
// the parity of how many motion reports the terminal happened to emit.
use crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
app.split_terminal().unwrap();
for (i, name) in ["one", "two", "three"].iter().enumerate() {
app.terminals[i].set_manual_name(Some(name.to_string()));
}
let backend = ratatui::backend::TestBackend::new(180, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let mouse = |kind, x: u16, y: u16| MouseEvent {
kind,
column: x,
row: y,
modifiers: KeyModifiers::NONE,
};
let grab = app.terminal_label_rects[0];
let dest = app.terminals[1].last_area;
let (dx, dy) = (dest.x + dest.width / 2, dest.y + dest.height / 2);
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
grab.x + 1,
grab.y,
));
// Four motion reports over the same cell, no redraw in between.
for _ in 0..4 {
app.handle_mouse(mouse(MouseEventKind::Drag(MouseButton::Left), dx, dy));
}
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), dx, dy));
let order: Vec<&str> = app
.terminals
.iter()
.map(|t| t.manual_name().unwrap_or(""))
.collect();
assert_eq!(
order,
vec!["two", "one", "three"],
"the pane must settle where the pointer is, whatever the event count"
);
}
#[test]
fn dragging_a_pane_label_and_a_rail_row_reorders_terminals_end_to_end() {
// Full wiring pass over real hit rects: render a frame, press the first
// pane's name pill, drag into the third pane, release - the terminal
// must land in the far slot. Then the same through the maximize rail.
use crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.split_terminal().unwrap();
app.split_terminal().unwrap();
for (i, name) in ["one", "two", "three"].iter().enumerate() {
app.terminals[i].set_manual_name(Some(name.to_string()));
}
let backend = ratatui::backend::TestBackend::new(180, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let mouse = |kind, x: u16, y: u16| MouseEvent {
kind,
column: x,
row: y,
modifiers: KeyModifiers::NONE,
};
let grab = app.terminal_label_rects[0];
assert!(grab.width > 0, "pane label pill must record a drag handle");
let dest = app.terminals[2].last_area;
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
grab.x + 1,
grab.y,
));
let (dx, dy) = (dest.x + dest.width / 2, dest.y + 2);
app.handle_mouse(mouse(MouseEventKind::Drag(MouseButton::Left), dx, dy));
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), dx, dy));
let order: Vec<&str> = app.terminals.iter().map(|t| t.label()).collect();
assert_eq!(order, ["two", "three", "one"], "label drag moves the pane");
assert_eq!(app.active_terminal, 2, "the dragged pane lands focused");
// Maximize mode: drag the top rail row onto the bottom one.
app.terminal_pane_maximized = true;
term.draw(|f| app.render(f)).unwrap();
let from_row = app.terminal_rail_rects[0];
let to_row = app.terminal_rail_rects[2];
assert!(from_row.width > 0 && to_row.width > 0, "rail rows painted");
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
from_row.x + 1,
from_row.y,
));
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
to_row.x + 1,
to_row.y,
));
app.handle_mouse(mouse(
MouseEventKind::Up(MouseButton::Left),
to_row.x + 1,
to_row.y,
));
let order: Vec<&str> = app.terminals.iter().map(|t| t.label()).collect();
assert_eq!(order, ["three", "one", "two"], "rail drag moves the row");
}
#[test]
fn stale_document_symbol_reply_must_not_replace_the_fresher_outline() {
// While typing on a slow language server, `documentSymbol` replies land
// several edits behind the buffer. Applying one replaces the fresh
// tree-sitter outline with ranges that no longer contain the caret, the
// breadcrumb's symbol crumb drops off, and the next keystroke restores it:
// the "hello_there blinks in the breadcrumb" bug. A reply is only valid
// when it answers the NEWEST request (same path, same edit seq).
use crate::lsp::manager::{OutlineKind, OutlineSymbol};
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("demo.rs");
std::fs::write(
&file,
"fn hello_there() {\n let a = 1;\n let b = 2;\n}\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_file_at_launch(&file);
// The LSP manager tracks this file at edit seq 7; the newest outline
// request was issued for that seq.
app.lsp_last_seen.insert(file.clone(), 7);
app.sync_outline();
assert!(
app.outline
.symbols()
.iter()
.any(|s| s.name == "hello_there"),
"tree-sitter must have painted the fresh outline"
);
let stale_symbol = OutlineSymbol {
name: String::from("hello_there"),
detail: None,
kind: OutlineKind::Function,
depth: 0,
line: 0,
character: 3,
range_start_line: 0,
range_end_line: 0, // ranges from an older buffer: caret now outside
};
let applied = app.apply_outline_symbols(file.clone(), 3, vec![stale_symbol.clone()]);
assert!(
!applied,
"a documentSymbol reply for an older edit seq must be dropped, not applied"
);
assert!(
app.outline
.symbols()
.iter()
.any(|s| s.name == "hello_there" && s.range_end_line >= 3),
"the fresh tree-sitter ranges must survive the stale reply"
);
// The reply answering the newest request (seq 7) refines the outline.
let applied = app.apply_outline_symbols(file.clone(), 7, vec![stale_symbol]);
assert!(applied, "the reply matching the newest request must apply");
}
// --- Increment / Decrement Number ------------------------------------------
/// The Cmd+Opt+= / Cmd+Opt+- chords as crossterm decodes them (ALT|SUPER on
/// macOS; Ctrl+Alt on Linux arrives as ALT|CONTROL, which the predicate
/// accepts too).
#[test]
fn the_increment_chord_bumps_the_number_under_the_cursor() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "port = 8080");
app.editor.cursor_col = 8;
app.handle_key(key(
KeyCode::Char('='),
KeyModifiers::ALT | KeyModifiers::SUPER,
))
.unwrap();
assert_eq!(app.editor.lines, vec!["port = 8081"]);
}
#[test]
fn the_decrement_chord_bumps_the_number_down() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "port = 8080");
app.editor.cursor_col = 8;
app.handle_key(key(
KeyCode::Char('-'),
KeyModifiers::ALT | KeyModifiers::CONTROL,
))
.unwrap();
assert_eq!(app.editor.lines, vec!["port = 8079"]);
}
/// A chord that finds nothing to bump must say so rather than looking like
/// a dead key.
#[test]
fn the_increment_chord_explains_itself_when_there_is_no_number() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "let name = value;");
app.handle_key(key(
KeyCode::Char('='),
KeyModifiers::ALT | KeyModifiers::SUPER,
))
.unwrap();
assert_eq!(app.editor.lines, vec!["let name = value;"]);
assert!(
app.status.contains("No number"),
"status should explain the no-op, got {:?}",
app.status
);
}
// --- Bookmarks ------------------------------------------------------------
#[test]
fn bookmark_chords_are_disjoint_from_the_chords_they_sit_beside() {
// Toggle is Cmd+Opt+Shift+K; plain Cmd+Shift+K is still Delete Line.
assert!(is_toggle_bookmark_key(key(
KeyCode::Char('k'),
KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT
)));
assert!(!is_delete_line_key(key(
KeyCode::Char('k'),
KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT
)));
assert!(!is_toggle_bookmark_key(key(
KeyCode::Char('k'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
// Next/previous are Cmd+Opt+. and Cmd+Opt+, — Quick Fix (Cmd+.) excludes
// Alt, so the two dot chords never fire together.
assert!(is_next_bookmark_key(key(
KeyCode::Char('.'),
KeyModifiers::SUPER | KeyModifiers::ALT
)));
assert!(!is_quick_fix_key(key(
KeyCode::Char('.'),
KeyModifiers::SUPER | KeyModifiers::ALT
)));
assert!(!is_next_bookmark_key(key(
KeyCode::Char('.'),
KeyModifiers::SUPER
)));
assert!(is_prev_bookmark_key(key(
KeyCode::Char(','),
KeyModifiers::CONTROL | KeyModifiers::ALT
)));
assert!(!is_prev_bookmark_key(key(
KeyCode::Char(','),
KeyModifiers::ALT
)));
}
// --- Emmet: Expand Abbreviation -------------------------------------------
#[test]
fn cmd_opt_shift_e_is_the_emmet_expand_chord() {
assert!(is_emmet_expand_key(key(
KeyCode::Char('e'),
KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT
)));
// Termux / Linux forward SUPER as CONTROL.
assert!(is_emmet_expand_key(key(
KeyCode::Char('e'),
KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT
)));
// Each modifier is load-bearing: dropping any one must not expand.
assert!(!is_emmet_expand_key(key(
KeyCode::Char('e'),
KeyModifiers::SUPER | KeyModifiers::ALT
)));
assert!(!is_emmet_expand_key(key(
KeyCode::Char('e'),
KeyModifiers::SUPER | KeyModifiers::SHIFT
)));
assert!(!is_emmet_expand_key(key(
KeyCode::Char('e'),
KeyModifiers::NONE
)));
// And it is the E chord specifically, not any Cmd+Opt+Shift letter.
assert!(!is_emmet_expand_key(key(
KeyCode::Char('w'),
KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT
)));
}
#[test]
fn the_toggle_chord_marks_the_cursor_line_and_says_so() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "notes.rs", "a\nb\nc\nd\n");
app.editor.cursor_row = 2;
app.handle_editor_key(key(
KeyCode::Char('k'),
KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
));
assert_eq!(app.editor.bookmarked_lines(), vec![3]);
assert!(
app.status.contains("line 3"),
"the status must name the line; was {:?}",
app.status
);
}
#[test]
fn the_navigation_chords_move_the_cursor_between_marks() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "notes.rs", "1\n2\n3\n4\n5\n6\n");
for row in [1, 4] {
app.editor.cursor_row = row;
app.editor.toggle_bookmark();
}
app.editor.cursor_row = 0;
app.handle_editor_key(key(
KeyCode::Char('.'),
KeyModifiers::SUPER | KeyModifiers::ALT,
));
assert_eq!(app.editor.cursor_row, 1);
app.handle_editor_key(key(
KeyCode::Char('.'),
KeyModifiers::SUPER | KeyModifiers::ALT,
));
assert_eq!(app.editor.cursor_row, 4);
app.handle_editor_key(key(
KeyCode::Char(','),
KeyModifiers::SUPER | KeyModifiers::ALT,
));
assert_eq!(app.editor.cursor_row, 1);
}
#[test]
fn bookmark_status_counts_marks_and_names_the_line_separately() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "notes.rs", "1\n2\n3\n4\n5\n6\n");
for row in [1, 4] {
app.editor.cursor_row = row;
app.editor.toggle_bookmark();
}
app.editor.cursor_row = 0;
let next = key(KeyCode::Char('.'), KeyModifiers::SUPER | KeyModifiers::ALT);
app.handle_editor_key(next);
assert_eq!(app.status, "Bookmark 1 of 2 (line 2)");
app.handle_editor_key(next);
assert_eq!(app.status, "Bookmark 2 of 2 (line 5)");
}
#[test]
fn bookmark_clear_chord_is_cmd_opt_shift_b_and_clears_the_file() {
assert!(is_clear_bookmarks_key(key(
KeyCode::Char('b'),
KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
)));
assert!(is_clear_bookmarks_key(key(
KeyCode::Char('B'),
KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT,
)));
assert!(!is_clear_bookmarks_key(key(
KeyCode::Char('b'),
KeyModifiers::SUPER | KeyModifiers::ALT,
)));
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "notes.rs", "1\n2\n3\n");
for row in [0, 2] {
app.editor.cursor_row = row;
app.editor.toggle_bookmark();
}
app.handle_editor_key(key(
KeyCode::Char('b'),
KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
));
assert!(app.editor.bookmarked_lines().is_empty());
assert_eq!(app.status, "Cleared 2 bookmarks");
}
/// The palette command reaches `clear_bookmarks` without the chord's
/// handler, so the non-text guard has to hold on that path too.
#[test]
fn the_palette_clear_bookmarks_command_leaves_a_preview_alone() {
use crate::widgets::command_palette::Command;
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "notes.md", "# a\n\nb\n");
app.editor.cursor_row = 2;
app.editor.toggle_bookmark();
assert!(app.editor.toggle_markdown_preview());
app.run_command(Command::ClearBookmarks);
assert_eq!(
app.editor.bookmarked_lines(),
vec![3],
"the preview hides them"
);
// Back on the source, the same command clears, so the assertion above is
// the guard and not a command that does nothing.
assert!(app.editor.toggle_markdown_preview());
app.run_command(Command::ClearBookmarks);
assert!(app.editor.bookmarked_lines().is_empty());
}
#[test]
fn navigating_an_unmarked_file_explains_itself_rather_than_doing_nothing() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "notes.rs", "1\n2\n3\n");
app.editor.cursor_row = 1;
app.handle_editor_key(key(
KeyCode::Char('.'),
KeyModifiers::SUPER | KeyModifiers::ALT,
));
assert_eq!(app.editor.cursor_row, 1);
assert!(app.status.contains("No bookmarks"), "was {:?}", app.status);
}
#[test]
fn the_emmet_chord_expands_the_abbreviation_in_the_editor() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("page.html");
std::fs::write(&f, "ul>li*2\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
app.editor.cursor_row = 0;
app.editor.cursor_col = 7;
app.handle_editor_key(key(
KeyCode::Char('e'),
KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
));
assert_eq!(
app.editor.lines,
vec!["<ul>", " <li></li>", " <li></li>", "</ul>"]
);
assert_eq!(app.status, "Emmet: expanded abbreviation");
}
/// Silence would leave the user unable to tell "wrong language" from
/// "typo in the abbreviation".
#[test]
fn the_emmet_chord_says_so_when_there_is_nothing_to_expand() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("page.html");
std::fs::write(&f, "div>(span\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
app.editor.cursor_row = 0;
app.editor.cursor_col = 9;
app.handle_editor_key(key(
KeyCode::Char('e'),
KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
));
assert_eq!(app.editor.lines, vec!["div>(span"]);
assert_eq!(app.status, "Emmet: no abbreviation at the cursor");
}
/// A buffer Emmet does not run in gets a status naming the language, not
/// the "no abbreviation" message that sends the user hunting for a typo.
#[test]
fn the_emmet_chord_names_an_unsupported_language() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("main.rs");
std::fs::write(&f, "ul>li*2\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
app.editor.cursor_row = 0;
app.editor.cursor_col = 7;
app.handle_editor_key(key(
KeyCode::Char('e'),
KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
));
assert_eq!(app.editor.lines, vec!["ul>li*2"]);
assert_eq!(app.status, "Emmet: not available in Rust files");
}
// --- In-editor Find & Replace ---------------------------------------------
/// The Cmd+Opt+F chord as crossterm decodes the forwarded CSI-u sequence
/// (ALT|SUPER on macOS; Ctrl+Alt+F arrives as ALT|CONTROL on Linux).
fn replace_chord() -> KeyEvent {
key(KeyCode::Char('f'), KeyModifiers::ALT | KeyModifiers::SUPER)
}
#[test]
fn replace_chord_opens_the_find_bar_with_the_replace_row() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "alpha beta");
app.handle_key(replace_chord()).unwrap();
let s = app
.editor_find
.as_ref()
.expect("Cmd+Opt+F must open the find bar");
assert!(s.replace_visible, "the replace row must be shown");
}
#[test]
fn replace_chord_toggles_the_replace_row_on_an_open_find_bar() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "alpha beta");
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
assert!(
!app.editor_find.as_ref().unwrap().replace_visible,
"plain Cmd+F opens find without the replace row"
);
app.handle_key(replace_chord()).unwrap();
assert!(
app.editor_find.as_ref().unwrap().replace_visible,
"Cmd+Opt+F on an open find bar expands the replace row"
);
app.handle_key(replace_chord()).unwrap();
assert!(
!app.editor_find.as_ref().unwrap().replace_visible,
"Cmd+Opt+F again collapses the replace row"
);
}
#[test]
fn tab_switches_focus_between_the_find_and_replace_fields() {
use crate::widgets::editor_find::FindField;
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "alpha beta");
app.handle_key(replace_chord()).unwrap();
for c in "alpha".chars() {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
assert_eq!(
app.editor_find.as_ref().unwrap().query,
"alpha",
"typing lands in the query row first"
);
app.handle_key(key(KeyCode::Tab, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor_find.as_ref().unwrap().focus,
FindField::Replace,
"Tab moves focus to the replace row"
);
for c in "x".chars() {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
assert_eq!(
app.editor_find.as_ref().unwrap().replace,
"x",
"typing lands in the replace row once focused"
);
assert_eq!(
app.editor_find.as_ref().unwrap().query,
"alpha",
"the query is untouched by replace-row typing"
);
}
#[test]
fn enter_in_the_replace_field_replaces_the_current_match_and_advances() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "alpha beta\ngamma alpha");
app.handle_key(replace_chord()).unwrap();
for c in "alpha".chars() {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
app.handle_key(key(KeyCode::Tab, KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.lines[0], "x beta",
"the current match is replaced"
);
assert_eq!(
app.editor.lines[1], "gamma alpha",
"only the current match is replaced"
);
assert_eq!(
app.editor.cursor_row, 1,
"the editor advances to the next match"
);
assert!(app.editor.dirty, "a replace dirties the buffer");
assert!(app.editor.undo(), "the replace is undoable");
assert_eq!(app.editor.lines[0], "alpha beta");
}
#[test]
fn replace_all_chord_replaces_every_match_in_one_undo_step() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "alpha beta\ngamma alpha");
app.handle_key(replace_chord()).unwrap();
for c in "alpha".chars() {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
app.handle_key(key(KeyCode::Tab, KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Enter, KeyModifiers::ALT | KeyModifiers::SUPER))
.unwrap();
assert_eq!(app.editor.lines[0], "x beta");
assert_eq!(app.editor.lines[1], "gamma x");
assert!(app.editor.dirty, "replace all dirties the buffer");
assert!(app.editor.undo(), "replace all is one undo step");
assert_eq!(app.editor.lines[0], "alpha beta");
assert_eq!(app.editor.lines[1], "gamma alpha");
}
// --- Merge conflict resolution ---------------------------------------------
const CONFLICTED_BODY: &str =
"fn main() {\n<<<<<<< HEAD\n ours();\n=======\n theirs();\n>>>>>>> feature\n}";
#[test]
fn quick_fix_inside_a_conflict_opens_the_merge_picker() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", CONFLICTED_BODY);
app.editor.cursor_row = 2; // inside the ours section
app.start_code_action();
let picker = app
.list_picker
.as_ref()
.expect("Quick Fix inside a conflict must open the merge picker without an LSP round-trip");
assert_eq!(
picker.purpose,
crate::widgets::list_picker::ListPurpose::MergeConflict
);
assert_eq!(
picker.rows.len(),
3,
"Accept Current / Accept Incoming / Accept Both"
);
}
#[test]
fn merge_picker_accept_current_replaces_the_block_with_ours() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", CONFLICTED_BODY);
app.editor.cursor_row = 4; // inside the theirs section, still the same block
app.start_code_action();
assert!(app.list_picker.is_some(), "the merge picker must open");
app.confirm_list_picker(); // first row = Accept Current
assert_eq!(
app.editor.lines,
vec!["fn main() {", " ours();", "}"],
"the whole marker block collapses to the current section"
);
assert!(app.editor.dirty, "resolving a conflict dirties the buffer");
assert!(app.editor.undo(), "resolution is one undo step");
assert_eq!(app.editor.lines.len(), 7, "undo restores the marker block");
}
#[test]
fn palette_merge_accept_incoming_resolves_at_cursor() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", CONFLICTED_BODY);
app.editor.cursor_row = 1;
app.run_command(crate::widgets::command_palette::Command::MergeAcceptIncoming);
assert_eq!(app.editor.lines, vec!["fn main() {", " theirs();", "}"]);
// The last block resolving appends the Complete Merge pointer, so the
// next step of the flow is always one status read away (#107).
assert_eq!(
app.status,
"Accepted incoming change — all conflicts resolved; \"Merge: Complete Merge\" stages the file"
);
}
#[test]
fn palette_merge_accept_both_keeps_ours_then_theirs() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", CONFLICTED_BODY);
app.editor.cursor_row = 3;
app.run_command(crate::widgets::command_palette::Command::MergeAcceptBoth);
assert_eq!(
app.editor.lines,
vec!["fn main() {", " ours();", " theirs();", "}"]
);
}
#[test]
fn merge_commands_outside_a_conflict_report_and_leave_the_buffer_alone() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", CONFLICTED_BODY);
app.editor.cursor_row = 0; // outside the block
app.run_command(crate::widgets::command_palette::Command::MergeAcceptCurrent);
assert_eq!(app.status, "No merge conflict at the cursor");
assert_eq!(app.editor.lines.len(), 7, "the buffer is untouched");
}
#[test]
fn conflict_regions_render_with_tinted_backgrounds() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", CONFLICTED_BODY);
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let x = app.editor.last_inner.x + app.editor.last_gutter_width as u16 + 1;
let y0 = app.editor.last_inner.y; // row 0: "fn main() {"
let buf = term.backend().buffer();
let bg_at = |dy: u16| buf[(x, y0 + dy)].style().bg;
assert_ne!(
bg_at(2),
bg_at(0),
"the ours content row must be tinted differently from a plain row"
);
assert_ne!(
bg_at(4),
bg_at(0),
"the theirs content row must be tinted differently from a plain row"
);
assert_ne!(
bg_at(2),
bg_at(4),
"ours and theirs tint differently, like VS Code's current vs incoming"
);
}
// --- Auto Save (files.autoSave: afterDelay) --------------------------------
/// Rewind a buffer's last-edit stamp so the auto-save delay has elapsed.
fn age_last_edit(e: &mut crate::widgets::editor::Editor) {
e.last_edit_at = std::time::Instant::now().checked_sub(std::time::Duration::from_secs(5));
}
/// Issue #213: files.autoSave onFocusChange. With the mode on, moving
/// focus off the editor writes the dirty buffer immediately, without
/// waiting for the afterDelay timer (which stays off here).
#[test]
fn auto_save_on_focus_change_writes_when_the_editor_loses_focus() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.auto_save = false;
app.auto_save_on_focus_change = true;
app.focus_pane(Pane::Editor);
app.tick_auto_save(); // settle the focus signature
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert!(app.editor.dirty);
assert!(
!app.tick_auto_save(),
"no focus change yet, and the delay mode is off"
);
assert!(app.editor.dirty, "still dirty while focus has not moved");
// Focus leaves the editor: the buffer must be written on the next tick.
app.focus_pane(Pane::Terminal);
assert!(app.tick_auto_save(), "losing focus saves the buffer");
assert!(!app.editor.dirty, "saving clears the dirty flag");
let on_disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
assert!(
on_disk.contains('x'),
"the edit must be on disk: {on_disk:?}"
);
}
/// Switching tabs saves the tab that lost focus, and leaves the newly
/// focused (untouched) tab alone.
#[test]
fn auto_save_on_focus_change_writes_the_tab_that_lost_focus() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
let b = tmp.path().join("b.txt");
std::fs::write(&a, "aaa").unwrap();
std::fs::write(&b, "bbb").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.auto_save = false;
app.auto_save_on_focus_change = true;
app.editor.open_pinned(&a).unwrap();
app.focus_pane(Pane::Editor);
app.tick_auto_save();
app.handle_key(key(KeyCode::Char('Z'), KeyModifiers::NONE))
.unwrap();
assert!(app.editor.dirty, "a.txt is dirty");
// Opening b.txt takes focus away from a.txt.
app.editor.open_pinned(&b).unwrap();
assert!(app.tick_auto_save(), "the tab that lost focus is saved");
let on_disk = std::fs::read_to_string(&a).unwrap();
assert!(
on_disk.contains('Z'),
"a.txt must be written when it lost focus: {on_disk:?}"
);
}
/// The mode is off by default, so a focus change alone never writes.
#[test]
fn focus_changes_do_not_save_when_the_mode_is_off() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
// Pin both modes off explicitly: App::new loads the developer's real
// prefs, so asserting a DEFAULT here would depend on machine state.
app.auto_save = false;
app.auto_save_on_focus_change = false;
app.focus_pane(Pane::Editor);
app.tick_auto_save();
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
app.focus_pane(Pane::Terminal);
assert!(!app.tick_auto_save(), "the mode is off");
assert!(app.editor.dirty, "the buffer stays dirty");
}
#[test]
fn auto_save_writes_a_dirty_buffer_after_the_delay() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.auto_save = true;
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert!(app.editor.dirty, "typing dirties the buffer");
assert!(
!app.tick_auto_save(),
"a buffer edited a moment ago must not save yet"
);
assert!(app.editor.dirty, "still dirty before the delay elapses");
age_last_edit(&mut app.editor);
assert!(app.tick_auto_save(), "the aged buffer must save");
assert!(!app.editor.dirty, "saving clears the dirty flag");
let on_disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
assert!(
on_disk.contains('x'),
"the edit must be on disk, got: {on_disk:?}"
);
}
#[test]
fn auto_save_surfaces_a_disk_conflict_instead_of_latching_silently() {
// A dirty buffer collides with an external write: save_to_disk latches
// disk_conflict, due() then excludes the tab forever, and without a
// prompt the user learns nothing while auto save silently stops.
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.auto_save = true;
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
std::fs::write(tmp.path().join("a.txt"), "external change wins\n").unwrap();
age_last_edit(&mut app.editor);
assert!(
app.tick_auto_save(),
"a conflict-only tick must signal a redraw so the prompt shows now, not on the next blink"
);
assert!(app.editor.disk_conflict, "the conflict latches");
assert!(
app.input_prompt.is_some() || app.status.to_lowercase().contains("conflict"),
"the collision must be surfaced, not swallowed; status: {:?}",
app.status
);
}
#[test]
fn explicit_save_prompts_before_a_lossy_encoding_write_then_second_press_consents() {
// Issue #41: encoding_rs substitutes HTML numeric character references
// (not `?`) for unmappable characters, so an unguarded save silently
// rewrites 日本語 as `日…` on disk while the buffer looks fine.
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "plain");
app.editor
.reopen_with_encoding(encoding_rs::WINDOWS_1252)
.unwrap();
app.editor.lines = vec![String::from("日本語 costs 5€")];
app.editor.dirty = true;
app.save();
assert_eq!(
std::fs::read_to_string(tmp.path().join("a.txt")).unwrap(),
"plain",
"the first Cmd+S must refuse, leaving the file untouched"
);
assert!(
app.status.contains("windows-1252") && app.status.contains('日'),
"the refusal must name the encoding and the doomed characters; status: {:?}",
app.status
);
assert!(
app.editor.lossy_save_armed,
"the refusal arms the second press"
);
app.save();
assert_eq!(
std::fs::read(tmp.path().join("a.txt")).unwrap(),
b"日本語 costs 5\x80",
"the second Cmd+S is explicit consent to the lossy write"
);
assert!(!app.editor.dirty, "the consented save completes normally");
}
#[test]
fn an_edit_between_refusal_and_consent_forces_a_fresh_prompt() {
// The first Cmd+S arms the second — but consent named the characters the
// buffer held at prompt time. Typing in between changes what the write
// would destroy, so the next Cmd+S must refuse and re-prompt (now naming
// the new character too), and only the press after that writes.
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "plain");
app.editor
.reopen_with_encoding(encoding_rs::WINDOWS_1252)
.unwrap();
app.editor.lines = vec![String::from("日")];
app.editor.dirty = true;
app.save();
assert!(
app.editor.lossy_save_armed,
"the refusal arms the second press"
);
app.editor.insert_char('語');
app.save();
assert_eq!(
std::fs::read_to_string(tmp.path().join("a.txt")).unwrap(),
"plain",
"the edit revoked the consent, so this press must refuse again"
);
assert!(
app.status.contains('語'),
"the fresh prompt must name the newly typed character; status: {:?}",
app.status
);
app.save();
assert_eq!(
std::fs::read(tmp.path().join("a.txt")).unwrap(),
b"語日",
"consent given after the prompt that named both characters writes"
);
}
#[test]
fn auto_save_surfaces_an_encoding_refusal_instead_of_latching_silently() {
// The same latch-and-tell contract as the disk-conflict arm: the refusal
// removes the tab from due(), so the transition tick must both redraw
// and say why auto save stopped — and must never write the mangled bytes.
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "plain");
app.auto_save = true;
app.editor
.reopen_with_encoding(encoding_rs::WINDOWS_1252)
.unwrap();
app.editor.lines = vec![String::from("日本語")];
app.editor.dirty = true;
age_last_edit(&mut app.editor);
assert!(
app.tick_auto_save(),
"a refusal-only tick must signal a redraw so the message shows now"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("a.txt")).unwrap(),
"plain",
"auto save must never write the substituted bytes"
);
assert!(app.editor.encoding_loss, "the refusal latches");
assert!(
!app.editor.lossy_save_armed,
"auto save must never consent to the lossy write on the user's behalf"
);
assert!(
app.status.contains("a.txt") && app.status.contains("windows-1252"),
"the stall must be surfaced with the tab and its encoding; status: {:?}",
app.status
);
assert!(
!app.tick_auto_save(),
"the latch keeps later ticks quiet instead of re-refusing every second"
);
}
#[test]
fn merge_accept_refuses_a_non_text_tab() {
let tmp = tempfile::tempdir().unwrap();
let png = tmp.path().join("p.png");
image::RgbaImage::new(1, 1).save(&png).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&png).unwrap();
app.run_command(crate::widgets::command_palette::Command::MergeAcceptCurrent);
assert_eq!(
app.status, "Merge conflict actions need a text file",
"a non-text tab must refuse, never consult a possibly-stale conflict cache"
);
}
#[test]
fn replace_all_recounts_instead_of_reporting_zero() {
// Replacing `a` with `aa` doubles the matches; the title must recount,
// not read "No results" over a body still full of highlights.
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "a");
app.open_editor_replace();
if let Some(s) = app.editor_find.as_mut() {
s.query = "a".to_string();
s.replace = "aa".to_string();
}
app.editor_find_replace_all();
assert_eq!(
app.editor_find.as_ref().unwrap().match_count,
2,
"the count reflects the buffer after the replace"
);
}
#[test]
fn a_restored_dirty_tab_gets_an_auto_save_stamp() {
// A session-restored dirty tab has no last_edit_at; due() then never
// fires and the restored unsaved content sits unwritten forever.
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
let state = app.capture_session_state();
let mut restored = App::new(tmp.path().to_path_buf()).unwrap();
restored.apply_session_state(&state);
let dirty = restored
.editor
.editors
.iter()
.find(|e| e.dirty)
.expect("the dirty tab survives the restore");
assert!(
dirty.last_edit_at.is_some(),
"a restored dirty tab must be eligible for auto save"
);
}
#[test]
fn auto_save_stays_off_by_default() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
assert!(!app.auto_save, "auto save defaults off, like VS Code");
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
age_last_edit(&mut app.editor);
assert!(!app.tick_auto_save());
assert!(app.editor.dirty, "nothing saves while the pref is off");
}
#[test]
fn auto_save_never_overwrites_an_external_disk_change() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.auto_save = true;
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
// The file changes under croft before the delay elapses.
std::fs::write(tmp.path().join("a.txt"), "external edit").unwrap();
age_last_edit(&mut app.editor);
app.tick_auto_save();
let on_disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
assert_eq!(
on_disk, "external edit",
"auto save must refuse the write and keep the external content"
);
}
#[test]
fn auto_save_sweeps_dirty_background_tabs() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "first");
app.auto_save = true;
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
// Open a second file; the dirty first tab moves to the background.
let b = tmp.path().join("b.txt");
std::fs::write(&b, "second").unwrap();
app.editor.open_pinned(&b).unwrap();
for e in app.editor.editors.iter_mut() {
age_last_edit(e);
}
assert!(app.tick_auto_save(), "the background tab must save");
let on_disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
assert!(
on_disk.contains('x'),
"the background tab's edit must be on disk, got: {on_disk:?}"
);
}
#[test]
fn toggle_auto_save_command_flips_the_pref_and_reports_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
app.run_command(crate::widgets::command_palette::Command::ToggleAutoSave);
assert!(app.auto_save);
assert_eq!(app.status, "Auto Save: on");
app.run_command(crate::widgets::command_palette::Command::ToggleAutoSave);
assert!(!app.auto_save);
assert_eq!(app.status, "Auto Save: off");
}
// --- Workspace symbol search (# in Quick Open) ------------------------------
fn ws_item(
name: &str,
path: &std::path::Path,
line: u32,
) -> crate::lsp::manager::WorkspaceSymbolItem {
crate::lsp::manager::WorkspaceSymbolItem {
name: name.to_string(),
kind: crate::lsp::manager::OutlineKind::Function,
path: path.to_path_buf(),
line,
character: 0,
container: None,
}
}
#[test]
fn hash_prefix_in_quick_open_switches_to_workspace_symbols() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}");
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
assert!(app.file_finder.is_some(), "Cmd+P opens Quick Open");
app.handle_key(key(KeyCode::Char('#'), KeyModifiers::NONE))
.unwrap();
assert!(
app.file_finder.is_none(),
"typing # hands Quick Open over to the workspace symbol picker"
);
let picker = app
.workspace_symbols
.as_ref()
.expect("the workspace symbol picker must open");
assert_eq!(picker.query, "", "the # itself is not part of the query");
}
#[test]
fn palette_go_to_symbol_in_workspace_opens_the_picker() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}");
app.run_command(crate::widgets::command_palette::Command::GoToWorkspaceSymbol);
assert!(app.workspace_symbols.is_some());
}
#[test]
fn stale_workspace_symbol_replies_are_dropped() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}");
app.open_workspace_symbols("ma");
app.ws_symbols_request_id = Some(7);
let f = tmp.path().join("a.rs");
assert!(
!app.apply_workspace_symbols(3, vec![ws_item("old", &f, 0)], false),
"a reply for a superseded request must be dropped"
);
assert!(app.workspace_symbols.as_ref().unwrap().results.is_empty());
assert!(
app.apply_workspace_symbols(7, vec![ws_item("main", &f, 0)], false),
"the newest request's reply applies"
);
assert_eq!(app.workspace_symbols.as_ref().unwrap().results.len(), 1);
}
#[test]
fn enter_opens_the_selected_symbols_file_at_its_line() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}");
let other = tmp.path().join("b.rs");
std::fs::write(&other, "line0\nline1\nfn target() {}\n").unwrap();
app.open_workspace_symbols("target");
app.ws_symbols_request_id = Some(1);
assert!(app.apply_workspace_symbols(1, vec![ws_item("target", &other, 2)], false));
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(app.workspace_symbols.is_none(), "Enter closes the picker");
assert_eq!(
app.editor.path.as_deref(),
Some(other.as_path()),
"Enter opens the symbol's file"
);
assert_eq!(
app.editor.cursor_row, 2,
"the caret lands on the symbol's line"
);
}
#[test]
fn typing_in_the_picker_without_a_language_server_reports_unsupported() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}");
app.lsp = None;
app.open_workspace_symbols("");
app.handle_key(key(KeyCode::Char('m'), KeyModifiers::NONE))
.unwrap();
// The query dispatches on the debounce tick, not the keystroke.
std::thread::sleep(std::time::Duration::from_millis(250));
app.workspace_symbols_dispatch_due();
let picker = app.workspace_symbols.as_ref().unwrap();
assert!(
picker.unsupported,
"with no language server the picker must say so instead of spinning"
);
}
#[test]
fn a_user_keybinding_overrides_and_runs_the_bound_command() {
// A chord in keybindings.json is consulted ahead of the built-in handlers
// and dispatches the palette command it names.
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+alt+g", "command": "show_search" }]"#);
assert_ne!(app.sidebar_view, SidebarView::Search);
app.handle_key(key(
KeyCode::Char('g'),
KeyModifiers::CONTROL | KeyModifiers::ALT,
))
.unwrap();
assert_eq!(
app.sidebar_view,
SidebarView::Search,
"the bound chord must run Show Search via run_command"
);
}
#[test]
fn a_user_keybinding_is_ignored_while_the_terminal_is_focused() {
// The terminal needs its raw control keys, so the keymap must not fire there.
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+alt+g", "command": "show_search" }]"#);
app.focus = Pane::Terminal;
app.handle_key(key(
KeyCode::Char('g'),
KeyModifiers::CONTROL | KeyModifiers::ALT,
))
.unwrap();
assert_ne!(
app.sidebar_view,
SidebarView::Search,
"a bound chord must be inert while the terminal is focused"
);
}
#[test]
fn tab_expands_a_user_snippet_and_places_the_caret() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.snippets = crate::snippets::SnippetSet::from_json(
r#"{ "Log": { "prefix": "log", "body": "console.log($1)" } }"#,
);
app.editor.insert_str("log");
app.handle_editor_tab();
assert_eq!(app.editor.lines[app.editor.cursor_row], "console.log()");
assert_eq!(
app.editor.cursor_col, 12,
"caret lands inside the parentheses at $1"
);
}
#[test]
fn accepting_a_snippet_completion_expands_it_with_tab_stops() {
// A snippet item in the completion popup carries the body as is_snippet
// insertion text; Enter must expand it through the editor engine, not
// insert the literal "$1".
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.insert_str("log");
let item = super::snippet_completion_item(&crate::snippets::Snippet {
prefix: "log".into(),
body: "console.log($1)".into(),
scope: vec![],
});
app.completion_popup = Some(crate::widgets::completion_popup::CompletionPopup::new(
vec![item],
"log".into(),
(0, 0),
std::path::PathBuf::new(),
1,
));
app.handle_completion_popup_key(key(KeyCode::Enter, KeyModifiers::NONE));
assert_eq!(app.editor.lines[app.editor.cursor_row], "console.log()");
assert_eq!(
app.editor.cursor_col, 12,
"the typed prefix is replaced and the caret lands at $1"
);
}
#[test]
fn settings_view_toggle_flips_the_setting_and_stays_open() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let before = app.auto_close_pairs;
app.open_settings_view();
// The first row is "Auto Closing Pairs"; confirming it flips the value.
app.confirm_list_picker();
assert_eq!(
app.auto_close_pairs, !before,
"the toggle row flips the setting"
);
assert!(
app.list_picker.is_some(),
"a toggle keeps the settings hub open so more can be flipped"
);
}
#[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);
// Cmd+K Shift+T brings the pane back: same slot, same name, and the
// child process never died in the grace window.
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");
// The same operation and the same old constant as the wait in
// `terminal_session_restores_pane_layout_names_and_focus_across_restarts`:
// a shell echoing one line, waited on under whatever load the suite is
// running. Same 2s base, so the same 8s floor.
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"))
},
);
// Past the grace window the parked pane is dropped for real: the tick
// reaps it and undo has nothing left to restore.
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();
// Row 0 is the deterministic `▶ …` run-label header; the printf rows
// land on rows 1..=3. Lines are short so nothing wraps at 80 cols.
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
// Sentinels are assembled at runtime so the pane's `▶ …` header
// (which echoes the command text) can never match the waits.
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));
};
// The header may wrap, so locate "aaaa1" by content: its distance from
// the grid top is the number of j presses after g.
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));
}
};
// Char selection: g to the grid top, j down to "aaaa1", v at col 0,
// $ to the line's last glyph, y copies and leaves copy mode.
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");
// Line selection: V spans full rows regardless of cursor column.
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"
);
// Block selection: a 2-wide, 3-tall rectangle from the output rows.
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"
);
// Esc exits and drops the highlight.
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" } ]"#,
));
// Read-gated so the drain tick pushes the trigger set into the pane
// before the matching line prints; the sentinel is assembled at runtime
// so the `▶ …` header can never fire the trigger itself.
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
);
// Enter on the row jumps back to the pane and selects the matched 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:?}"
);
// `n` asks the Navigator about the line (#372); with none seated it
// says so rather than doing nothing, and the palette carries the same
// command.
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"
);
}
#[test]
fn finished_commands_land_in_durable_history_and_the_popup_types_them() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Point the store at the tempdir so tests never touch the real file.
app.command_history =
crate::command_history::CommandHistory::load(&tmp.path().join("hist.jsonl"));
// Full OSC 133 marks around a fake command (B → command text → C →
// 1s of "runtime" → D;0), then a read so the popup's Enter-typed
// bytes are observable through the shell.
let script = "printf '\\033]133;A\\007$ \\033]133;B\\007kubectl get pods\\n\\033]133;C\\007'; sleep 1; printf 'out\\n\\033]133;D;0\\007'; read x; echo typed-$x; sleep 30";
// The marks are stamped when the reader thread PARSES them, not when
// the child wrote them. Under suite load a late pickup shrinks the
// measured gap (#65), and in the extreme the reader is descheduled
// across the WHOLE sleep: both marks then coalesce into one read and
// the arrival-time measurement honestly collapses to ~0 (#154) — the
// true gap is unrecoverable from coalesced bytes. So the C→D floor is
// asserted per attempt, retrying the collapse class a bounded number
// of times: a real wrong-span bug fails every attempt deterministically,
// while three consecutive full-second deschedules do not happen.
let mut entry = None;
for attempt in 0..3 {
app.command_history.entries.clear();
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 finished command to reach the history store",
|| {
app.drain_terminal_bells();
!app.command_history.is_empty()
},
);
let e = app.command_history.entries[0].clone();
assert_eq!(
e.cmd, "kubectl get pods",
"the typed text travels with the completion"
);
assert_eq!(e.exit, Some(0));
if e.dur_ms >= 500 {
entry = Some(e);
break;
}
assert!(
attempt < 2,
"duration must cover the C→D gap on some attempt; every run measured under 500ms (last: {})",
e.dur_ms
);
}
let e = entry.expect("an attempt produced a full-gap measurement");
let _ = e;
// The popup searches the store and Enter types the pick at the prompt.
app.focus_pane(Pane::Terminal);
app.handle_terminal_key(key(
KeyCode::Char('h'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT,
));
assert!(
app.command_history_popup.is_some(),
"Ctrl+Shift+H must open the history popup"
);
for c in "pods".chars() {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
let picked = app
.command_history_popup
.as_ref()
.and_then(|p| p.selected_entry())
.map(|e| e.cmd.clone());
assert_eq!(picked.as_deref(), Some("kubectl get pods"));
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(
app.command_history_popup.is_none(),
"Enter closes the popup"
);
app.terminals[0].write_input(b"\n");
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the typed command to reach the shell",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.contains("typed-kubectl get pods"))
},
);
}
#[test]
fn terminal_session_restores_pane_layout_names_and_focus_across_restarts() {
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[1].set_manual_name(Some(String::from("srv")));
app.active_terminal = 1;
app.save_terminal_session();
let raw = std::fs::read_to_string(&session_path).unwrap();
assert!(
raw.contains("srv"),
"the session file records pane names: {raw}"
);
// A fresh app on the same workspace resurrects the layout.
let mut app2 = App::new(tmp.path().to_path_buf()).unwrap();
app2.terminal_session_path = session_path.clone();
app2.restore_terminal_session();
assert_eq!(app2.terminals.len(), 2, "both panes come back");
assert_eq!(app2.terminals[1].label(), "srv", "names survive");
assert_eq!(
app2.active_terminal, 1,
"focus lands on the pane that had it"
);
// The restored pane runs a live shell.
app2.terminals[1].write_input(b"s=ali; echo ${s}ve-42\n");
// Load-scaled, not a fixed 8000ms: what blows a wait on a spawned shell
// is contention, which is a property of what else the suite is doing
// rather than of this test, and `test_budget` is where that reasoning
// already lives (#307/#422).
//
// `await_spawned` multiplies the base by `BASE_CALIBRATION * load_scale`,
// which that module's own test pins at 4 at MIN_SCALE and 8 at the cap.
// A 2s base is therefore 8s at the floor and 16s at the cap: the 8000ms
// this replaces is what the wait KEEPS on a quiet machine, and load buys
// more on top. The floor is the point - `MIN_SCALE`'s own doc says it may
// never shrink below the budgets these tests already had, since every one
// of them was observed failing at 1x.
crate::test_budget::await_spawned(
crate::test_budget::tests::RESTORED_SHELL_BASE,
"the restored pane's shell to answer",
|| {
app2.terminals[1]
.grid_lines()
.0
.iter()
.any(|l| l.contains("alive-42"))
},
);
// Closing back down to one default pane prunes the record, so a plain
// single-shell workspace never grows the file.
app2.terminals[1].set_manual_name(None);
assert!(app2.close_terminal_at(1));
app2.save_terminal_session();
let map = crate::terminal_session::load(&session_path);
assert!(
!map.contains_key(&tmp.path().display().to_string()),
"a trivial session (one unnamed pane at the root) is pruned"
);
}
#[test]
fn opening_a_workspace_file_installs_its_exact_folder_set() {
// #163: an explicitly opened .code-workspace defines the arrangement
// exactly — the automatic per-primary store is not merged in.
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("alpha");
let b = tmp.path().join("beta");
let c = tmp.path().join("gamma");
for d in [&a, &b, &c] {
std::fs::create_dir(d).unwrap();
}
let file = tmp.path().join("proj.code-workspace");
crate::workspace::write_workspace_file(&file, &[b.clone(), c.clone()]).unwrap();
let mut app = App::new(a.clone()).unwrap();
// Poison the auto-store for primary B with a DIFFERENT folder: the
// file must win, so alpha never joins.
let b_canon = b.canonicalize().unwrap();
crate::workspace::save_folders_for_root(
&app.workspace_folders_path.clone(),
&b_canon.display().to_string(),
vec![a.clone()],
)
.unwrap();
app.open_workspace_file(&file);
let roots: Vec<PathBuf> = app.roots.iter().map(Path::to_path_buf).collect();
assert_eq!(
app.workspace_root(),
b_canon,
"first folder becomes primary"
);
assert!(
roots.contains(&c.canonicalize().unwrap()),
"the file's second folder joins: {roots:?}"
);
assert!(
!roots.contains(&a.canonicalize().unwrap()),
"the auto-store's folder does NOT merge in: {roots:?}"
);
// Save Workspace As round-trips the live set through the prompt path.
let dest = tmp.path().join("saved.code-workspace");
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
app.open_input_prompt(
InputPrompt::new(
InputPurpose::SaveWorkspaceAs,
String::from("Save Workspace As"),
"",
)
.with_value(dest.display().to_string()),
);
app.submit_input_prompt();
let saved = crate::workspace::parse_workspace_file(&dest).unwrap();
assert_eq!(saved, roots, "the saved file names the live folder set");
// A malformed file refuses with the error in the status.
let bad = tmp.path().join("bad.code-workspace");
std::fs::write(&bad, "{ nope").unwrap();
let before: Vec<PathBuf> = app.roots.iter().map(Path::to_path_buf).collect();
app.open_workspace_file(&bad);
assert!(app.status.starts_with("Workspace file:"), "{}", app.status);
let after: Vec<PathBuf> = app.roots.iter().map(Path::to_path_buf).collect();
assert_eq!(before, after, "a bad file changes nothing");
}
#[test]
fn workspace_folder_set_persists_across_sessions_and_reroots() {
// #153: the folder set lived only in memory — reopening the same
// workspace came back single-folder.
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a");
let b = tmp.path().join("b");
let c = tmp.path().join("c");
std::fs::create_dir(&a).unwrap();
std::fs::create_dir(&b).unwrap();
std::fs::create_dir(&c).unwrap();
let store = tmp.path().join("folders.json");
let mut app = App::new(a.clone()).unwrap();
app.workspace_folders_path = store.clone();
app.add_workspace_folder(b.clone());
app.add_workspace_folder(c.clone());
// A fresh session on the same primary restores the arrangement.
let mut app2 = App::new(a.clone()).unwrap();
app2.workspace_folders_path = store.clone();
app2.restore_workspace_folders();
let b_canon = b.canonicalize().unwrap();
let c_canon = c.canonicalize().unwrap();
let roots: Vec<PathBuf> = app2.roots.iter().map(Path::to_path_buf).collect();
assert!(
roots.contains(&b_canon) && roots.contains(&c_canon),
"both folders come back: {roots:?}"
);
// A vanished folder is dropped from the record, not restored.
std::fs::remove_dir_all(&c).unwrap();
let mut app3 = App::new(a.clone()).unwrap();
app3.workspace_folders_path = store.clone();
app3.restore_workspace_folders();
let roots: Vec<PathBuf> = app3.roots.iter().map(Path::to_path_buf).collect();
assert!(roots.contains(&b_canon) && !roots.contains(&c_canon));
let map = crate::workspace::load_folders(&store);
assert_eq!(
map.get(&a.display().to_string()),
Some(&vec![b_canon.clone()]),
"the record rewrites to what survived"
);
// Removing the last secondary folder prunes the key.
app3.remove_workspace_folder(b_canon.clone());
assert!(
!crate::workspace::load_folders(&store).contains_key(&a.display().to_string()),
"a single-folder workspace never lingers in the store"
);
// Re-rooting into a workspace with a saved set restores it.
crate::workspace::save_folders_for_root(
&store,
&b_canon.display().to_string(),
vec![a.clone()],
)
.unwrap();
app3.change_workspace_root(b_canon.clone());
let roots: Vec<PathBuf> = app3.roots.iter().map(Path::to_path_buf).collect();
assert!(
roots.contains(&a.canonicalize().unwrap()),
"the new primary's saved folders come back with the re-root: {roots:?}"
);
}
#[test]
fn focusing_a_secondary_roots_file_rebinds_the_test_runner_and_tasks() {
// #151: the runner gate and the worker resolved against the primary
// only — from a secondary folder's file, Run All refused with "no
// test runner" even when that folder is a cargo project.
let tmp = tempfile::tempdir().unwrap();
let plain = tmp.path().join("plain");
let proj = tmp.path().join("proj");
std::fs::create_dir(&plain).unwrap();
std::fs::create_dir_all(proj.join("src")).unwrap();
std::fs::write(
proj.join("Cargo.toml"),
"[package]\nname = \"proj\"\nversion = \"0.0.1\"\nedition = \"2021\"\n",
)
.unwrap();
std::fs::write(
proj.join("src/main.rs"),
"fn main() {}\n#[test]\nfn proj_truth() {}\n",
)
.unwrap();
std::fs::write(proj.join("Makefile"), "build:\n\techo hi\n").unwrap();
let mut app = App::new(plain.clone()).unwrap();
app.add_workspace_folder(proj.clone());
let proj_canon = proj.canonicalize().unwrap();
// Primary focused: no runner, the gate refuses.
app.status.clear();
app.run_all_tests();
assert_eq!(app.status, crate::testing::NO_RUNNER_STATUS);
// Focus the cargo project's file: the follow tick rebinds the
// Testing stack and the gate passes.
app.editor
.open_pinned(&proj_canon.join("src/main.rs"))
.unwrap();
let _ = app.drain_git_responses();
assert_eq!(
app.active_test_root, proj_canon,
"the Testing stack follows"
);
app.status.clear();
app.run_all_tests();
assert_ne!(
app.status,
crate::testing::NO_RUNNER_STATUS,
"the secondary folder's cargo runner is found"
);
// The open-Testing-view path discovers against the active folder:
// this is the exact live sequence, and the discovery gate had its own
// primary-root check the entry-point gates didn't cover.
app.open_testing_view();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
loop {
let _ = app.test_worker.drain(&mut app.testing);
if app
.testing
.cases_for_test()
.iter()
.any(|(name, _)| name.contains("proj_truth"))
{
break;
}
assert!(
std::time::Instant::now() < deadline,
"discovery never returned the secondary project's tests; cases: {:?}",
app.testing.cases_for_test()
);
std::thread::sleep(std::time::Duration::from_millis(50));
}
// Drain the discovery's Finished before running: breaking out on the
// first case leaves the panel busy, and run_all_tests refuses while a
// discovery is in flight.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
while app.testing.is_busy() {
let _ = app.test_worker.drain(&mut app.testing);
assert!(
std::time::Instant::now() < deadline,
"discovery never reported Finished"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
// And a full RUN executes in that folder: the case must go green,
// which only happens if cargo built and ran the secondary project.
app.run_all_tests();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
loop {
let _ = app.test_worker.drain(&mut app.testing);
if app.testing.cases_for_test().iter().any(|(name, status)| {
name.contains("proj_truth") && *status == crate::testing::model::TestStatus::Passed
}) {
break;
}
assert!(
std::time::Instant::now() < deadline,
"the secondary project's test never passed; cases: {:?}",
app.testing.cases_for_test()
);
std::thread::sleep(std::time::Duration::from_millis(50));
}
// Tasks discover against the active folder too.
let tasks = crate::tasks::discover_tasks(&app.active_workspace_root());
assert!(
tasks.iter().any(|t| t.command.contains("make")),
"the secondary folder's Makefile tasks are offered: {:?}",
tasks.iter().map(|t| t.command.clone()).collect::<Vec<_>>()
);
}
#[test]
fn repositories_overview_lists_every_folder_and_a_pin_overrides_the_follow() {
// #161: with several folders open, the panel shows a REPOSITORIES
// overview and a clicked row pins the panel until focus crosses
// folders again.
let tmp = tempfile::tempdir().unwrap();
let mk_repo = |name: &str, branch: &str| {
let dir = tmp.path().join(name);
std::fs::create_dir(&dir).unwrap();
for args in [
vec!["init", "-q", "-b", branch],
vec!["config", "user.email", "a@b"],
vec!["config", "user.name", "a"],
] {
assert!(
std::process::Command::new("git")
.args(["-C"])
.arg(&dir)
.args(&args)
.status()
.map(|s| s.success())
.unwrap_or(false),
"git setup failed: {args:?}"
);
}
std::fs::write(dir.join("f.txt"), "x\n").unwrap();
dir
};
let a = mk_repo("repa", "main");
let b = mk_repo("repb", "trunk");
let mut app = App::new(a.clone()).unwrap();
app.add_workspace_folder(b.clone());
let b_canon = b.canonicalize().unwrap();
// Both workers report their repos; the per-frame sync builds the rows.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
loop {
let _ = app.drain_git_responses();
app.sync_focus_flags();
let rows = &app.source_control.repositories;
if rows.len() == 2
&& rows.iter().any(|r| r.branch.as_deref() == Some("main"))
&& rows.iter().any(|r| r.branch.as_deref() == Some("trunk"))
{
break;
}
assert!(
std::time::Instant::now() < deadline,
"overview rows never filled: {:?}",
rows
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert!(
app.source_control
.repositories
.iter()
.all(|r| r.changes >= 1),
"EVERY repository's untracked file shows in its change count: {:?}",
app.source_control.repositories
);
// Anchor the focus in folder A first, then pin B: the pin wins for
// as long as the focus stays inside A (further A files included).
//
// Compare against the root in the form the workspace holds it, not a
// canonicalised one: `App::new` stores the primary root verbatim, and
// on macOS a tempdir arrives as `/var/…` for a `/private/var/…`
// directory. The app is self-consistent — the follow root derives from
// the same workspace roots — so canonicalising only this side compares
// two spellings of one path and fails everywhere `/var` is a symlink.
let a_root = app
.roots
.iter()
.find(|r| r.ends_with("repa"))
.expect("folder A is in the workspace")
.to_path_buf();
app.editor.open_pinned(&a.join("f.txt")).unwrap();
let _ = app.drain_git_responses();
assert_eq!(app.active_scm_root, a_root);
app.scm_pin = Some(b_canon.clone());
let _ = app.drain_git_responses();
assert_eq!(
app.active_scm_root, b_canon,
"the pin wins while focus stays put"
);
// CROSSING folders with the focus releases the pin: land in B (the
// follow now agrees with the pinned repo), then back to A — the
// panel follows again.
app.editor.open_pinned(&b_canon.join("f.txt")).unwrap();
let _ = app.drain_git_responses();
assert!(
app.scm_pin.is_none(),
"the cross-folder focus released the pin"
);
app.editor.open_pinned(&a.join("f.txt")).unwrap();
let _ = app.drain_git_responses();
assert_eq!(
app.active_scm_root, a_root,
"after release the panel follows the focus again"
);
}
#[test]
fn tab_strip_renders_disambiguated_titles_for_colliding_names() {
// #167 end-to-end: two same-named files from different folders must
// paint distinguishable tab titles in the real strip.
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("alpha");
let b = tmp.path().join("beta");
std::fs::create_dir(&a).unwrap();
std::fs::create_dir(&b).unwrap();
std::fs::write(a.join("main.rs"), "a\n").unwrap();
std::fs::write(b.join("main.rs"), "b\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// The QUICK OPEN path (preview tab, pinned by an edit, then a second
// preview) — the live gesture, which must disambiguate exactly like
// two pinned opens.
app.editor.open_preview(&a.join("main.rs")).unwrap();
app.editor.insert_char('x');
app.editor.open_preview(&b.join("main.rs")).unwrap();
assert_eq!(app.editor.iter_tabs().count(), 2, "two tabs");
let backend = ratatui::backend::TestBackend::new(120, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let buf = term.backend().buffer().clone();
let strip_y = app.editor.tab_strip_y_for_test();
let row: String = (0..buf.area.width)
.map(|x| buf[(x, strip_y)].symbol().to_string())
.collect();
assert!(
row.contains("main.rs — alpha") && row.contains("main.rs — beta"),
"the strip paints the disambiguated titles: {row}"
);
}
#[test]
fn clicking_a_repositories_overview_row_switches_the_panel() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mk_repo = |name: &str, branch: &str| {
let dir = tmp.path().join(name);
std::fs::create_dir(&dir).unwrap();
for args in [
vec!["init", "-q", "-b", branch],
vec!["config", "user.email", "a@b"],
vec!["config", "user.name", "a"],
] {
assert!(
std::process::Command::new("git")
.args(["-C"])
.arg(&dir)
.args(&args)
.status()
.map(|s| s.success())
.unwrap_or(false),
);
}
std::fs::write(dir.join("f.txt"), "x\n").unwrap();
dir
};
let a = mk_repo("repa", "main");
let b = mk_repo("repb", "trunk");
let mut app = App::new(a.clone()).unwrap();
app.add_workspace_folder(b.clone());
let b_canon = b.canonicalize().unwrap();
app.set_sidebar_view(SidebarView::SourceControl);
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
loop {
let _ = app.drain_git_responses();
app.sync_focus_flags();
term.draw(|frame| app.render(frame)).unwrap();
if app.source_control.repo_row_areas.len() == 2 {
break;
}
assert!(
std::time::Instant::now() < deadline,
"overview rows never rendered; rows: {:?}",
app.source_control.repositories
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
let (rect, root) = app.source_control.repo_row_areas[1].clone();
assert_eq!(root, b_canon);
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
rect.x + 2,
rect.y,
));
let _ = app.drain_git_responses();
assert_eq!(
app.active_scm_root, b_canon,
"the click pins the panel to the second repository"
);
assert_eq!(app.scm_pin.as_deref(), Some(b_canon.as_path()));
}
#[test]
fn focusing_a_secondary_roots_file_flips_source_control_to_its_repo() {
// #149: git state was singular (one worker at the primary), so a
// secondary root's repository was invisible — no branch, no panel
// entries, no scm_root for its operations.
let tmp = tempfile::tempdir().unwrap();
let plain = tmp.path().join("plain");
let repo = tmp.path().join("repo");
std::fs::create_dir(&plain).unwrap();
std::fs::create_dir(&repo).unwrap();
for args in [
vec!["init", "-q", "-b", "trunk"],
vec!["config", "user.email", "a@b"],
vec!["config", "user.name", "a"],
] {
let ok = std::process::Command::new("git")
.args(["-C"])
.arg(&repo)
.args(&args)
.status()
.map(|s| s.success())
.unwrap_or(false);
assert!(ok, "git setup step failed: {args:?}");
}
std::fs::write(repo.join("seed.txt"), "one\n").unwrap();
for args in [vec!["add", "."], vec!["commit", "-qm", "init"]] {
let ok = std::process::Command::new("git")
.args(["-C"])
.arg(&repo)
.args(&args)
.status()
.map(|s| s.success())
.unwrap_or(false);
assert!(ok, "git setup step failed: {args:?}");
}
std::fs::write(repo.join("seed.txt"), "one\ntwo\n").unwrap();
// Primary is NOT a repo; the repo joins as a secondary folder.
let mut app = App::new(plain.clone()).unwrap();
app.add_workspace_folder(repo.clone());
let repo_canon = repo.canonicalize().unwrap();
// Focus the secondary root's file: the SCM surfaces must follow.
app.editor
.open_pinned(&repo_canon.join("seed.txt"))
.unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
let mut flipped = false;
while std::time::Instant::now() < deadline {
let _ = app.drain_git_responses();
if app.source_control.status.branch.as_deref() == Some("trunk")
&& app
.source_control
.entries
.iter()
.any(|e| e.path == "seed.txt")
{
flipped = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert!(
flipped,
"the panel must show the secondary root's repo (branch + changes); saw {:?} / {:?}",
app.source_control.status.branch,
app.source_control
.entries
.iter()
.map(|e| e.path.clone())
.collect::<Vec<_>>()
);
assert_eq!(
app.scm_root().canonicalize().unwrap(),
repo_canon,
"panel operations address the active repo's toplevel"
);
// The mutation path must hit the SAME repository the panel shows
// (#150 review: staging addressed the active repo while commit still
// ran against the primary — stage in B, commit in A).
app.stage_all_source_control();
app.source_control.message = String::from("from the panel");
app.commit_staged_source_control();
let log = std::process::Command::new("git")
.args(["-C"])
.arg(&repo)
.args(["log", "--oneline"])
.output()
.unwrap();
assert!(log.status.success());
assert!(
String::from_utf8_lossy(&log.stdout).contains("from the panel"),
"the commit lands in the ACTIVE repo, the one the panel shows"
);
}
#[test]
fn add_and_remove_workspace_folder_fan_out_across_tree_index_and_search() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("alpha");
let b = tmp.path().join("beta");
std::fs::create_dir(&a).unwrap();
std::fs::create_dir(&b).unwrap();
std::fs::write(a.join("main.rs"), "fn main() {}\n").unwrap();
std::fs::write(b.join("util.rs"), "pub fn u() {}\n").unwrap();
let mut app = App::new(a.clone()).unwrap();
app.add_workspace_folder(b.clone());
let b_canon = b.canonicalize().unwrap();
assert!(app.roots.is_multi(), "the model grew");
assert!(
app.tree.root_paths().any(|r| r == b_canon),
"the Explorer gained the section"
);
assert_eq!(app.search.roots.len(), 2, "the search panel spans both");
assert_eq!(
app.fs_watch_extra.len(),
1,
"the added root gets its own watcher share"
);
// The Cmd+P index rebuild runs on a walker thread: poll it in, then
// both roots' files must appear under root-name prefixes.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
app.try_install_pending_init();
if let Some(idx) = app.file_finder_index.as_ref() {
let rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
if rels.contains(&"alpha/main.rs") && rels.contains(&"beta/util.rs") {
break;
}
}
assert!(
std::time::Instant::now() < deadline,
"the multi-root Cmd+P index never landed; entries: {:?}",
app.file_finder_index
.as_ref()
.map(|i| i.iter().map(|e| e.rel.clone()).collect::<Vec<_>>())
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
// Adding it again is a no-op with an explanation.
app.add_workspace_folder(b.clone());
assert_eq!(app.status, "Folder is already in the workspace");
// The primary is not removable; the secondary is, and everything
// collapses back to single-root.
let a_canon = a.canonicalize().unwrap();
app.remove_workspace_folder(a_canon);
assert!(app.roots.is_multi(), "removing the primary is refused");
app.remove_workspace_folder(b_canon.clone());
assert!(!app.roots.is_multi());
assert!(
!app.tree.root_paths().any(|r| r == b_canon),
"the section left the Explorer"
);
assert_eq!(app.search.roots.len(), 1);
assert!(app.fs_watch_extra.is_empty());
}
#[test]
fn delete_filters_workspace_roots_out_of_a_mixed_selection() {
// #146 review: the context menu forwards a mixed multi-selection
// wholesale into MenuAction::Delete, and Select All marks the root
// rows too — so the batch path must refuse root rows at the
// delete_paths choke point, not rely on the per-node guard.
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();
std::fs::write(a.join("f.txt"), "x\n").unwrap();
let mut app = App::new(a.clone()).unwrap();
app.tree.add_root(b.clone());
// Mixed batch: a real file plus BOTH root rows (what Select All +
// right-click Delete assembles).
app.delete_paths(vec![a.join("f.txt"), a.clone(), b.clone()]);
let prompt = app.input_prompt.as_ref().expect("the confirm opens");
match &prompt.purpose {
crate::widgets::input_prompt::InputPurpose::TreeDelete { paths } => {
assert_eq!(
paths,
&vec![a.join("f.txt")],
"both workspace roots are filtered; only the file survives to the confirm"
);
}
other => panic!("wrong prompt purpose: {other:?}"),
}
app.input_prompt = None;
// A batch of ONLY roots opens no prompt at all.
app.delete_paths(vec![a.clone(), b.clone()]);
assert!(
app.input_prompt.is_none(),
"a roots-only batch is refused outright"
);
assert_eq!(app.status, "Workspace roots cannot be deleted");
}
#[test]
fn change_workspace_root_saves_the_outgoing_workspaces_terminal_layout() {
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 mut app = App::new(a.clone()).unwrap();
app.terminal_session_path = tmp.path().join("sessions.json");
// Name the pane directly (the rename UI would flush a save itself, and
// this test must prove the RE-ROOT saves): a named pane is a
// non-trivial layout the store keeps.
app.terminals[0].set_manual_name(Some(String::from("srv")));
assert!(
!app.terminal_session_path.exists(),
"precondition: nothing has saved the session yet"
);
app.change_workspace_root(b.clone());
let map = crate::terminal_session::load(&app.terminal_session_path);
let rec = map.get(&a.display().to_string()).expect(
"re-rooting away must persist the outgoing workspace's pane layout under ITS key; \
the layout was silently discarded",
);
assert_eq!(
rec.panes[0].name.as_deref(),
Some("srv"),
"the saved record carries the outgoing panes"
);
assert!(
!map.contains_key(&b.display().to_string()),
"nothing may be filed under the incoming root's key by the re-root itself"
);
}
#[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;
// The default pane is untouched: no input, no name, no launched
// program — exactly the startup state restore replaces at launch.
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;
// Park an undo-close entry (the split writes no input into pane 0, so
// the panel stays pristine) and open copy mode on the surviving pane:
// both are bound to the OUTGOING panel and keyed by pane index, which
// the restored panel's identical indexes would wrongly satisfy.
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 change_workspace_root_keeps_live_panes_when_the_terminal_was_touched() {
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;
// Any input byte marks the pane as the user's: its shell (history,
// scrollback, possibly a job) must survive the re-root untouched even
// though the incoming workspace has a saved layout.
app.terminal_mut().write_input(b"echo touched\n");
let uid = app.terminals[0].uid();
app.change_workspace_root(b.clone());
assert_eq!(
app.terminals.len(),
1,
"a touched panel is never replaced by the incoming workspace's saved layout"
);
assert_eq!(
app.terminals[0].uid(),
uid,
"the surviving pane is the same live shell, not a respawn"
);
}
#[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();
// Pane 0 reports 46% (state 1), then a read gates the state-0 clear so
// the test controls both phases. A second pane makes the name pill paint.
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.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();
fn screen_rows(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> Vec<String> {
let buf = term.backend().buffer();
(0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
.collect()
})
.collect()
}
let area = app.terminals[0].last_area;
let inner = app.terminals[0].last_inner;
let rows = screen_rows(&term);
let border_row = &rows[(area.y + area.height - 1) as usize];
// The gauge's fill glyph contrasts with the pane's own border weight
// (#470): a focused pane draws a heavy border, so its fill is `═`
// against `━`; an unfocused one draws light, so its fill is `━`
// against `─`. Counting the glyph that marks FILL keeps this test
// about the gauge rather than about which border weight is in force.
let fill_glyph = 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:?}"
);
// State 0 clears: the gauge and the pill percent both vanish.
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_rows(&term);
let border_row = &rows[(area.y + area.height - 1) as usize];
// No FILL glyph remains. `━` is the border's own glyph on a focused
// pane (#470), so a literal check here would fail on an intact border
// rather than on a leftover gauge.
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:?}"
);
// A pane's output carries colour (croft's own run header does, and so
// does any shell prompt), so the dump lands in the rendered log view
// (#257) rather than a plain scratch buffer; the text is read from the
// view once its index is complete and its window loaded.
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"
);
}
/// #257: Cmd+K D lands the pane's scrollback in the rendered log view, so
/// the colours the pane showed survive into the tab, written to a real file
/// under the scrollback dir because the log view indexes from disk.
#[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();
{
// The view indexes in the background and parses a window on demand:
// read only what it has actually loaded.
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"
);
}
/// The dump file is one per pane and overwritten on each Cmd+K D, so the
/// second dump must show the pane's NEW output, not the first dump's rows
/// through a stale index, and must not claim a fresh open it did not make.
#[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:?}"
);
}
/// The route gate and the open path's sniff must agree: the sniff reads only
/// the first 8 KiB, so colour that first appears beyond it must route to the
/// plain buffer, or the user gets an editable file full of raw escapes.
#[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");
}
/// A dump is a pinned tab of its own, as the scratch buffer was: a later
/// single-click file peek must not replace it, and two panes' dumps must
/// not share one preview slot.
#[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"
);
}
/// Two panes may carry the same label (two unnamed shells both read
/// `terminal`), so the dump file is keyed on the pane's stable uid too: the
/// second pane's dump must not overwrite and close the first pane's.
#[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"
);
}
/// A dump holds terminal output, so it is written owner-only: the dir is
/// 0700 and the file 0600 whatever the umask, so another local account
/// cannot read it.
#[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");
}
/// A dump file must not be shared across croft processes: the pane uid is
/// a per-process counter that restarts at 1, so the file name carries the
/// pid too, as the session handoff file does.
#[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}"
);
}
/// A stale tab from an earlier dump can live in ANY editor group, not only
/// the focused one, and every copy must go before the file is rewritten:
/// a tab left in another group would read the new bytes through its old
/// index and paint garbage, with nothing to heal it.
#[test]
fn a_second_dump_closes_the_stale_tab_in_every_editor_group() {
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}GRP\\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("QQGRP"))
},
);
app.open_scrollback_in_editor();
let path = app.editor.path.clone().expect("the first dump has a path");
// Split: the dump tab now sits in the left group; the right is focused.
app.split_editor();
app.focus_pane(Pane::Terminal);
app.open_scrollback_in_editor();
let stale_elsewhere = app
.editor_layout
.inactive_groups()
.iter()
.any(|g| g.find_tab_with_path(&path).is_some());
assert!(
!stale_elsewhere,
"no other group keeps a tab over the rewritten dump file"
);
assert!(
app.editor.find_tab_with_path(&path).is_some(),
"the focused group holds the rebuilt dump"
);
// The left group held nothing but the stale dump: closing its only tab
// leaves a blank group, which every other close path prunes; a dead
// blank pane the user never opened must not survive here either.
assert!(
app.editor_layout
.inactive_groups()
.iter()
.all(|g| !g.is_blank_initial()),
"an inactive group emptied by the close is pruned, not left blank"
);
}
/// The private write must never re-mode something it did not create through
/// a link: `set_permissions` follows symlinks, so a scrollback dir that is a
/// link is refused and its target keeps its mode. A real dir left loose by
/// an older run is tightened, and so is a stale dump file.
#[cfg(unix)]
#[test]
fn write_private_refuses_a_symlinked_dir_and_tightens_a_loose_one() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let loose = tmp.path().join("loose");
std::fs::create_dir(&loose).unwrap();
std::fs::set_permissions(&loose, std::fs::Permissions::from_mode(0o755)).unwrap();
let stale = loose.join("old.log");
std::fs::write(&stale, "old").unwrap();
std::fs::set_permissions(&stale, std::fs::Permissions::from_mode(0o644)).unwrap();
write_private(&loose, &stale, "new").expect("a real dir is written");
let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(
mode(&loose),
0o700,
"a loose dir from an older run is tightened"
);
assert_eq!(mode(&stale), 0o600, "and so is a stale dump file");
assert_eq!(std::fs::read_to_string(&stale).unwrap(), "new");
let target = tmp.path().join("target");
std::fs::create_dir(&target).unwrap();
std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o755)).unwrap();
let link = tmp.path().join("link");
std::os::unix::fs::symlink(&target, &link).unwrap();
let outcome = write_private(&link, &link.join("x.log"), "x");
assert!(
outcome.is_err(),
"a symlinked dir is refused, not written through"
);
assert_eq!(mode(&target), 0o755, "the link's target keeps its mode");
assert!(!target.join("x.log").exists(), "and gains no file");
// The same for the dump FILE: a link planted where the dump goes must
// not have its target truncated, overwritten and re-moded.
let outside = tmp.path().join("outside.txt");
std::fs::write(&outside, "secret").unwrap();
std::fs::set_permissions(&outside, std::fs::Permissions::from_mode(0o644)).unwrap();
let planted = loose.join("planted.log");
std::os::unix::fs::symlink(&outside, &planted).unwrap();
let outcome = write_private(&loose, &planted, "new");
assert!(outcome.is_err(), "a symlinked dump file is refused");
assert_eq!(
std::fs::read_to_string(&outside).unwrap(),
"secret",
"its target is untouched"
);
assert_eq!(mode(&outside), 0o644, "and keeps its mode");
}
/// The prune after a close is scoped to the group the close emptied: a
/// group the user left blank on purpose (a split with one side cleared) is
/// not this command's to fold away.
#[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();
// Split, blank the new (focused) group, then focus the group that holds
// the dump: the blank group is now an inactive leaf with no dump in it.
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()
.iter()
.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"
);
}
/// With two inactive groups, one emptied by the close and one the user
/// blanked, only the emptied one is pruned: the sweep must be scoped to the
/// group the close emptied, not to blankness.
#[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();
// [A(dump) | B(focused)] -> blank B -> focus A -> split A again:
// [[A(dump) | C(focused)] | B(blank)], so A and B are both inactive.
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();
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();
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"
);
}
/// A dump that cannot reach the disk still leaves the user the text: the
/// plain rows land in the scratch buffer and the status says why.
#[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();
// A file where the dir's parent should be: nothing can be created under it.
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
);
}
/// Dumps are named by pid, so a croft that exits leaves its dumps behind
/// with no process that will ever overwrite them; the next dump reaps the
/// files of pids that are gone and leaves live processes' files alone.
#[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();
// A pid that is certainly gone: a child that has already been reaped.
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();
// A pid no `pid_t` can hold reads as alive: a false "alive" only leaks
// a file, a false "dead" would delete one.
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");
}
/// The dump is a new on-disk copy of pane output, so the redact rules must
/// hold on disk too: the matching row is written masked (and gives up its
/// colour), while a neighbouring row keeps its colour.
#[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 timestamps_gutter_toggles_on_and_shows_arrival_times() {
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("g=gutter; echo ${g}-row-9; 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 \"gutter-row-9\"",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.starts_with("gutter-row-9"))
},
);
fn screen_rows(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> Vec<String> {
let buf = term.backend().buffer();
(0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
.collect()
})
.collect()
}
fn gutter_of(rows: &[String], needle: &str) -> Option<String> {
let row = rows.iter().find(|r| r.contains(needle))?;
let inner = row.trim_end().trim_end_matches(['│', '┃']);
Some(
inner
.chars()
.rev()
.take(8)
.collect::<String>()
.chars()
.rev()
.collect(),
)
}
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
// Off by default: the row ends with its own text, no clock.
term.draw(|f| app.render(f)).unwrap();
let g = gutter_of(&screen_rows(&term), "gutter-row-9").unwrap_or_default();
assert!(
!g.chars().filter(|c| *c == ':').count().eq(&2),
"no gutter while the toggle is off: {g:?}"
);
app.toggle_terminal_timestamps();
assert!(app.show_terminal_timestamps);
term.draw(|f| app.render(f)).unwrap();
let g = gutter_of(&screen_rows(&term), "gutter-row-9").expect("row still on screen");
let looks_like_clock = g.len() == 8
&& g.as_bytes()[2] == b':'
&& g.as_bytes()[5] == b':'
&& g.chars().filter(|c| c.is_ascii_digit()).count() == 6;
assert!(
looks_like_clock,
"the toggled gutter shows HH:MM:SS at the row's right edge: {g:?}"
);
app.toggle_terminal_timestamps();
term.draw(|f| app.render(f)).unwrap();
let g = gutter_of(&screen_rows(&term), "gutter-row-9").unwrap_or_default();
assert!(
!(g.len() == 8 && g.as_bytes()[2] == b':' && g.as_bytes()[5] == b':'),
"toggling off removes the gutter: {g:?}"
);
}
#[test]
fn sticky_command_header_pins_the_command_while_scrolled_into_its_output() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Full OSC 133 marks around a runtime-assembled command (the pane's
// `▶ …` run header echoes the script text, so the typed command must
// never appear verbatim in it), then enough output to scroll.
let script = "b=build; printf \"\\033]133;A\\007$ \\033]133;B\\007${b}-it-77 now\\n\\033]133;C\\007\"; i=0; while [ $i -lt 80 ]; do echo out-$i; i=$((i+1)); done; printf '\\033]133;D;0\\007'; sleep 30";
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from(script)],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the command to finish",
|| !app.terminals[0].command_decorations().is_empty(),
);
fn screen_rows(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> Vec<String> {
let buf = term.backend().buffer();
(0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
.collect()
})
.collect()
}
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;
// At the live bottom nothing pins.
let rows = screen_rows(&term);
assert!(
!rows[inner.y as usize].contains("build-it-77"),
"no header at the live bottom: {:?}",
rows[inner.y as usize]
);
// Scroll so the viewport's top row sits inside the command's output,
// with its prompt above the view: the typed command pins to row 0.
app.terminals[0].scroll_to_top();
for _ in 0..4 {
app.terminals[0].scroll_down(1);
}
term.draw(|f| app.render(f)).unwrap();
let rows = screen_rows(&term);
assert!(
rows[inner.y as usize].contains("build-it-77 now"),
"the command must pin to the pane's top row: {:?}",
rows[inner.y as usize]
);
// Back at the live bottom the header unpins.
app.terminals[0].reset_scrollback();
term.draw(|f| app.render(f)).unwrap();
let rows = screen_rows(&term);
assert!(
!rows[inner.y as usize].contains("build-it-77"),
"the header unpins at the live bottom: {:?}",
rows[inner.y as usize]
);
}
/// Copy-mode coordinates live in the App while the pane re-anchors its
/// selection to streaming content; each keystroke used to re-push the
/// stale absolute lines, teleporting the highlight off the text the user
/// was looking at.
#[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();
// The pane runs a real shell whose prompt arrives on its own schedule:
// under load it landed between the fed rows and the key press and moved
// the selection. Wait for the shell's output to settle first.
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));
// Five rows stream while the user pauses between keys; the pane
// re-anchors the selection to keep it on row-40.
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:?}"
);
}
/// Clicking an annotated span pops its note, but that branch used to
/// return before the mouse-up cleanup: the zero-area selection the
/// mouse-down planted stayed painted as a one-cell highlight and the
/// pane-drag latch stayed armed.
#[test]
fn clicking_an_annotated_span_still_clears_the_click_selection() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// A SILENT pane (#477). `App::new` spawns the user's interactive shell,
// whose prompt lands whenever the machine gets round to it; a prompt
// arriving between the anchor below and the click scrolled the
// annotation off the row the click was aimed at, and the popup
// assertion read as "annotation hover broke" on a merely busy host.
// A child that prints nothing cannot move the grid, so the only bytes
// on it are the ones this test feeds.
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(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
app.terminals[0].feed_bytes_for_test(b"annotated words here\r\n");
// Anchor the note to the grid line the text actually landed on and aim
// the click at that same line, rather than assuming both are row 0.
let line = app.terminals[0]
.find_captured_line("annotated words here")
.expect("the fed text is on the grid");
assert!(
line >= 0,
"with no scrollback the text sits on a viewport row, got line {line}"
);
let clock = app.terminals[0].scroll_clock();
app.terminals[0].add_annotation(line, clock, 0, 15, String::from("the note"));
let inner = app.terminals[0].last_inner;
let (cx, cy) = (inner.x + 2, inner.y + line as u16);
assert!(
app.terminals[0]
.line_text_at(cx, cy)
.is_some_and(|(text, idx)| text.starts_with("annotated words here") && idx == 2),
"the click must land ON the annotated text, or the popup assertion is vacuous"
);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), cx, cy));
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), cx, cy));
assert!(app.hover_popup.is_some(), "the click must pop the note");
assert!(
app.terminals[0].selection().is_none(),
"the zero-area click selection must not stay painted"
);
}
#[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");
// The shell's `dd` captures exactly what the click writes to the PTY.
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'"
);
}
/// An app that enables application cursor keys (DECCKM, `\e[?1h`) — Python's
/// REPL binds arrows from terminfo's application-mode entries — must receive
/// arrows and Home/End as SS3 (`\eOA`…), not the normal-mode CSI form the
/// REPL does not recognize (vitali87/croft#1).
#[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");
// The child turns on DECCKM, then `dd` captures exactly what the six
// key presses write to the PTY (six 3-byte sequences).
// The sentinel is assembled at runtime ("${s}DY_MARK") because the pane
// header echoes this script text verbatim; a literal sentinel would match
// before the child has run at all.
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"
);
}
/// Broadcast input fans one keystroke out to panes whose children disagree
/// about DECCKM. Each pane must receive the form its own child asked for
/// (bash's readline leaves DECCKM off while zsh turns it on, so mixed panes
/// are the normal case): pane 0 stays in normal mode and must get CSI, pane
/// 1 turns application cursor keys on and must get SS3.
#[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");
// Runtime-assembled sentinel: the pane header echoes the script text.
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 cmd_k_n_annotates_the_selection_and_a_click_shows_the_note() {
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("m=mark; echo ${m}-this-output; 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 \"mark-this-output\"",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.starts_with("mark-this-output"))
},
);
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 = (top
+ lines
.iter()
.position(|l| l.starts_with("mark-this-output"))
.unwrap() as i32) as u16;
// Select the word and annotate it through the prompt.
app.terminals[0].start_selection_at(inner.x, inner.y + vrow);
app.terminals[0].extend_selection_to(inner.x + 15, inner.y + vrow);
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('n'), KeyModifiers::NONE)));
assert!(
app.prompt.is_some(),
"Cmd+K N must open the annotation prompt"
);
app.prompt.as_mut().unwrap().buffer = String::from("broke here");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(app.prompt.is_none());
let (_, text) = app.terminals[0]
.annotation_at(inner.x + 3, inner.y + vrow)
.expect("the annotation must exist over the selected span");
assert_eq!(text, "broke here");
// The span renders amber + underlined.
term.draw(|f| app.render(f)).unwrap();
let style = term.backend().buffer()[(inner.x + 3, inner.y + vrow)].style();
assert_eq!(
style.fg,
Some(ratatui::style::Color::Rgb(0xe5, 0xc0, 0x7b)),
"annotated cells are tinted amber"
);
assert!(
style
.add_modifier
.contains(ratatui::style::Modifier::UNDERLINED),
"annotated cells are underlined"
);
// A plain click on the span pops the note.
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
inner.x + 3,
inner.y + vrow,
));
app.handle_mouse(mouse(
MouseEventKind::Up(MouseButton::Left),
inner.x + 3,
inner.y + vrow,
));
let popup = app
.hover_popup
.as_ref()
.expect("clicking the span shows the note");
assert!(
popup.lines.iter().any(|l| l.contains("broke here")),
"popup carries the note text"
);
// The note must actually be PAINTED, not just set. Regression: the
// hover popup rendered only inside the editor-tabs branch, so with the
// welcome screen up (no file open — exactly a fresh croft) the click
// set the popup but nothing ever drew it.
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let painted = (0..buf.area.height).any(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol())
.collect::<String>()
.contains("broke here")
});
assert!(
painted,
"the note popup must be painted on screen even with the welcome screen up"
);
// A real mouse drifts right after the click: the note must survive
// pointer motion while it stays on the annotated span, and dismiss
// once the pointer leaves it (regression: any move outside the editor
// used to kill the popup instantly).
app.handle_mouse(mouse(MouseEventKind::Moved, inner.x + 4, inner.y + vrow));
assert!(
app.hover_popup.is_some(),
"drifting within the span must keep the note open"
);
app.handle_mouse(mouse(MouseEventKind::Moved, inner.x + 60, inner.y + vrow));
assert!(
app.hover_popup.is_none(),
"leaving the span dismisses the note"
);
// Cmd+K Shift+N over the span deletes it.
app.terminals[0].start_selection_at(inner.x + 2, inner.y + vrow);
app.terminals[0].extend_selection_to(inner.x + 5, inner.y + vrow);
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('N'), KeyModifiers::SHIFT)));
assert!(
app.terminals[0]
.annotation_at(inner.x + 3, inner.y + vrow)
.is_none(),
"Cmd+K Shift+N deletes the annotation under the selection"
);
}
#[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, // defaults to the danger red
badge: Some(String::from("PROD")),
}]);
// Pane 0 reports a production hostname over OSC 7; pane 1 stays plain.
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:?}"
);
// The plain pane keeps croft's normal border color.
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() {
// Field report: mouse-down on a word mid-pane inside Claude Code,
// drag UP, and the highlight ran DOWNWARD instead — the drift math
// measured against the selection's top, which mid-drag is the pointer,
// so every event "corrected" a phantom shift and walked the anchor
// down. Reproduce through the production dispatch: an alt-screen
// mouse-tracking app, a press mid-pane, upward drags, with app
// repaints (animated status row) and renders between every event.
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();
// Few enough rows that nothing scrolls in the pane's alt grid. The
// modes are Claude Code's own pair: click-only 1000 with SGR 1006. Since
// #474 the press is forwarded to such a child, but a drag is croft's
// selection because the child never asked for motion -- under 1002 this
// same plain drag would be the app's and Shift would be needed.
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);
// Press on grid row 4, then drag up to rows 3 and 2, the app
// repainting its animated row and croft rendering between events.
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 participant_action_ids_round_trip() {
assert_eq!(
parse_participant_action("grant:3"),
Some((ParticipantVerb::Grant, 3))
);
assert_eq!(
parse_participant_action("revoke:0"),
Some((ParticipantVerb::Revoke, 0))
);
assert_eq!(
parse_participant_action("kick:12"),
Some((ParticipantVerb::Kick, 12))
);
assert_eq!(parse_participant_action("grant:"), None);
assert_eq!(parse_participant_action("promote:1"), None);
assert_eq!(parse_participant_action("grant"), None);
}
#[test]
fn participant_rows_show_role_and_size() {
let p = crate::session_host::Participant {
id: 7,
name: String::from("vitali@mac"),
cols: 120,
rows: 40,
control: true,
version: String::new(),
};
let row = participant_row(&p);
assert_eq!(row.id, "7");
assert!(row.label.contains("vitali@mac"));
assert!(row.label.contains("120\u{d7}40"));
assert!(row.label.contains("write"));
// Read-only guest with an unknown size (0x0 under `script`).
let p = crate::session_host::Participant {
id: 8,
name: String::from("guest@box"),
cols: 0,
rows: 0,
control: false,
version: String::new(),
};
let row = participant_row(&p);
assert!(row.label.contains("read-only"));
assert!(!row.label.contains("0\u{d7}0"));
}
#[test]
fn typist_change_stashes_and_restores_per_participant_carets() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("f.txt");
std::fs::write(&file, "hello world\nsecond line\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_at(&file, 0, 0).unwrap();
// Participant 1 starts typing with the cursor at (1, 3): no stash to
// restore, cursor untouched.
app.editor.cursor_row = 1;
app.editor.cursor_col = 3;
app.apply_typist_change(1);
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 3));
// Participant 1 moves to (0, 2); then participant 2 takes over: 1's
// caret is parked where they left it.
app.editor.cursor_row = 0;
app.editor.cursor_col = 2;
app.apply_typist_change(2);
let parked = app.session_carets.get(&1).expect("caret parked for 1");
assert_eq!((parked.row, parked.col), (0, 2));
// Participant 2 works at (1, 4); participant 1 returns: 2 is parked and
// 1's caret is restored.
app.editor.cursor_row = 1;
app.editor.cursor_col = 4;
app.apply_typist_change(1);
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 2));
let parked = app.session_carets.get(&2).expect("caret parked for 2");
assert_eq!((parked.row, parked.col), (1, 4));
// A parked caret past the end of a shrunken buffer restores clamped.
app.session_carets.insert(
3,
SessionCaret {
path: app.editor.path.clone().unwrap(),
row: 99,
col: 99,
},
);
app.apply_typist_change(3);
assert!(app.editor.cursor_row < app.editor.lines.len());
let line_len = app.editor.lines[app.editor.cursor_row].chars().count();
assert!(app.editor.cursor_col <= line_len);
}
/// Headless end-to-end of the Phase D live wiring: two Apps on the same
/// workspace (an owner and a solo guest) connected through a real relay
/// socket. The guest bootstraps the owner's buffer, edits flow both ways and
/// converge, the guest never echoes an applied edit back, and the save-owner
/// gates hold (guest Cmd+S is a no-op with a hint; the owner writes).
#[test]
fn collab_solo_apps_bootstrap_edit_and_gate_saves() {
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));
}
};
// Guest opens the shared file and bootstraps it from the owner's buffer.
pump_until(&mut owner, &mut guest, "bootstrap", &|_, g| {
g.collab.as_ref().is_some_and(|s| s.is_live("f.txt"))
});
// Guest types; the owner's buffer converges (through poll_collab's
// extract, the relay, and apply_collab_spans on the owner side).
guest.editor.insert_str("GUEST ");
pump_until(
&mut owner,
&mut guest,
"guest edit reaches owner",
&|o, _| o.editor.lines[0].contains("GUEST"),
);
// Concurrent edits from both sides converge to identical buffers.
owner.editor.cursor_row = 0;
owner.editor.cursor_col = 0;
owner.editor.insert_str("OWNER ");
pump_until(
&mut owner,
&mut guest,
"concurrent edits converge",
&|o, g| o.editor.lines == g.editor.lines && o.editor.lines[0].contains("OWNER"),
);
// Settle: buffer convergence does not imply the WIRE is drained (#56).
// Typing sends caret frames besides the edits, every drained event —
// a caret included — reports redraw-worthy from poll_collab, and the
// relay thread can deliver a trailing caret after the convergence
// predicate already passed. Drain those, bounded so a genuine echo
// storm still reaches the silence check below and fails there.
let settle = Instant::now() + Duration::from_secs(5);
loop {
let owner_drained = owner.poll_collab();
let guest_drained = guest.poll_collab();
if !owner_drained && !guest_drained {
break;
}
assert!(
Instant::now() < settle,
"the wire never went quiet: an echo storm, not a trailing caret"
);
std::thread::sleep(Duration::from_millis(2));
}
// No echo: with the wire drained and both sides idle, it stays quiet.
let settled = owner.editor.lines.clone();
for _ in 0..20 {
assert!(!owner.poll_collab(), "owner must be quiescent");
assert!(!guest.poll_collab(), "guest must be quiescent");
std::thread::sleep(Duration::from_millis(2));
}
assert_eq!(owner.editor.lines, settled);
assert_eq!(guest.editor.lines, settled);
// Save-owner gate: the guest's Cmd+S never writes shared files.
let disk_before = std::fs::read_to_string(&file).unwrap();
guest.save();
assert_eq!(std::fs::read_to_string(&file).unwrap(), disk_before);
assert!(
guest.status.contains("owner saves"),
"guest gets a hint, got: {}",
guest.status
);
// The owner writes the converged text.
owner.save();
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
settled.join("\n"),
"owner save must persist the converged buffer"
);
}
/// Splitting (or reopening) a live shared file loads the DISK copy, which
/// is stale by construction: a guest never writes shared files, so an
/// unsaved session's work exists only in buffers and replicas. The stale
/// duplicate used to become the active buffer, catch incoming spans at
/// nonsense offsets, and — on the first keystroke — broadcast a diff of
/// the live doc against the old disk text, reverting every peer to the
/// pre-session file. A fresh buffer of a live file must be seeded from the
/// replicated text, and every pane of the file must mirror the session.
#[test]
fn splitting_a_live_file_does_not_revert_the_session() {
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.as_ref().is_some_and(|s| s.is_live("f.txt"))
});
// An hour of unsaved session work, in miniature.
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")
});
let session_text = owner.editor.lines.clone();
// The guest splits: the duplicate is read from the stale disk copy.
guest.split_editor_dir(crate::app::editor_layout::SplitDir::Horizontal, true);
pump_until(
&mut owner,
&mut guest,
"the split pane seeds from the live doc, not the disk",
&|_, g| g.editor.lines == session_text,
);
// Typing in the split must extend the session, never revert it.
guest.editor.insert_str("MORE ");
pump_until(
&mut owner,
&mut guest,
"the split edit reaches the owner",
&|o, _| o.editor.lines[0].contains("MORE"),
);
assert!(
owner.editor.lines[0].contains("SESSION"),
"the pre-split session work survived, got: {:?}",
owner.editor.lines
);
// Both guest panes mirror the live document.
pump_until(&mut owner, &mut guest, "both panes mirror", &|o, g| {
g.editor.lines == o.editor.lines
&& g.editor_layout
.inactive_groups()
.iter()
.all(|grp| grp.editors.iter().all(|ed| ed.lines == o.editor.lines))
});
}
/// Losing the relay link must not be silent: the app detects the dead
/// channel, drops the session, and reconnects through the normal backoff
/// path. Before detection existed, `is_live` stayed true forever and the
/// guest typed into a buffer whose ops reached nobody.
#[test]
fn losing_the_relay_reconnects_instead_of_typing_into_the_void() {
use std::time::{Duration, Instant};
let tmp = tempfile::tempdir().unwrap();
let socket = tmp.path().join("collab.sock");
// A hand-rolled "relay": accepts, then hangs up on command.
let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
let mut guest = App::new(tmp.path().to_path_buf()).unwrap();
guest.collab_config = Some((socket.clone(), crate::collab::CollabRole::Guest));
guest.poll_collab();
assert!(guest.collab.is_some(), "first connect");
let (peer, _) = listener.accept().unwrap();
drop(peer); // the relay dies
// Detection: the dead session is dropped.
let deadline = Instant::now() + Duration::from_secs(3);
while guest.collab.is_some() {
assert!(
Instant::now() < deadline,
"the dead session was never dropped"
);
guest.poll_collab();
std::thread::sleep(Duration::from_millis(10));
}
// Recovery: a fresh session connects (the listener's backlog accepts).
let deadline = Instant::now() + Duration::from_secs(5);
while guest.collab.is_none() {
assert!(Instant::now() < deadline, "never reconnected");
guest.poll_collab();
std::thread::sleep(Duration::from_millis(50));
}
}
/// A guest whose bootstrap nobody answered degrades to plain local editing,
/// as the timeout promises: the input gate lifts, the file stays local-only
/// (no re-request re-arming the gate every 3 seconds), and the guest's save
/// writes to disk — with no owner there is no other author to defer to, so
/// a refused save meant the work could never persist anywhere.
#[test]
fn a_guest_without_an_owner_degrades_to_local_editing_and_saves() {
use std::time::{Duration, Instant};
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("f.txt");
std::fs::write(&file, "hello").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));
}
// A guest alone on the relay: nobody answers its snapshot request.
let mut guest = App::new(tmp.path().to_path_buf()).unwrap();
guest.collab_config = Some((socket.clone(), crate::collab::CollabRole::Guest));
guest.open_file_at_launch(&file);
let deadline = Instant::now() + Duration::from_secs(8);
loop {
guest.poll_collab();
if let Some(s) = guest.collab.as_ref()
&& s.is_local_only("f.txt")
{
break;
}
assert!(Instant::now() < deadline, "bootstrap never gave up");
std::thread::sleep(Duration::from_millis(20));
}
// Later ticks must not re-arm the bootstrap gate.
for _ in 0..5 {
guest.poll_collab();
}
assert!(
!guest.collab.as_ref().unwrap().is_bootstrapping("f.txt"),
"the tick re-armed the input gate after the give-up"
);
// The guest is the only author: its save persists.
guest.editor.insert_str("LOCAL ");
guest.save();
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
guest.editor.lines.join("\n"),
"the degraded file's save must reach disk, got status: {}",
guest.status
);
}
/// The `file` key in a snapshot request comes straight off the wire: a
/// traversing or absolute key must never resolve outside the workspace, or
/// any guest (the MCP collab agent included) could make the owner read,
/// broadcast, and even edit arbitrary files it can reach.
#[test]
fn a_traversing_wire_file_key_is_declined() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("workspace");
std::fs::create_dir(&root).unwrap();
std::fs::write(tmp.path().join("secret.txt"), "SECRET").unwrap();
std::fs::write(root.join("inner.txt"), "inner").unwrap();
let mut app = App::new(root.clone()).unwrap();
assert_eq!(
app.owner_buffer_text(&root, "../secret.txt"),
None,
"a traversing wire key must not escape the workspace root"
);
assert_eq!(
app.owner_buffer_text(&root, "sub/../../secret.txt"),
None,
"a mid-path traversal must not escape the workspace root"
);
assert_eq!(
app.owner_buffer_text(&root, "/etc/hosts"),
None,
"an absolute wire key must not leave the workspace root"
);
assert_eq!(
app.owner_buffer_text(&root, "inner.txt").as_deref(),
Some("inner"),
"a plain relative key still resolves"
);
}
/// Lexical containment is not enough: a normal-looking wire key can name a
/// symlink inside the workspace whose target lies outside it, and the
/// owner-side open would follow the link — disclosing (and editing) files
/// beyond the share. Symlinked keys must resolve inside the workspace or be
/// declined; intra-workspace symlinks keep working.
#[test]
fn a_symlinked_wire_file_key_cannot_escape_the_workspace() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("workspace");
std::fs::create_dir(&root).unwrap();
std::fs::write(tmp.path().join("secret.txt"), "SECRET").unwrap();
std::fs::write(root.join("inner.txt"), "inner").unwrap();
std::os::unix::fs::symlink(tmp.path().join("secret.txt"), root.join("leak.txt")).unwrap();
std::fs::create_dir(tmp.path().join("outside")).unwrap();
std::fs::write(tmp.path().join("outside").join("deep.txt"), "DEEP").unwrap();
std::os::unix::fs::symlink(tmp.path().join("outside"), root.join("sub")).unwrap();
std::os::unix::fs::symlink(root.join("inner.txt"), root.join("alias.txt")).unwrap();
let mut app = App::new(root.clone()).unwrap();
assert_eq!(
app.owner_buffer_text(&root, "leak.txt"),
None,
"a symlink to a file outside the workspace must be declined"
);
assert_eq!(
app.owner_buffer_text(&root, "sub/deep.txt"),
None,
"a path through a symlinked directory must not escape the workspace"
);
assert_eq!(
app.owner_buffer_text(&root, "alias.txt").as_deref(),
Some("inner"),
"a symlink resolving inside the workspace still works"
);
}
/// An edit the guest made while the relay link was down exists nowhere but
/// its buffer: the op never reached the owner. Reconnection bootstraps from
/// the owner's older snapshot, and replacing the buffer with it silently
/// deleted the offline work. The divergence must instead be re-injected as
/// local edits, so the guest keeps its work and the owner receives it.
#[test]
fn reconnecting_replays_offline_guest_edits_instead_of_deleting_them() {
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.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")
});
// The link dies: drive the same teardown poll_collab runs after
// detecting a dead channel (session dropped, config kept). Hold the
// reconnect backoff while the guest keeps typing offline.
let dead = guest.collab.take().unwrap();
guest.drop_lost_collab_session(dead);
guest.last_collab_connect = Some(Instant::now());
guest.editor.insert_str("OFFLINE ");
let offline_text = guest.editor.lines.clone();
// Reconnect: the file re-bootstraps from the owner's older snapshot.
guest.last_collab_connect = None;
pump_until(&mut owner, &mut guest, "reconnect goes live", &|_, g| {
g.collab.as_ref().is_some_and(|s| s.is_live("f.txt"))
});
assert!(
guest.editor.lines[0].contains("OFFLINE"),
"the bootstrap deleted the guest's offline edit, got: {:?}",
guest.editor.lines
);
assert_eq!(
guest.editor.lines, offline_text,
"the guest's buffer must survive the reconnect intact"
);
// The offline edit reaches the owner: nothing was lost.
pump_until(
&mut owner,
&mut guest,
"the offline edit reaches the owner",
&|o, g| o.editor.lines == g.editor.lines && o.editor.lines[0].contains("OFFLINE"),
);
}
/// The converse of the replay test above: while the guest was offline, the
/// OWNER also edited the file. The guest's whole diverged buffer replayed
/// over the reconnect bootstrap used to read the owner's unseen edit as a
/// deletion and strip it from every replica. The reconnect must merge the
/// guest's offline delta with the owner's snapshot (three-way, against the
/// last shared text harvested when the link died).
#[test]
fn reconnect_replay_preserves_owner_edits_made_during_the_outage() {
use std::time::{Duration, Instant};
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("f.txt");
std::fs::write(&file, "alpha\nbeta\ngamma").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.as_ref().is_some_and(|s| s.is_live("f.txt"))
});
// The guest's link dies through the real teardown (which harvests the
// merge base); it edits line 1 offline while the owner edits line 3.
let dead = guest.collab.take().unwrap();
guest.drop_lost_collab_session(dead);
guest.last_collab_connect = Some(Instant::now());
guest.editor.insert_str("OFFLINE ");
let owner_pump = |owner: &mut App| {
let deadline = Instant::now() + Duration::from_secs(1);
while Instant::now() < deadline {
owner.poll_collab();
std::thread::sleep(Duration::from_millis(5));
}
};
owner.editor.cursor_row = 2;
owner.editor.cursor_col = 0;
owner.editor.insert_str("OWNER ");
owner_pump(&mut owner);
// Reconnect: both offline-era edits must survive, everywhere.
guest.last_collab_connect = None;
pump_until(&mut owner, &mut guest, "reconnect goes live", &|_, g| {
g.collab.as_ref().is_some_and(|s| s.is_live("f.txt"))
});
pump_until(
&mut owner,
&mut guest,
"both offline-era edits converge on every replica",
&|o, g| {
// `get`, not indexing: if the merge dropped a line, the test must
// fail at the deadline with "never settled", not panic here.
o.editor.lines == g.editor.lines
&& o.editor
.lines
.first()
.is_some_and(|l| l.contains("OFFLINE"))
&& o.editor.lines.get(2).is_some_and(|l| l.contains("OWNER"))
},
);
}
/// Diff, image, and sheet tabs can carry a shared file's path (a diff tab
/// stores it so close-by-path works), but their `lines` are not documents:
/// the collab passes must never seed, span-splice, or mark them — and a
/// diff tab sitting earlier in the tab strip must not shadow the real text
/// tab out of receiving the session's updates.
#[test]
fn collab_never_touches_diff_image_or_sheet_tabs() {
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);
// The guest's diff tab lands at index 0, AHEAD of the text tab: a
// first-found-by-path lookup would hand it the session's updates.
guest.editor.open_diff(&file, &file).unwrap();
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.as_ref().is_some_and(|s| s.is_live("f.txt"))
});
owner.editor.insert_str("OWNER ");
pump_until(
&mut owner,
&mut guest,
"the owner edit reaches the guest text tab",
&|o, g| g.editor.lines == o.editor.lines && g.editor.lines[0].contains("OWNER"),
);
let diff_tab = &guest.editor.editors[0];
assert!(diff_tab.diff.is_some(), "the diff tab survived");
assert_eq!(
diff_tab.collab_doc_gen, 0,
"a diff tab must never be marked as an attached collab buffer"
);
assert!(
!diff_tab.lines.join("\n").contains("hello"),
"the collab passes seeded document text into a diff tab"
);
}
/// A keystroke into a fresh, not-yet-attached pane of a live file (a split
/// or reopen holding stale disk text) used to land in the stale buffer and
/// be silently wiped when the attach pass seeded the pane one tick later.
/// The bootstrap input gate must cover this window too: refuse the key
/// with a hint instead of losing it.
#[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.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")
});
// The split duplicate holds stale disk text and has not attached yet;
// a keystroke arriving before the next tick must be refused, not
// absorbed into text the attach pass is about to replace.
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"
);
}
/// While the relay link is down there is no session to defer to: the guest
/// editing offline must be able to save its shared file, or a permanent
/// relay outage strands the work in RAM forever (the save gate used to
/// treat a missing session as "shared, owner saves").
#[test]
fn a_disconnected_guest_can_still_save_its_shared_file() {
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.as_ref().is_some_and(|s| s.is_live("f.txt"))
});
// The link dies; the guest keeps editing offline and saves.
guest.collab = None;
guest.last_collab_connect = Some(Instant::now());
guest.editor.insert_str("OFF ");
guest.save();
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
guest.editor.lines.join("\n"),
"a disconnected guest's save must reach disk, got status: {}",
guest.status
);
}
/// Two split panes of a shared file edited while the link is down must both
/// keep their work through the reconnect. Panes cannot converge through the
/// doc while there is no session, so the active pane (the only one input
/// reaches) mirrors onto its siblings — the reconnect then replays exactly
/// one offline text per file, holding every edit.
#[test]
fn offline_edits_in_split_panes_all_survive_a_reconnect() {
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.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);
let session_text = owner.editor.lines.clone();
pump_until(&mut owner, &mut guest, "both panes attach", &|_, g| {
g.editor.lines == session_text
&& g.editor_layout
.inactive_groups()
.iter()
.all(|grp| grp.editors.iter().all(|ed| ed.lines == session_text))
});
// The link dies. Both panes are edited while offline.
guest.collab = None;
guest.last_collab_connect = Some(Instant::now());
guest.editor.insert_str("RIGHT ");
guest.poll_collab();
guest.focus_editor_group(true);
guest.editor.insert_str("LEFT ");
guest.poll_collab();
// Reconnect: every offline edit must reach the owner.
guest.last_collab_connect = None;
pump_until(
&mut owner,
&mut guest,
"both offline edits reach the owner",
&|o, _| {
let text = o.editor.lines.join("\n");
text.contains("RIGHT") && text.contains("LEFT")
},
);
}
/// The cancel affordances around the AI stream: Cmd+K X and the palette
/// entry both route through `collab_cancel_stream` (hint when idle), and
/// the gutter stop button's row follows the pilot's caret in the streamed
/// file, falling back to the top visible row.
#[test]
fn cmd_k_x_cancels_the_ai_stream_and_the_stop_row_follows_the_pilot_caret() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("f.txt");
std::fs::write(&file, "l0\nl1\nl2\nl3\nl4\nl5\nl6").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_at(&file, 0, 0).unwrap();
// The chord is always consumed; idle it hints instead of broadcasting.
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('x'), KeyModifiers::NONE)));
assert!(
app.status.to_lowercase().contains("no ai stream"),
"idle chord hints, got: {}",
app.status
);
// No stream: no stop row.
assert_eq!(app.stream_stop_row(), None);
// A stream into the active file with no pilot caret yet: the top
// visible row wears the button.
app.collab_stream = Some(CollabStreamInfo {
file: "f.txt".into(),
name: "pilot".into(),
site: 7,
});
assert_eq!(app.stream_stop_row(), Some(app.editor.scroll));
// The pilot's ghost caret pins the row.
app.collab_carets.insert(
7,
CollabCaret {
file: "f.txt".into(),
row: 5,
col: 2,
name: "pilot".into(),
last_moved: std::time::Instant::now(),
},
);
assert_eq!(app.stream_stop_row(), Some(5));
// A stream into a file that is not active here shows no button.
app.collab_stream.as_mut().unwrap().file = "other.txt".into();
assert_eq!(app.stream_stop_row(), None);
// The palette entry drives the same action.
app.status.clear();
app.run_command(crate::widgets::command_palette::Command::CollabCancelStream);
assert!(
app.status.to_lowercase().contains("no ai stream"),
"palette cancel hints when idle, got: {}",
app.status
);
}
/// The resident navigator: an enabled pair record seats the pilot within a
/// throttled tick, a plain-launch croft self-appoints the collab OWNER seat
/// (nobody else would answer the pilot's snapshot requests), and a disabled
/// record unseats it.
#[test]
fn navigator_record_seats_the_pilot_and_self_appoints_owner() {
use std::time::{Duration, Instant};
if !crate::lsp::manager::is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("f.txt"), "l0\nl1\nl2").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 script = tmp.path().join("fake_claude.py");
std::fs::write(&script, crate::pair::FAKE_CLAUDE).unwrap();
let log = tmp.path().join("stdin.log");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.pair_record_path = tmp.path().join("x.pair.json");
app.pair_socket = socket.clone();
app.pair_host_lock_path = tmp.path().join("x.pair-host.lock");
let (script2, log2, socket2) = (script.clone(), log.clone(), socket.clone());
app.pair_spawn_override = Some(Box::new(move |cfg| {
let mut cmd = std::process::Command::new("python3");
cmd.arg(&script2).arg(&log2).arg("notes");
crate::pair_host::PairHost::spawn_cmd(&socket2, &cfg.name, cfg.task.as_deref(), cmd)
}));
// No record yet: nothing seats.
assert!(!app.maybe_seat_navigator());
assert!(app.pair_host.is_none());
crate::session::write_pair_record(
&app.pair_record_path,
&crate::session::PairRecord {
model: None,
name: "navigator".into(),
enabled: true,
task: None,
provider: None,
base_url: None,
},
)
.unwrap();
assert!(app.collab_config.is_none(), "plain launch precondition");
app.last_pair_check = None;
assert!(app.maybe_seat_navigator());
assert!(app.pair_host.is_some(), "pilot must seat");
assert_eq!(
app.collab_config,
Some((socket.clone(), crate::collab::CollabRole::Owner)),
"plain launch self-appoints the owner seat"
);
assert!(
app.status.to_lowercase().contains("seated"),
"got: {}",
app.status
);
// The self-appointed seat actually connects.
let deadline = Instant::now() + Duration::from_secs(5);
while app.collab.is_none() {
assert!(Instant::now() < deadline, "owner seat never connected");
app.poll_collab();
std::thread::sleep(Duration::from_millis(5));
}
// A real parked caret: an ask turn on f.txt (served by this window's
// owner seat) bootstraps the pilot's replica and parks its caret at the
// asked row. The seat's identity is its site ids, never its name.
app.pair_host
.as_ref()
.unwrap()
.send_ask_turn("f.txt", (1, 1), "", "look here", "l0\nl1\nl2")
.unwrap();
let deadline = Instant::now() + Duration::from_secs(10);
let pilot_sites = loop {
app.poll_collab();
let sites = app.pair_host.as_ref().unwrap().caret_sites();
if sites.iter().any(|s| app.collab_carets.contains_key(s)) {
break sites;
}
assert!(
Instant::now() < deadline,
"the pilot's parked caret never reached the app"
);
std::thread::sleep(Duration::from_millis(10));
};
// A human who picked the very same display name is not the navigator.
app.collab_carets.insert(
9999,
CollabCaret {
file: "f.txt".into(),
row: 0,
col: 0,
name: "navigator".into(),
last_moved: Instant::now(),
},
);
// Disabled record: the host unseats on the next check.
crate::session::write_pair_record(
&app.pair_record_path,
&crate::session::PairRecord {
model: None,
name: "navigator".into(),
enabled: false,
task: None,
provider: None,
base_url: None,
},
)
.unwrap();
app.last_pair_check = None;
assert!(app.maybe_seat_navigator());
assert!(app.pair_host.is_none(), "pilot must unseat");
assert!(
!pilot_sites
.iter()
.any(|s| app.collab_carets.contains_key(s)),
"the unseated navigator's caret must not linger"
);
assert!(
app.collab_carets.contains_key(&9999),
"a human named like the navigator keeps their caret"
);
}
/// The navigator's caret wears its fixed identity accent (the same orange
/// as its comment boxes); human collaborators keep the join-order palette.
/// Identity is the seat's site ids, never its display name: names are
/// neither unique (a human may pick the same one) nor length-stable (caret
/// names truncate to 24 chars at ingest).
#[test]
fn navigator_caret_wears_its_accent_and_humans_keep_the_palette() {
assert_eq!(
collab_caret_color(&[3, 7], 3),
crate::widgets::editor::NAVIGATOR_ACCENT
);
assert_eq!(collab_caret_color(&[3, 7], 5), participant_color(5));
assert_eq!(collab_caret_color(&[], 3), participant_color(3));
}
/// A record activated with `--provider ollama` seats the pilot with the
/// Local provider and its recorded endpoint, not the claude default.
#[test]
fn app_seats_local_provider_from_record() {
let tmp = tempfile::tempdir().unwrap();
let socket = tmp.path().join("collab.sock");
type SeenConfig = Option<(crate::pair::Provider, Option<String>)>;
let seen: std::rc::Rc<std::cell::RefCell<SeenConfig>> =
std::rc::Rc::new(std::cell::RefCell::new(None));
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.pair_record_path = tmp.path().join("x.pair.json");
app.pair_socket = socket.clone();
app.pair_host_lock_path = tmp.path().join("x.pair-host.lock");
// Already the owner (skip the relay bootstrap): the test exercises the
// provider mapping, not collab connect.
app.collab_config = Some((socket, crate::collab::CollabRole::Owner));
let seen2 = seen.clone();
app.pair_spawn_override = Some(Box::new(move |cfg| {
*seen2.borrow_mut() = Some((cfg.provider.clone(), cfg.model.clone()));
anyhow::bail!("captured the config; no seat needed")
}));
crate::session::write_pair_record(
&app.pair_record_path,
&crate::session::PairRecord {
model: Some("qwen3-coder:30b".into()),
name: "navigator".into(),
enabled: true,
task: None,
provider: Some("ollama".into()),
base_url: Some("http://localhost:11500".into()),
},
)
.unwrap();
app.last_pair_check = None;
assert!(app.maybe_seat_navigator());
assert_eq!(
*seen.borrow(),
Some((
crate::pair::Provider::Local {
base_url: "http://localhost:11500".into()
},
Some(String::from("qwen3-coder:30b")),
)),
"the recorded provider and model must reach the seat config"
);
}
/// A dead pilot is not respawned every second: after a death (or a failed
/// seat) the navigator stays down until the record is deactivated and
/// re-enabled, matching the "re-activate to reseat" contract and the LSP
/// no-auto-respawn precedent.
#[test]
fn a_dead_navigator_is_not_respawned_until_reactivated() {
let tmp = tempfile::tempdir().unwrap();
let socket = tmp.path().join("collab.sock");
let seats = std::rc::Rc::new(std::cell::Cell::new(0usize));
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.pair_record_path = tmp.path().join("x.pair.json");
app.pair_socket = socket.clone();
app.pair_host_lock_path = tmp.path().join("x.pair-host.lock");
// Already the owner (skip the relay bootstrap): the test exercises the
// death latch, not collab connect.
app.collab_config = Some((socket, crate::collab::CollabRole::Owner));
let seats2 = seats.clone();
app.pair_spawn_override = Some(Box::new(move |_cfg| {
seats2.set(seats2.get() + 1);
anyhow::bail!("scripted seat failure");
}));
let enabled = |a: &mut App| {
crate::session::write_pair_record(
&a.pair_record_path,
&crate::session::PairRecord {
model: None,
name: "nav".into(),
enabled: true,
task: None,
provider: None,
base_url: None,
},
)
.unwrap();
a.last_pair_check = None;
};
// First tick: it tries once, fails, and latches down.
enabled(&mut app);
app.maybe_seat_navigator();
assert_eq!(seats.get(), 1, "one seat attempt");
assert!(
app.navigator_down,
"a failed seat latches the navigator down"
);
// Many more ticks with the record still enabled: NO respawn storm.
for _ in 0..5 {
app.last_pair_check = None;
app.maybe_seat_navigator();
}
assert_eq!(seats.get(), 1, "a latched navigator must not be respawned");
// Deactivate, then re-enable: the latch clears and it tries again.
crate::session::write_pair_record(
&app.pair_record_path,
&crate::session::PairRecord {
model: None,
name: "nav".into(),
enabled: false,
task: None,
provider: None,
base_url: None,
},
)
.unwrap();
app.last_pair_check = None;
app.maybe_seat_navigator();
assert!(!app.navigator_down, "deactivation clears the latch");
enabled(&mut app);
app.maybe_seat_navigator();
assert_eq!(seats.get(), 2, "re-activation retries the seat");
}
/// Resident seating never replays a persisted task: a stale record carrying
/// a task must not re-execute an instruction against the buffer on every
/// launch (and an @file task would freeze the UI thread on seat).
#[test]
fn resident_seating_never_replays_a_persisted_task() {
let tmp = tempfile::tempdir().unwrap();
let socket = tmp.path().join("collab.sock");
let seen_task = std::rc::Rc::new(std::cell::RefCell::new(Some(String::from("sentinel"))));
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.pair_record_path = tmp.path().join("x.pair.json");
app.pair_socket = socket.clone();
app.pair_host_lock_path = tmp.path().join("x.pair-host.lock");
app.collab_config = Some((socket, crate::collab::CollabRole::Owner));
let seen2 = seen_task.clone();
app.pair_spawn_override = Some(Box::new(move |cfg| {
*seen2.borrow_mut() = cfg.task.clone();
anyhow::bail!("stop before a real child");
}));
crate::session::write_pair_record(
&app.pair_record_path,
&crate::session::PairRecord {
model: None,
name: "nav".into(),
enabled: true,
task: Some("delete the deprecated helpers".into()),
provider: None,
base_url: None,
},
)
.unwrap();
app.last_pair_check = None;
app.maybe_seat_navigator();
assert_eq!(
*seen_task.borrow(),
None,
"the seat must never carry a persisted task"
);
}
/// F4 visits notes in file (row) order and wraps, regardless of the order
/// they streamed in. Landing order [(10,..),(2,..)] must not strand the
/// row-2 note or stick on row 10.
#[test]
fn next_note_by_row_walks_rows_in_order_and_wraps() {
let notes = vec![
(1u64, 10usize, String::from("late")),
(2u64, 2usize, String::from("early")),
(3u64, 6usize, String::from("mid")),
];
// From the top: nearest row strictly greater.
assert_eq!(notes[super::next_note_by_row(¬es, (0, usize::MAX))].1, 2);
assert_eq!(notes[super::next_note_by_row(¬es, (2, usize::MAX))].1, 6);
assert_eq!(
notes[super::next_note_by_row(¬es, (6, usize::MAX))].1,
10
);
// Past the last note: wrap to the smallest row (not stick on row 10).
assert_eq!(
notes[super::next_note_by_row(¬es, (10, usize::MAX))].1,
2
);
assert_eq!(
notes[super::next_note_by_row(¬es, (99, usize::MAX))].1,
2
);
}
/// The palette off/on round trip must keep the seat's backend: writing
/// `provider: None` silently reseated a local-only ollama navigator on the
/// cloud claude CLI - shipping the workspace to a remote service the user
/// explicitly avoided, under a model name claude does not have.
#[test]
fn toggling_the_navigator_preserves_its_provider() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.pair_record_path = tmp.path().join("pair.json");
crate::session::write_pair_record(
&app.pair_record_path,
&crate::session::PairRecord {
model: Some(String::from("qwen3-coder:30b")),
name: String::from("navigator"),
enabled: true,
task: None,
provider: Some(String::from("ollama")),
base_url: Some(String::from("http://localhost:11434")),
},
)
.unwrap();
app.toggle_navigator(); // off
let mid = crate::session::read_pair_record(&app.pair_record_path).unwrap();
assert!(!mid.enabled, "the first toggle really deactivates");
assert_eq!(mid.name, "navigator");
assert_eq!(mid.provider.as_deref(), Some("ollama"));
assert_eq!(mid.base_url.as_deref(), Some("http://localhost:11434"));
assert_eq!(mid.model.as_deref(), Some("qwen3-coder:30b"));
app.toggle_navigator(); // back on
let r = crate::session::read_pair_record(&app.pair_record_path).unwrap();
assert!(r.enabled);
assert_eq!(r.provider.as_deref(), Some("ollama"));
assert_eq!(r.base_url.as_deref(), Some("http://localhost:11434"));
assert_eq!(r.model.as_deref(), Some("qwen3-coder:30b"));
assert_eq!(r.name, "navigator", "the seat keeps its name too");
}
/// Collab carets are keyed by root-relative file paths: after a re-root, a
/// same-named file under the new root would wear a departed peer's caret
/// from the old workspace. Re-rooting clears them; a live session
/// repopulates its own on the next poll.
#[test]
fn changing_the_workspace_root_drops_stale_collab_carets() {
let tmp = tempfile::tempdir().unwrap();
let inner = tmp.path().join("inner");
std::fs::create_dir_all(&inner).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.collab_carets.insert(
7,
CollabCaret {
file: String::from("src/main.rs"),
row: 3,
col: 1,
name: String::from("guest"),
last_moved: std::time::Instant::now(),
},
);
app.change_workspace_root(inner);
assert!(
app.collab_carets.is_empty(),
"old-workspace carets must not survive a re-root"
);
}
/// Replying anchors the navigator's answer on the answered note's own row,
/// so two notes on one row is the NORMAL state after one reply. The index
/// tie-break must step through both and wrap - a row-only walk went
/// first-note → first-note forever and the answer was unreachable by F4.
#[test]
fn next_note_by_row_steps_through_co_anchored_notes() {
let notes = vec![
(1u64, 5usize, String::from("original")),
(2u64, 5usize, String::from("answer")),
];
// Focused on the first note at row 5: F4 reaches its co-anchored answer.
assert_eq!(super::next_note_by_row(¬es, (5, 0)), 1);
// Focused on the answer: F4 wraps back to the first.
assert_eq!(super::next_note_by_row(¬es, (5, 1)), 0);
// From a bare caret on that row, neither is "past" it: wrap to first.
assert_eq!(super::next_note_by_row(¬es, (5, usize::MAX)), 0);
}
/// Only one croft self-appoints the navigator owner per workspace: a second
/// plain croft is refused the single-host lock and must NOT seat (two owners
/// would both claim collab site id 1 and corrupt the shared buffer).
#[test]
fn only_one_croft_self_appoints_the_navigator_owner() {
use std::time::{Duration, Instant};
let tmp = tempfile::tempdir().unwrap();
let socket = tmp.path().join("collab.sock");
let lock_path = tmp.path().join("host.lock");
{
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 enable = |a: &mut App| {
crate::session::write_pair_record(
&a.pair_record_path,
&crate::session::PairRecord {
model: None,
name: "nav".into(),
enabled: true,
task: None,
provider: None,
base_url: None,
},
)
.unwrap();
a.last_pair_check = None;
};
// Croft A grabs the single-host lock, self-appoints, and HOSTS (a
// local-provider seat spawns no child): the lock is only kept by a
// window that actually holds the seat.
let mut a = App::new(tmp.path().to_path_buf()).unwrap();
a.pair_record_path = tmp.path().join("a.pair.json");
a.pair_socket = socket.clone();
a.pair_host_lock_path = lock_path.clone();
a.pair_spawn_override = Some(Box::new(local_test_spawn));
enable(&mut a);
a.maybe_seat_navigator();
assert!(a.pair_host.is_some(), "A must host: {}", a.status);
assert!(
a.pair_host_lock.is_some(),
"A must hold the single-host lock"
);
// Croft B, same workspace: with a live relay, WITHOUT the lock gate it
// would self-appoint and reach the spawn (panic). The gate must refuse it.
let mut b = App::new(tmp.path().to_path_buf()).unwrap();
b.pair_record_path = tmp.path().join("b.pair.json");
b.pair_socket = socket.clone();
b.pair_host_lock_path = lock_path.clone();
b.pair_spawn_override = Some(Box::new(|_| panic!("a second croft must never host")));
enable(&mut b);
b.maybe_seat_navigator();
assert!(b.pair_host.is_none(), "B must not host");
assert!(b.pair_host_lock.is_none(), "B must not hold the lock");
assert!(
b.status.to_lowercase().contains("another croft"),
"B must say another croft hosts it, got: {}",
b.status
);
// The refusal is announced ONCE. B keeps silently polling for takeover,
// but re-announcing every second clobbered its status line forever and
// dirtied a frame at 1 Hz.
b.status = String::from("Saved src/foo.rs");
b.last_pair_check = None;
let redraw = b.maybe_seat_navigator();
assert!(!redraw, "an unchanged refusal must not dirty the frame");
assert_eq!(
b.status, "Saved src/foo.rs",
"the refusal must not clobber the status line again"
);
}
/// A lock file croft cannot open is not another window (#337): the status
/// names the path and the error, never "another croft". And the refusal is
/// latched by KIND: when the reason changes (the directory appears but a
/// second window now holds the flock) the new reason is announced, and
/// when the lock frees this window hosts.
#[test]
fn an_unopenable_host_lock_is_reported_as_such_and_re_announced_when_the_reason_changes() {
use std::time::{Duration, Instant};
let tmp = tempfile::tempdir().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 lock_dir = tmp.path().join("no-such-dir");
let lock_path = lock_dir.join("host.lock");
let mut b = App::new(tmp.path().to_path_buf()).unwrap();
b.pair_record_path = tmp.path().join("b.pair.json");
b.pair_socket = socket.clone();
b.pair_host_lock_path = lock_path.clone();
b.pair_spawn_override = Some(Box::new(local_test_spawn));
crate::session::write_pair_record(
&b.pair_record_path,
&crate::session::PairRecord {
model: None,
name: "nav".into(),
enabled: true,
task: None,
provider: None,
base_url: None,
},
)
.unwrap();
b.last_pair_check = None;
b.maybe_seat_navigator();
assert!(b.pair_host.is_none(), "cannot host without the lock");
assert!(
b.status.contains("cannot open host lock") && b.status.contains("no-such-dir"),
"an unopenable lock names the path and the error, got: {}",
b.status
);
assert!(
!b.status.to_lowercase().contains("another croft"),
"an open failure must never be blamed on another window: {}",
b.status
);
// Same reason next tick: quiet.
b.status = String::from("Saved src/foo.rs");
b.last_pair_check = None;
assert!(
!b.maybe_seat_navigator(),
"an unchanged refusal stays quiet"
);
assert_eq!(b.status, "Saved src/foo.rs");
// The directory appears, but another window holds the flock: the
// reason changed, so it is announced.
std::fs::create_dir_all(&lock_dir).unwrap();
let holder = crate::session::try_acquire_pair_host_lock(&lock_path).expect("holder acquires");
b.last_pair_check = None;
assert!(
b.maybe_seat_navigator(),
"a changed reason dirties the frame"
);
assert!(
b.status.to_lowercase().contains("another croft"),
"now it IS another window, got: {}",
b.status
);
// The reverse transition: the holder is still there but the lock's
// directory vanishes, so the refusal is an open failure again - and
// that change of reason is announced too.
std::fs::remove_dir_all(&lock_dir).unwrap();
b.last_pair_check = None;
assert!(b.maybe_seat_navigator(), "Busy -> Io is a changed reason");
assert!(
b.status.contains("cannot open host lock"),
"the open failure is named again, got: {}",
b.status
);
std::fs::create_dir_all(&lock_dir).unwrap();
// The holder exits: this window takes over.
drop(holder);
b.last_pair_check = None;
b.maybe_seat_navigator();
assert!(
b.pair_host.is_some(),
"B hosts once the lock frees: {}",
b.status
);
assert!(b.pair_host_lock.is_some());
}
/// A local-provider seat for tests: connects to the workspace relay but
/// spawns no child process (the endpoint is never contacted until a turn).
fn local_test_spawn(cfg: &crate::pair::PairConfig) -> anyhow::Result<crate::pair_host::PairHost> {
crate::pair_host::PairHost::spawn(crate::pair::PairConfig {
socket: cfg.socket.clone(),
workspace: cfg.workspace.clone(),
name: cfg.name.clone(),
model: Some(String::from("test-model")),
task: None,
provider: crate::pair::Provider::Local {
base_url: String::from("http://127.0.0.1:9"),
},
})
}
/// A window whose spawn FAILED must not keep the workspace's single-host
/// lock: it cannot host, so holding the flock only blocks the window that
/// can. The failed spawner un-appoints itself and releases; the next window
/// acquires and seats.
#[test]
fn a_failed_spawner_releases_the_lock_so_another_window_can_host() {
use std::time::{Duration, Instant};
let tmp = tempfile::tempdir().unwrap();
let socket = tmp.path().join("collab.sock");
let lock_path = tmp.path().join("host.lock");
{
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 record = crate::session::PairRecord {
model: None,
name: "nav".into(),
enabled: true,
task: None,
provider: None,
base_url: None,
};
let mut a = App::new(tmp.path().to_path_buf()).unwrap();
a.pair_record_path = tmp.path().join("a.pair.json");
a.pair_socket = socket.clone();
a.pair_host_lock_path = lock_path.clone();
a.pair_spawn_override = Some(Box::new(|_| anyhow::bail!("claude is broken")));
crate::session::write_pair_record(&a.pair_record_path, &record).unwrap();
a.last_pair_check = None;
a.maybe_seat_navigator();
assert!(a.pair_host.is_none());
assert!(a.navigator_down, "the failure latches, no 1s retry storm");
assert!(
a.pair_host_lock.is_none(),
"a window that cannot host must release the lock"
);
assert!(
a.collab_config.is_none(),
"the same-tick self-appointment is undone with it"
);
let mut b = App::new(tmp.path().to_path_buf()).unwrap();
b.pair_record_path = tmp.path().join("b.pair.json");
b.pair_socket = socket.clone();
b.pair_host_lock_path = lock_path.clone();
b.pair_spawn_override = Some(Box::new(local_test_spawn));
crate::session::write_pair_record(&b.pair_record_path, &record).unwrap();
b.last_pair_check = None;
b.maybe_seat_navigator();
assert!(
b.pair_host.is_some(),
"the working window must be able to host: {}",
b.status
);
}
/// Unseating the navigator mid-turn must reset the turn's note counters:
/// they survived into the NEXT seat's first TurnDone, which then reported
/// a dead seat's notes (inflated count, wrong file).
#[test]
fn unseating_the_navigator_resets_the_turn_note_counters() {
use std::time::{Duration, Instant};
let tmp = tempfile::tempdir().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 record = crate::session::PairRecord {
model: None,
name: "nav".into(),
enabled: true,
task: None,
provider: None,
base_url: None,
};
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.pair_record_path = tmp.path().join("x.pair.json");
app.pair_socket = socket.clone();
app.pair_host_lock_path = tmp.path().join("x.host.lock");
app.pair_spawn_override = Some(Box::new(local_test_spawn));
crate::session::write_pair_record(&app.pair_record_path, &record).unwrap();
app.last_pair_check = None;
app.maybe_seat_navigator();
assert!(app.pair_host.is_some(), "seated: {}", app.status);
// Mid-turn state: the navigator commented three times in a.rs.
app.pair_notes_this_turn = 3;
app.pair_last_noted_file = Some(String::from("a.rs"));
app.pair_noted_files.insert(String::from("a.rs"));
record.enabled = false;
crate::session::write_pair_record(&app.pair_record_path, &record).unwrap();
app.last_pair_check = None;
app.maybe_seat_navigator();
assert!(app.pair_host.is_none(), "unseated");
assert_eq!(
app.pair_notes_this_turn, 0,
"a dead seat's note count must not leak into the next seat's TurnDone"
);
assert!(
app.pair_last_noted_file.is_none(),
"a dead seat's noted file must not leak either"
);
assert!(app.pair_noted_files.is_empty());
}
/// The TurnDone hint names a file only when every note landed in the SAME
/// file: "3 comments in b.rs" was a lie when two of them sat in a.rs.
#[test]
fn turn_note_summary_only_names_a_single_file() {
use std::collections::BTreeSet;
let one: BTreeSet<String> = [String::from("a.rs")].into();
assert_eq!(super::turn_note_summary(1, &one), "1 comment in a.rs");
assert_eq!(super::turn_note_summary(3, &one), "3 comments in a.rs");
let two: BTreeSet<String> = [String::from("a.rs"), String::from("b.rs")].into();
assert_eq!(
super::turn_note_summary(3, &two),
"3 comments across 2 files"
);
assert_eq!(super::turn_note_summary(2, &BTreeSet::new()), "2 comments");
}
/// Relay startup failure is the spawn failure's sibling: the window has
/// already acquired the workspace host lock, cannot host without a relay,
/// and must release the lock on the way out so another window can try.
/// Holding it made every other window report "hosted by another croft
/// window" while nobody hosted anything.
#[test]
fn a_relay_failure_releases_the_host_lock() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.pair_record_path = tmp.path().join("x.pair.json");
// A socket inside a directory that does not exist: the relay can never
// bind it, so ensure_relay fails after its aliveness poll.
app.pair_socket = tmp.path().join("missing-dir").join("collab.sock");
app.pair_host_lock_path = tmp.path().join("x.host.lock");
app.pair_spawn_override = Some(Box::new(|_| panic!("must not reach the spawn")));
crate::session::write_pair_record(
&app.pair_record_path,
&crate::session::PairRecord {
model: None,
name: "nav".into(),
enabled: true,
task: None,
provider: None,
base_url: None,
},
)
.unwrap();
app.last_pair_check = None;
app.maybe_seat_navigator();
assert!(app.pair_host.is_none());
assert!(
app.status.contains("relay failed"),
"the failure is announced: {}",
app.status
);
assert!(
app.pair_host_lock.is_none(),
"a window without a relay cannot host; the lock must be released"
);
}
/// Re-running `croft pair` after a failed seat must retry: the CLI promises
/// "a running croft seats it within a second", but an enabled→enabled
/// rewrite has no transition for the death latch to observe. The record's
/// mtime is the signal.
#[test]
fn a_record_rewrite_re_arms_a_downed_navigator() {
use std::time::{Duration, Instant};
let tmp = tempfile::tempdir().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 record = crate::session::PairRecord {
model: None,
name: "nav".into(),
enabled: true,
task: None,
provider: None,
base_url: None,
};
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.pair_record_path = tmp.path().join("x.pair.json");
app.pair_socket = socket.clone();
app.pair_host_lock_path = tmp.path().join("x.host.lock");
app.pair_spawn_override = Some(Box::new(|_| anyhow::bail!("claude is broken")));
crate::session::write_pair_record(&app.pair_record_path, &record).unwrap();
app.last_pair_check = None;
app.maybe_seat_navigator();
assert!(app.navigator_down, "the first seat fails and latches");
// Latched: an unchanged record must NOT retry every second.
app.last_pair_check = None;
app.maybe_seat_navigator();
assert!(app.pair_host.is_none());
// The user fixes the backend and re-runs `croft pair`: the rewritten
// record re-arms seating — even when the rewrite lands within the same
// mtime grain (coarse-timestamp filesystems): pin the mtime to the old
// value so only the CONTENT can carry the signal (every write stamps
// the record, so an enabled→enabled rewrite is never byte-identical).
let old_mtime = std::fs::metadata(&app.pair_record_path)
.unwrap()
.modified()
.unwrap();
crate::session::write_pair_record(&app.pair_record_path, &record).unwrap();
let f = std::fs::File::options()
.write(true)
.open(&app.pair_record_path)
.unwrap();
f.set_modified(old_mtime).unwrap();
app.pair_spawn_override = Some(Box::new(local_test_spawn));
// Poll like the app's once-a-second tick: a child forked by a parallel
// test can share the host lock's file until its exec closes it, which
// reads as Busy for that one tick.
let deadline = Instant::now() + Duration::from_secs(5);
loop {
app.last_pair_check = None;
app.maybe_seat_navigator();
if app.pair_host.is_some() || Instant::now() >= deadline {
break;
}
std::thread::sleep(Duration::from_millis(20));
}
assert!(
app.pair_host.is_some(),
"a rewritten record must re-arm the downed navigator: {}",
app.status
);
}
/// A solo guest viewport never hosts the navigator: the owner's croft does,
/// or two hosts would fight over one seat.
#[test]
fn solo_guest_never_hosts_the_navigator() {
let tmp = tempfile::tempdir().unwrap();
let socket = tmp.path().join("collab.sock");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.pair_record_path = tmp.path().join("x.pair.json");
app.pair_socket = socket.clone();
app.pair_host_lock_path = tmp.path().join("x.pair-host.lock");
app.collab_config = Some((socket, crate::collab::CollabRole::Guest));
app.pair_spawn_override = Some(Box::new(|_| {
panic!("a solo guest must never spawn the pilot");
}));
crate::session::write_pair_record(
&app.pair_record_path,
&crate::session::PairRecord {
model: None,
name: "navigator".into(),
enabled: true,
task: None,
provider: None,
base_url: None,
},
)
.unwrap();
app.last_pair_check = None;
app.maybe_seat_navigator();
assert!(app.pair_host.is_none());
}
/// The four navigator palette commands exist, hint their chords, and their
/// hostless paths hint instead of panicking; Toggle records activation for
/// the tick loop to seat.
#[test]
fn palette_carries_the_navigator_commands() {
use crate::widgets::command_palette::{ALL_COMMANDS, Command};
for cmd in [
Command::AskNavigator,
Command::YieldToNavigator,
Command::ToggleNavigator,
Command::ClearNavigatorNotes,
] {
assert!(ALL_COMMANDS.contains(&cmd), "{cmd:?} missing from palette");
}
assert_eq!(Command::AskNavigator.keybinding_hint(), "Cmd+K Q");
assert_eq!(Command::YieldToNavigator.keybinding_hint(), "Cmd+K Y");
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("f.txt");
std::fs::write(&file, "a\nb").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.pair_record_path = tmp.path().join("x.pair.json");
app.open_file_at_launch(&file);
app.run_command(crate::widgets::command_palette::Command::AskNavigator);
assert!(app.status.to_lowercase().contains("not active"));
app.run_command(crate::widgets::command_palette::Command::YieldToNavigator);
assert!(app.status.to_lowercase().contains("not active"));
app.navigator_notes
.insert("f.txt".into(), vec![(1, 0, "n".into())]);
app.editor.comment_focus = Some(crate::widgets::editor::CommentFocus {
id: 1,
reply: String::new(),
cursor: 0,
});
app.run_command(crate::widgets::command_palette::Command::ClearNavigatorNotes);
assert!(app.navigator_notes.is_empty());
assert!(app.editor.comment_focus.is_none());
app.run_command(crate::widgets::command_palette::Command::ToggleNavigator);
let record =
crate::session::read_pair_record(&app.pair_record_path).expect("toggle writes the record");
assert!(record.enabled);
app.run_command(crate::widgets::command_palette::Command::ToggleNavigator);
let record = crate::session::read_pair_record(&app.pair_record_path).unwrap();
assert!(!record.enabled);
}
/// Cmd+K Y yields the active file to the navigator (a COMMENT-ONLY turn
/// carrying the numbered buffer). Commentary normally lands as a comment
/// box; here no owner serves the file (the host was seated by hand, no
/// self-appointment), so the words fall back to the Navigator OUTPUT
/// channel rather than being lost.
#[test]
fn cmd_k_y_yields_the_active_file_and_commentary_reaches_output() {
use std::time::{Duration, Instant};
if !crate::lsp::manager::is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("f.txt");
std::fs::write(&file, "a\nb\nc").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 script = tmp.path().join("fake_claude.py");
std::fs::write(&script, crate::pair::FAKE_CLAUDE).unwrap();
let log = tmp.path().join("stdin.log");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_file_at_launch(&file);
// Without a host the chord hints instead of panicking.
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('y'), KeyModifiers::NONE)));
assert!(
app.status.to_lowercase().contains("not active"),
"got: {}",
app.status
);
let mut cmd = std::process::Command::new("python3");
cmd.arg(&script).arg(&log).arg("notes");
app.pair_host =
Some(crate::pair_host::PairHost::spawn_cmd(&socket, "navigator", None, cmd).unwrap());
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('y'), KeyModifiers::NONE)));
assert!(
app.status.to_lowercase().contains("yielded"),
"got: {}",
app.status
);
let deadline = Instant::now() + Duration::from_secs(10);
loop {
let sent = std::fs::read_to_string(&log).unwrap_or_default();
if sent.contains("COMMENT-ONLY") && sent.contains("0|a") {
break;
}
assert!(
Instant::now() < deadline,
"yield turn never reached claude; log: {sent}"
);
std::thread::sleep(Duration::from_millis(10));
}
// The fake's "Reviewing." commentary flows to the Navigator channel.
// OUTPUT is process-global, so only lines past this test's own baseline
// count: a sibling test's residue on the same channel must not be able
// to satisfy the wait.
let baseline = crate::output::snapshot("Navigator")
.unwrap_or_default()
.len();
let deadline = Instant::now() + Duration::from_secs(10);
loop {
app.poll_pair();
let lines = crate::output::snapshot("Navigator").unwrap_or_default();
if lines
.iter()
.skip(baseline)
.any(|l| l.text.contains("Reviewing."))
{
break;
}
assert!(
Instant::now() < deadline,
"commentary never reached OUTPUT; got {lines:?}"
);
std::thread::sleep(Duration::from_millis(10));
}
}
/// A clean turn that left comments must SAY so: the TurnDone status names
/// the comment count and the F4 review key. The fake's turn leaves TWO
/// boxes: its NOTE fence, plus its prose commentary ("Reviewing."), which
/// lands as a comment box at the turn's origin — never in OUTPUT (boxes are
/// the navigator's single voice).
#[test]
fn turn_done_status_keeps_the_notes_visible() {
use std::time::{Duration, Instant};
if !crate::lsp::manager::is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("demo.txt");
std::fs::write(&file, "a\nb\nc").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 script = tmp.path().join("fake_claude.py");
std::fs::write(&script, crate::pair::FAKE_CLAUDE).unwrap();
let log = tmp.path().join("stdin.log");
// Full seating (record + owner self-appointment): the app-side owner
// answers the pilot's SnapshotRequest so the NOTE can anchor.
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_file_at_launch(&file);
app.pair_record_path = tmp.path().join("x.pair.json");
app.pair_socket = socket.clone();
app.pair_host_lock_path = tmp.path().join("x.pair-host.lock");
let (script2, log2, socket2) = (script.clone(), log.clone(), socket.clone());
app.pair_spawn_override = Some(Box::new(move |cfg| {
let mut cmd = std::process::Command::new("python3");
cmd.arg(&script2).arg(&log2).arg("notes");
crate::pair_host::PairHost::spawn_cmd(&socket2, &cfg.name, cfg.task.as_deref(), cmd)
}));
crate::session::write_pair_record(
&app.pair_record_path,
&crate::session::PairRecord {
model: None,
name: "nav".into(),
enabled: true,
task: None,
provider: None,
base_url: None,
},
)
.unwrap();
app.last_pair_check = None;
assert!(app.maybe_seat_navigator());
let deadline = Instant::now() + Duration::from_secs(5);
while app.collab.is_none() {
assert!(Instant::now() < deadline, "owner seat never connected");
app.poll_collab();
std::thread::sleep(Duration::from_millis(5));
}
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('y'), KeyModifiers::NONE)));
let deadline = Instant::now() + Duration::from_secs(10);
loop {
app.poll_collab();
app.poll_pair();
if app.status.contains("finished") {
break;
}
assert!(
Instant::now() < deadline,
"turn never finished; status: {}",
app.status
);
std::thread::sleep(Duration::from_millis(10));
}
assert!(
app.status.contains("2 comments") && app.status.contains("F4"),
"TurnDone status must surface the comments, got: {}",
app.status
);
// The prose landed as an anchored box (poll_pair's match makes box vs
// OUTPUT mutually exclusive; the fallback path has its own test, and
// the OUTPUT channel is process-global so it cannot be asserted empty
// under the parallel suite).
let host = app.pair_host.as_ref().expect("still seated");
let snap = host.notes_snapshot("demo.txt");
assert!(
snap.iter().any(|(_, _, body)| body.contains("Reviewing.")),
"commentary must land as a comment box; snapshot: {snap:?}"
);
}
/// The ask box: Cmd+K Q opens the navigator input scoped to the caret line
/// (or the selection), right-click menus carry the entries, and submitting
/// sends the composed ask turn (instruction, 0-based range, numbered
/// buffer) to the pilot's claude stdin.
#[test]
fn ask_box_opens_from_chord_and_menus_and_sends_the_ask_turn() {
use crate::widgets::input_prompt::InputPurpose;
use crossterm::event::{MouseButton, MouseEventKind};
use std::time::{Duration, Instant};
if !crate::lsp::manager::is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("f.txt");
std::fs::write(&file, "a\nb\nc\nd\ne").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 script = tmp.path().join("fake_claude.py");
std::fs::write(&script, crate::pair::FAKE_CLAUDE).unwrap();
let log = tmp.path().join("stdin.log");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_file_at_launch(&file);
let mut cmd = std::process::Command::new("python3");
cmd.arg(&script).arg(&log).arg("notes");
app.pair_host =
Some(crate::pair_host::PairHost::spawn_cmd(&socket, "navigator", None, cmd).unwrap());
// Cmd+K Q on the caret line (no selection): single-line scope, 1-based
// title, Esc closes through the shared input-prompt path.
app.editor.cursor_row = 2;
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('q'), KeyModifiers::NONE)));
{
let p = app.input_prompt.as_ref().expect("ask box opens");
assert!(
matches!(&p.purpose, InputPurpose::AskNavigator { range: (2, 2), .. }),
"caret-line scope"
);
assert!(p.title.contains("line 3"), "title: {}", p.title);
}
app.handle_input_prompt_key(key(KeyCode::Esc, KeyModifiers::NONE));
assert!(app.input_prompt.is_none());
// With a selection the chord scopes to the selected lines; submitting
// sends the composed turn to the pilot.
app.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: (1, 0),
head: (3, 1),
});
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('q'), KeyModifiers::NONE)));
assert!(matches!(
&app.input_prompt.as_ref().unwrap().purpose,
InputPurpose::AskNavigator { range: (1, 3), .. }
));
for c in "tighten this".chars() {
app.handle_input_prompt_key(key(KeyCode::Char(c), KeyModifiers::NONE));
}
app.handle_input_prompt_key(key(KeyCode::Enter, KeyModifiers::NONE));
assert!(app.input_prompt.is_none(), "submit closes the box");
let deadline = Instant::now() + Duration::from_secs(10);
loop {
let sent = std::fs::read_to_string(&log).unwrap_or_default();
if sent.contains("tighten this") && sent.contains("lines 1-3") && sent.contains("2|c") {
break;
}
assert!(
Instant::now() < deadline,
"composed ask never reached claude; log: {sent}"
);
std::thread::sleep(Duration::from_millis(10));
}
// The gutter right-click menu offers the ask entry; the body menu adds
// the selection-scoped one while a selection is active.
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let gutter_col = app.editor.last_inner.x;
let row = app.editor.last_inner.y + 1;
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Right),
gutter_col,
row,
));
let labels = menu_labels(&app.context_menu.as_ref().unwrap().items);
assert!(labels.contains(&"Ask Navigator"), "gutter menu: {labels:?}");
app.context_menu = None;
app.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: (0, 0),
head: (2, 1),
});
let text_x = app.editor.last_inner.x + app.editor.last_gutter_width + 2;
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Right), text_x, row));
let labels = menu_labels(&app.context_menu.as_ref().unwrap().items);
assert!(
labels.contains(&"Ask Navigator About Selection"),
"body menu: {labels:?}"
);
}
/// The navigator note popup: opens when the caret LANDS on a noted line
/// (staying put never re-triggers), Esc dismisses it without eating the
/// selection, F4 cycles through the file's notes (wrapping) and jumps the
/// caret, and moving off a noted line closes it.
#[test]
fn f4_focuses_comment_boxes_typing_edits_the_draft_and_esc_releases() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("f.txt");
std::fs::write(&file, "a\nb\nc\nd\ne").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_file_at_launch(&file);
app.navigator_notes.insert(
"f.txt".into(),
vec![(1, 1, "first note".into()), (2, 3, "second note".into())],
);
// F4 focuses the next box from the caret (id 1 on row 1) and jumps to
// its anchor; a second F4 hops to the next box; a third wraps.
app.handle_key(key(KeyCode::F(4), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.cursor_row, 1);
assert_eq!(app.editor.comment_focus.as_ref().map(|f| f.id), Some(1));
app.handle_key(key(KeyCode::F(4), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.cursor_row, 3);
assert_eq!(app.editor.comment_focus.as_ref().map(|f| f.id), Some(2));
app.handle_key(key(KeyCode::F(4), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.comment_focus.as_ref().map(|f| f.id), Some(1));
// Typing edits the reply draft, never the buffer.
let before = app.editor.lines.clone();
for c in ['w', 'h', 'y'] {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
assert_eq!(
app.editor.comment_focus.as_ref().map(|f| f.reply.as_str()),
Some("why")
);
assert_eq!(app.editor.lines, before, "the buffer is untouched");
app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.comment_focus.as_ref().map(|f| f.reply.as_str()),
Some("wh")
);
// Esc releases the keyboard back to the buffer.
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(app.editor.comment_focus.is_none());
// Shift+F4 ignores the nearest box: it leaves the snapshot immediately.
app.editor.cursor_row = 0;
app.handle_key(key(KeyCode::F(4), KeyModifiers::SHIFT))
.unwrap();
assert_eq!(
app.navigator_notes.get("f.txt").map(|n| n.len()),
Some(1),
"the ignored box is gone from the snapshot"
);
}
/// Re-rooting the workspace (Cmd+Z jump / Make Root) rebinds the resident
/// navigator: the activation record, relay socket, and single-host lock all
/// key off the root, so a `croft pair` run in the NEW root must be seen by
/// this window. The old workspace's seat (and its comment boxes) unseats.
#[test]
fn reroot_rebinds_the_navigator_activation_watch() {
let a = tempfile::tempdir().unwrap();
let b = tempfile::tempdir().unwrap();
std::fs::write(a.path().join("a.txt"), "a").unwrap();
std::fs::write(b.path().join("b.txt"), "b").unwrap();
let mut app = App::new(a.path().to_path_buf()).unwrap();
assert_eq!(
app.pair_record_path,
crate::session::pair_record_path(a.path())
);
// A seat and its boxes from root A are torn down by the move.
app.navigator_notes
.insert("a.txt".into(), vec![(1, 0, "n".into())]);
app.editor.comment_focus = Some(crate::widgets::editor::CommentFocus {
id: 1,
reply: String::new(),
cursor: 0,
});
app.navigator_down = true; // a dead pilot in A must not block B
app.last_pair_check = Some(std::time::Instant::now());
app.change_workspace_root(b.path().to_path_buf());
assert_eq!(
app.pair_record_path,
crate::session::pair_record_path(b.path()),
"the activation watch follows the root"
);
assert_eq!(
app.pair_socket,
crate::session::collab_socket_path(b.path())
);
assert_eq!(
app.pair_host_lock_path,
crate::session::pair_host_lock_path(b.path())
);
assert!(app.navigator_notes.is_empty(), "old root's boxes are gone");
assert!(app.editor.comment_focus.is_none());
assert!(
!app.navigator_down,
"the death latch belongs to the old root"
);
assert!(
app.last_pair_check.is_none(),
"the new record is checked on the next tick, not in 1s"
);
}
/// The proactive trigger: after the navigator's first look at a file, a
/// newly COMPLETED construct plus a typing pause makes it take a
/// comment-only look on its own. A pause alone never fires, the pref kills
/// the behavior, and one buffer state never fires twice.
#[test]
fn a_completed_construct_plus_pause_triggers_a_proactive_look() {
use std::time::{Duration, Instant};
if !crate::lsp::manager::is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("f.rs");
std::fs::write(&file, "fn alpha() {}\n").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 script = tmp.path().join("fake_claude.py");
std::fs::write(&script, crate::pair::FAKE_CLAUDE).unwrap();
let log = tmp.path().join("stdin.log");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_file_at_launch(&file);
// Own the workspace's collab session so the pilot's bootstraps answer.
app.collab_config = Some((socket.clone(), crate::collab::CollabRole::Owner));
app.last_collab_connect = None;
let deadline = Instant::now() + Duration::from_secs(5);
while app.collab.is_none() {
assert!(Instant::now() < deadline, "owner seat never connected");
app.poll_collab();
std::thread::sleep(Duration::from_millis(5));
}
let mut cmd = std::process::Command::new("python3");
cmd.arg(&script).arg(&log).arg("notes");
app.pair_host = Some(crate::pair_host::PairHost::spawn_cmd(&socket, "nav", None, cmd).unwrap());
// The navigator's first look: a manual yield; wait the turn out.
app.yield_to_navigator();
let deadline = Instant::now() + Duration::from_secs(15);
while app.pair_host.as_ref().unwrap().is_busy() {
assert!(Instant::now() < deadline, "the first look never finished");
app.poll_collab();
app.poll_pair();
std::thread::sleep(Duration::from_millis(10));
}
// A pause with no new construct never fires.
app.editor.last_edit_at = Some(Instant::now() - Duration::from_secs(3));
app.editor.edit_seq += 1;
assert!(!app.tick_proactive_navigator(), "no new construct: no look");
// Complete a new function, pause — but the pref is off: no fire.
let beta_row = app.editor.lines.len(); // where the new fn will sit
app.editor.lines.push("fn beta() {}".into());
app.editor.edit_seq += 1;
app.editor.last_edit_at = Some(Instant::now() - Duration::from_secs(3));
app.proactive_navigator_enabled = false;
assert!(
!app.tick_proactive_navigator(),
"the pref must gate the look"
);
// Pref back on but the user is mid-typing in a prompt (the ask box):
// stealing the seat now would make their Enter fail against a busy
// host and lose the typed draft. An open prompt suppresses the look
// without consuming the scan.
app.proactive_navigator_enabled = true;
app.open_ask_navigator((0, 0), String::new());
assert!(app.input_prompt.is_some(), "the ask box must open");
assert!(
!app.tick_proactive_navigator(),
"an open prompt must suppress the proactive look"
);
app.close_input_prompt();
// Prompt closed: the completed construct fires a comment-only look
// anchored at the new function's row.
assert!(app.tick_proactive_navigator(), "new fn + pause must fire");
assert_eq!(
app.pair_turn_origin,
Some((String::from("f.rs"), beta_row)),
"the look anchors at the completed construct"
);
assert!(
app.pair_host.as_ref().unwrap().is_busy(),
"the proactive look is a real turn"
);
// The same buffer state never fires twice (latch + busy host).
assert!(!app.tick_proactive_navigator());
}
/// A failed ask submit must not eat the typed draft: the navigator can go
/// away (or busy) between opening the box and Enter, and the instruction
/// the user typed is unrecoverable once the prompt closes. The failure
/// keeps the box open for a retry, like a failed comment reply keeps its
/// draft.
#[test]
fn a_failed_ask_submit_keeps_the_typed_draft() {
use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.input_prompt = Some(
InputPrompt::new(
InputPurpose::AskNavigator {
file: String::from("f.rs"),
range: (0, 0),
selection: String::new(),
},
"Ask nav",
"",
)
.with_value("check the loop bounds"),
);
app.submit_input_prompt();
let p = app
.input_prompt
.as_ref()
.expect("the failed submit must keep the prompt open");
assert_eq!(p.value, "check the loop bounds", "the draft survives");
assert!(
app.status.to_lowercase().contains("not active"),
"the failure is announced: {}",
app.status
);
}
/// Enter in a focused comment box sends the reply turn: the composed
/// message (note context, the reply, COMMENT-ONLY, numbered buffer) reaches
/// the pilot's claude stdin, and the focus releases.
#[test]
fn enter_in_a_focused_comment_box_sends_the_reply_turn() {
use std::time::{Duration, Instant};
if !crate::lsp::manager::is_on_path("python3") {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("f.txt");
std::fs::write(&file, "a\nb\nc").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 script = tmp.path().join("fake_claude.py");
std::fs::write(&script, crate::pair::FAKE_CLAUDE).unwrap();
let log = tmp.path().join("stdin.log");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_file_at_launch(&file);
let mut cmd = std::process::Command::new("python3");
cmd.arg(&script).arg(&log).arg("notes");
app.pair_host = Some(crate::pair_host::PairHost::spawn_cmd(&socket, "nav", None, cmd).unwrap());
app.navigator_notes
.insert("f.txt".into(), vec![(1, 1, "seed note".into())]);
app.editor.comment_focus = Some(crate::widgets::editor::CommentFocus {
id: 1,
reply: String::from("is this hot?"),
cursor: 12,
});
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(
app.editor.comment_focus.is_none(),
"a sent reply releases the focus; status: {}",
app.status
);
let deadline = Instant::now() + Duration::from_secs(10);
loop {
let sent = std::fs::read_to_string(&log).unwrap_or_default();
if sent.contains("replied to your note on f.txt at line 1")
&& sent.contains("seed note")
&& sent.contains("is this hot?")
&& sent.contains("COMMENT-ONLY")
{
break;
}
assert!(
Instant::now() < deadline,
"reply turn never reached claude; log: {sent}"
);
std::thread::sleep(Duration::from_millis(10));
}
}
/// The AI-stream badge lifecycle: a pilot's StreamState(active) sets
/// `collab_stream` on a dirty tick, the cancel action broadcasts
/// StreamCancel to the pilot, and StreamState(inactive) clears the badge.
/// With no active stream, cancel is a hint, not a broadcast.
#[test]
fn collab_stream_state_drives_the_badge_and_cancel_broadcasts() {
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));
owner.open_file_at_launch(&file);
// Cancel with no stream: a hint, nothing on the wire required yet.
owner.collab_cancel_stream();
assert!(
owner.status.to_lowercase().contains("no ai stream"),
"inactive cancel hints, got: {}",
owner.status
);
// The relay is a dumb fan-out with no replay, so the owner must be
// connected BEFORE the pilot broadcasts or the message is simply lost
// (poll_collab's lazy connect is throttled and can lose that race
// under a contended parallel suite).
let deadline = Instant::now() + Duration::from_secs(5);
while owner.collab.is_none() {
assert!(Instant::now() < deadline, "owner never joined the relay");
owner.poll_collab();
std::thread::sleep(Duration::from_millis(5));
}
// A pilot stand-in seat on the same relay.
let mut pilot = {
let deadline = Instant::now() + Duration::from_secs(5);
loop {
if let Some(ch) =
crate::collab::CollabChannel::connect(&socket, crate::collab::CollabRole::Guest)
{
break crate::collab::CollabSession::new(ch, "pilot".into());
}
assert!(Instant::now() < deadline, "pilot never connected");
std::thread::sleep(Duration::from_millis(10));
}
};
// Stream starts: the owner's badge state fills on a dirty tick.
pilot.send_stream_state("f.txt", true);
let deadline = Instant::now() + Duration::from_secs(5);
let mut dirty_on_arrival = false;
while owner.collab_stream.is_none() {
assert!(Instant::now() < deadline, "badge never appeared");
dirty_on_arrival = owner.poll_collab();
std::thread::sleep(Duration::from_millis(5));
}
assert!(dirty_on_arrival, "the badge tick must request a redraw");
let stream = owner.collab_stream.as_ref().unwrap();
assert_eq!(
(stream.name.as_str(), stream.file.as_str()),
("pilot", "f.txt")
);
// The owner cancels: the pilot's seat receives StreamCancel.
owner.collab_cancel_stream();
let deadline = Instant::now() + Duration::from_secs(5);
loop {
let events = pilot.poll(|_| None);
if events
.iter()
.any(|e| matches!(e, crate::collab::CollabEvent::StreamCancel))
{
break;
}
assert!(Instant::now() < deadline, "pilot never saw the cancel");
std::thread::sleep(Duration::from_millis(5));
}
// Stream ends: the badge clears.
pilot.send_stream_state("f.txt", false);
let deadline = Instant::now() + Duration::from_secs(5);
while owner.collab_stream.is_some() {
assert!(Instant::now() < deadline, "badge never cleared");
owner.poll_collab();
std::thread::sleep(Duration::from_millis(5));
}
}
/// A caret name tag is visible while inside its 2s fade window and signals
/// exactly one redraw when it appears and one when it expires — no redraw
/// churn in between (the tick loop repaints only on `poll_collab() == true`).
#[test]
fn collab_caret_label_fade_signals_one_redraw_per_transition() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(
!app.collab_labels_dirty(),
"no carets, no labels, no redraw"
);
app.collab_carets.insert(
2,
CollabCaret {
file: "f.txt".into(),
row: 0,
col: 3,
name: "claude".into(),
last_moved: std::time::Instant::now(),
},
);
assert!(app.collab_labels_dirty(), "fresh tag: one redraw");
assert!(!app.collab_labels_dirty(), "still visible: quiet");
app.collab_carets.get_mut(&2).unwrap().last_moved =
std::time::Instant::now() - std::time::Duration::from_secs(3);
assert!(app.collab_labels_dirty(), "expired tag: one redraw");
assert!(!app.collab_labels_dirty(), "stays hidden: quiet");
}
/// A right-click menu opened over an image tab was painted *under* the
/// picture: on Kitty the editor preview was placed at the default z=0, which
/// the spec puts above text. Placing it below text AND below non-default
/// background cells (the same trick the sidebar illustrations use) lets any
/// opaque popup box paint fully on top, while the preview still shows through
/// the pane's default-bg canvas.
#[test]
fn editor_image_preview_sits_below_text_so_popups_paint_over_it() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("shot.png");
let mut png = Vec::new();
image::RgbaImage::from_pixel(4, 4, image::Rgba([10, 200, 30, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.expect("encode test png");
std::fs::write(&path, &png).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
app.cell_pixel = Some((8, 16));
app.editor.open(&path).unwrap();
app.update_editor_image_overlay(
0,
ratatui::layout::Rect {
x: 0,
y: 0,
width: 60,
height: 30,
},
);
let (osc, _) = app.editor_image_payload(0).expect("preview must bake");
assert!(
osc.contains(&format!(
"z={}",
crate::iterm2_inline::KITTY_Z_BELOW_TEXT_AND_BG
)),
"the preview must be placed below text so menus draw on top: {:?}",
&osc[..osc.len().min(120)]
);
}
// --- Preview navigation (PDF pages, spreadsheet rows, Markdown, text) -----
//
// Every tab type must stay navigable right after it is opened, from the
// keyboard and from the wheel. Opening a file from the Explorer used to leave
// focus on the tree, so arrows walked the file list and a PDF looked frozen on
// page 1; the wheel over a PDF or a spreadsheet did nothing at all.
/// A three-page PDF written inline, so the tests need no fixture file.
/// Poppler repairs the missing xref table, so exact offsets are unnecessary.
fn write_three_page_pdf(path: &std::path::Path) {
let pdf = concat!(
"%PDF-1.4\n",
"1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n",
"2 0 obj<</Type/Pages/Kids[3 0 R 4 0 R 5 0 R]/Count 3>>endobj\n",
"3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 6 0 R>>endobj\n",
"4 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 7 0 R>>endobj\n",
"5 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 8 0 R>>endobj\n",
"6 0 obj<</Length 27>>stream\n0 0 1 rg 10 10 100 100 re f\nendstream endobj\n",
"7 0 obj<</Length 27>>stream\n1 0 0 rg 10 10 100 100 re f\nendstream endobj\n",
"8 0 obj<</Length 27>>stream\n0 1 0 rg 10 10 100 100 re f\nendstream endobj\n",
"trailer<</Root 1 0 R/Size 9>>\n%%EOF\n",
);
std::fs::write(path, pdf).unwrap();
}
fn write_test_png(path: &std::path::Path) {
let mut png = Vec::new();
image::RgbaImage::from_pixel(8, 8, image::Rgba([10, 200, 30, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.expect("encode test png");
std::fs::write(path, &png).unwrap();
}
fn csv_body(rows: usize) -> String {
let mut s = String::from("name,qty,price\n");
for i in 0..rows {
s.push_str(&format!("row{i},{i},{i}.50\n"));
}
s
}
fn current_pdf_page(app: &App) -> u32 {
app.editor
.image
.as_ref()
.and_then(|i| i.pdf.as_ref())
.expect("a PDF tab must carry page state")
.current_page
}
fn sheet_cursor(app: &App) -> (usize, usize) {
let sheet = app.editor.sheet.as_ref().expect("a spreadsheet tab");
let data = &sheet.sheets[sheet.current_sheet];
(data.cur_row, data.cur_col)
}
fn sheet_scroll(app: &App) -> (usize, usize) {
let sheet = app.editor.sheet.as_ref().expect("a spreadsheet tab");
let data = &sheet.sheets[sheet.current_sheet];
(data.scroll_row, data.scroll_col)
}
/// Open `name` the way a user does: select it in the Explorer and press Enter.
fn open_from_explorer(app: &mut App, name: &str) {
let idx = app
.tree
.nodes
.iter()
.position(|n| n.path.file_name().is_some_and(|f| f == name))
.unwrap_or_else(|| panic!("{name} must be visible in the Explorer"));
app.tree.selected = idx;
app.focus_pane(Pane::Tree);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
}
/// Give the editor pane a real rectangle so wheel events land inside it.
fn place_editor_pane(app: &mut App) -> (u16, u16) {
let area = Rect {
x: 20,
y: 2,
width: 60,
height: 30,
};
app.editor.last_area = area;
app.editor.last_full_area = area;
app.editor.last_inner = Rect {
x: area.x + 1,
y: area.y + 2,
width: area.width - 2,
height: area.height - 3,
};
(area.x + 10, area.y + 10)
}
fn wheel(app: &mut App, kind: crossterm::event::MouseEventKind, col: u16, row: u16) {
app.handle_mouse(mouse(kind, col, row));
}
fn require_pdf_backend() {
assert!(
crate::pdf::detect_backend().is_some(),
"these tests need a PDF rasteriser (poppler's pdftoppm, or sips on macOS)"
);
}
#[test]
fn arrow_keys_page_through_an_open_pdf() {
require_pdf_backend();
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("doc.pdf");
write_three_page_pdf(&path);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&path).unwrap();
app.focus_pane(Pane::Editor);
assert_eq!(current_pdf_page(&app), 1);
app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
.unwrap();
assert_eq!(current_pdf_page(&app), 2, "Right must go to the next page");
app.handle_key(key(KeyCode::Left, KeyModifiers::NONE))
.unwrap();
assert_eq!(current_pdf_page(&app), 1, "Left must go back a page");
app.handle_key(key(KeyCode::PageDown, KeyModifiers::NONE))
.unwrap();
assert_eq!(current_pdf_page(&app), 2, "PageDown pages forward");
app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
.unwrap();
assert_eq!(current_pdf_page(&app), 3, "End jumps to the last page");
app.handle_key(key(KeyCode::Home, KeyModifiers::NONE))
.unwrap();
assert_eq!(current_pdf_page(&app), 1, "Home jumps back to page 1");
}
#[test]
fn a_pdf_opened_from_the_explorer_pages_with_the_arrow_keys() {
require_pdf_backend();
let tmp = tempfile::tempdir().unwrap();
write_three_page_pdf(&tmp.path().join("doc.pdf"));
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
open_from_explorer(&mut app, "doc.pdf");
assert!(
matches!(app.focus, Pane::Editor),
"opening a file must hand the keyboard to the editor, or its navigation keys are dead"
);
app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
.unwrap();
assert_eq!(
current_pdf_page(&app),
2,
"a PDF opened from the Explorer must page with Right"
);
}
#[test]
fn the_wheel_pages_a_pdf_under_the_pointer() {
require_pdf_backend();
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("doc.pdf");
write_three_page_pdf(&path);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&path).unwrap();
let (col, row) = place_editor_pane(&mut app);
wheel(&mut app, MouseEventKind::ScrollDown, col, row);
assert_eq!(current_pdf_page(&app), 2, "wheel down pages forward");
wheel(&mut app, MouseEventKind::ScrollUp, col, row);
assert_eq!(current_pdf_page(&app), 1, "wheel up pages back");
}
/// A momentum flick delivers a burst of same-direction wheel events, and
/// every PDF page step is a synchronous rasteriser run on the UI thread: the
/// burst must coalesce (rate-limited per direction) instead of queueing
/// dozens of blocking renders. A reversal is deliberate and passes through
/// immediately (the paging test above depends on that).
#[test]
fn a_wheel_flick_over_a_pdf_coalesces_to_one_page_step() {
require_pdf_backend();
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("doc.pdf");
write_three_page_pdf(&path);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&path).unwrap();
let (col, row) = place_editor_pane(&mut app);
wheel(&mut app, MouseEventKind::ScrollDown, col, row);
wheel(&mut app, MouseEventKind::ScrollDown, col, row);
wheel(&mut app, MouseEventKind::ScrollDown, col, row);
assert_eq!(
current_pdf_page(&app),
2,
"a same-direction burst steps one page, not one per event"
);
}
/// The wheel never wraps the document: page 1 stays put on wheel up and the
/// last page stays put on wheel down. (The arrow keys wrap deliberately;
/// no PDF viewer wraps on scroll.)
#[test]
fn the_wheel_does_not_wrap_a_pdf_at_its_ends() {
require_pdf_backend();
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("doc.pdf");
write_three_page_pdf(&path);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&path).unwrap();
let (col, row) = place_editor_pane(&mut app);
wheel(&mut app, MouseEventKind::ScrollUp, col, row);
assert_eq!(
current_pdf_page(&app),
1,
"wheel up on page 1 must not wrap"
);
app.jump_pdf_page(3);
wheel(&mut app, MouseEventKind::ScrollDown, col, row);
assert_eq!(
current_pdf_page(&app),
3,
"wheel down on the last page must not wrap"
);
}
/// Opening a file while the terminal is maximized (Ctrl+Shift+J) must
/// restore the editor - the same convention VS Code follows when a file is
/// revealed over a maximized panel. Before this, focus silently moved into
/// an editor the layout gave zero rows: arrows did nothing visible and
/// typing dirtied a hidden buffer.
#[test]
fn opening_a_file_over_a_maximized_terminal_restores_the_editor() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.txt"), "hello").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminal_maximized = true;
open_from_explorer(&mut app, "a.txt");
assert!(matches!(app.focus, Pane::Editor));
assert!(
!app.terminal_maximized,
"focusing the editor must restore it from under a maximized terminal"
);
}
/// iTerm2 OSC-1337 and Sixel have no image z-layer: the post-frame image
/// blit overwrites whatever text sits in those cells, so an open context
/// menu overlapping the editor preview must suppress the overlay (Kitty
/// instead layers images below text and needs nothing).
#[test]
fn a_context_menu_over_the_editor_image_suppresses_the_blit_on_no_z_protocols() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let img = ratatui::layout::Rect::new(2, 2, 30, 15);
assert!(
!app.context_menu_covers_rect(img),
"no menu open: nothing to suppress"
);
app.context_menu = Some(ContextMenu::flat(
(4, 4),
vec![(
String::from("Rename"),
MenuAction::Rename(tmp.path().into()),
)],
tmp.path().into(),
));
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::ITerm2;
assert!(
app.context_menu_covers_rect(img),
"an overlapping menu must suppress the image on iTerm2"
);
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
assert!(
!app.context_menu_covers_rect(img),
"Kitty layers images below text; the menu already wins"
);
}
/// F6 must give the same guarantee as every other route into the editor:
/// it used to assign focus directly, bypassing `focus_pane`, so cycling
/// into the editor under a maximized terminal focused a zero-height pane.
#[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"
);
}
/// The wheel cooldown is per document: scrolling one PDF and immediately
/// wheeling in a second, freshly focused PDF is that document's FIRST
/// gesture, not a repeat - an app-global cooldown swallowed it.
#[test]
fn the_wheel_cooldown_does_not_leak_across_pdf_documents() {
require_pdf_backend();
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.pdf");
let b = tmp.path().join("b.pdf");
write_three_page_pdf(&a);
write_three_page_pdf(&b);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&a).unwrap();
let (col, row) = place_editor_pane(&mut app);
wheel(&mut app, MouseEventKind::ScrollDown, col, row);
assert_eq!(current_pdf_page(&app), 2);
app.editor.open(&b).unwrap();
let (col, row) = place_editor_pane(&mut app);
// Pin the cooldown stamp to "just now, same direction, other document"
// so the window is deterministically open regardless of how long the
// rasteriser took: only the document identity may let this tick through.
app.last_pdf_wheel = Some((std::time::Instant::now(), 1, Some(a.clone())));
wheel(&mut app, MouseEventKind::ScrollDown, col, row);
assert_eq!(
current_pdf_page(&app),
2,
"the second document's first wheel tick must not be dropped"
);
}
#[test]
fn a_spreadsheet_opened_from_the_explorer_scrolls_with_the_arrow_keys() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("data.csv"), csv_body(40)).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
open_from_explorer(&mut app, "data.csv");
assert!(app.editor.sheet.is_some(), "a .csv opens as a spreadsheet");
assert!(matches!(app.focus, Pane::Editor));
app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
.unwrap();
assert_eq!(
sheet_cursor(&app).0,
1,
"Down moves the cell cursor down a row (#177)"
);
app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
.unwrap();
assert_eq!(
sheet_cursor(&app).1,
1,
"Right moves the cell cursor a column"
);
}
#[test]
fn the_wheel_scrolls_a_spreadsheet_under_the_pointer() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("data.csv");
std::fs::write(&path, csv_body(40)).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&path).unwrap();
let (col, row) = place_editor_pane(&mut app);
wheel(&mut app, MouseEventKind::ScrollDown, col, row);
assert_eq!(sheet_scroll(&app).0, 3, "wheel down scrolls the sheet rows");
wheel(&mut app, MouseEventKind::ScrollUp, col, row);
assert_eq!(sheet_scroll(&app).0, 0, "wheel up scrolls back");
}
#[test]
fn a_tsv_preview_scrolls_the_same_way_as_a_csv() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("data.tsv");
std::fs::write(&path, "a\tb\n1\t2\n3\t4\n5\t6\n7\t8\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&path).unwrap();
let (col, row) = place_editor_pane(&mut app);
assert!(app.editor.sheet.is_some(), "a .tsv opens as a spreadsheet");
wheel(&mut app, MouseEventKind::ScrollDown, col, row);
assert_eq!(sheet_scroll(&app).0, 3, "wheel down scrolls a TSV too");
}
#[test]
fn a_markdown_file_opened_from_the_explorer_scrolls_its_preview() {
let tmp = tempfile::tempdir().unwrap();
let body: String = (0..200).map(|i| format!("line {i}\n")).collect();
std::fs::write(tmp.path().join("notes.md"), body).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
open_from_explorer(&mut app, "notes.md");
assert!(matches!(app.focus, Pane::Editor));
app.toggle_markdown_preview();
assert!(app.editor.markdown_preview.is_some());
app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
.unwrap();
let scrolled = app
.editor
.markdown_preview
.as_ref()
.map(|p| p.scroll)
.unwrap();
assert!(scrolled > 0, "Down must scroll the rendered Markdown");
}
#[test]
fn the_wheel_scrolls_a_markdown_preview_under_the_pointer() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("notes.md");
let body: String = (0..200).map(|i| format!("line {i}\n")).collect();
std::fs::write(&path, body).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&path).unwrap();
let (col, row) = place_editor_pane(&mut app);
app.toggle_markdown_preview();
wheel(&mut app, MouseEventKind::ScrollDown, col, row);
let scrolled = app
.editor
.markdown_preview
.as_ref()
.map(|p| p.scroll)
.unwrap();
assert!(scrolled > 0, "the wheel must scroll the rendered Markdown");
}
#[test]
fn a_text_file_opened_from_the_explorer_takes_the_arrow_keys() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("main.rs"), "one\ntwo\nthree\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
open_from_explorer(&mut app, "main.rs");
let before = app.tree.selected;
app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.cursor_row, 1, "Down moves the caret in the file");
assert_eq!(
app.tree.selected, before,
"the Explorer selection must not move once the file is open"
);
}
#[test]
fn the_wheel_still_scrolls_a_long_text_file() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("long.txt");
let body: String = (0..500).map(|i| format!("line {i}\n")).collect();
std::fs::write(&path, body).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&path).unwrap();
let (col, row) = place_editor_pane(&mut app);
wheel(&mut app, MouseEventKind::ScrollDown, col, row);
assert_eq!(app.editor.scroll, 3, "wheel down still scrolls text");
wheel(&mut app, MouseEventKind::ScrollUp, col, row);
assert_eq!(app.editor.scroll, 0, "wheel up still scrolls text back");
}
#[test]
fn an_image_preview_swallows_navigation_without_disturbing_the_buffer() {
let tmp = tempfile::tempdir().unwrap();
write_test_png(&tmp.path().join("shot.png"));
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
open_from_explorer(&mut app, "shot.png");
assert!(app.editor.image.is_some());
let (col, row) = place_editor_pane(&mut app);
for code in [
KeyCode::Right,
KeyCode::Left,
KeyCode::Up,
KeyCode::Down,
KeyCode::PageDown,
KeyCode::Home,
KeyCode::End,
KeyCode::Char('x'),
] {
app.handle_key(key(code, KeyModifiers::NONE)).unwrap();
}
wheel(&mut app, MouseEventKind::ScrollDown, col, row);
wheel(&mut app, MouseEventKind::ScrollUp, col, row);
assert_eq!(
app.editor.lines,
vec![String::new()],
"an image tab is read-only: no key may reach the buffer"
);
}
#[test]
fn right_arrow_in_the_explorer_previews_a_file_without_stealing_focus() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("peek.txt"), "hello\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let idx = app
.tree
.nodes
.iter()
.position(|n| n.path.file_name().is_some_and(|f| f == "peek.txt"))
.expect("peek.txt in the tree");
app.tree.selected = idx;
app.focus_pane(Pane::Tree);
app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines[0], "hello");
assert!(
matches!(app.focus, Pane::Tree),
"Right is an Explorer navigation gesture: it previews but keeps the keyboard in the tree"
);
}
/// The invariant behind every test above, applied to one file of each kind
/// croft previews: opening a file must leave the keyboard where that file's
/// navigation keys are handled. Add a new preview type, add a row here.
#[test]
fn opening_any_file_type_from_the_explorer_lands_the_keyboard_in_the_editor() {
require_pdf_backend();
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("plain.txt"), "alpha\nbeta\n").unwrap();
std::fs::write(tmp.path().join("code.rs"), "fn main() {}\n").unwrap();
std::fs::write(tmp.path().join("notes.md"), "# Title\n\nbody\n").unwrap();
std::fs::write(tmp.path().join("data.csv"), csv_body(5)).unwrap();
std::fs::write(tmp.path().join("data.tsv"), "a\tb\n1\t2\n").unwrap();
std::fs::write(tmp.path().join("conf.json"), "{\"a\": 1}\n").unwrap();
write_test_png(&tmp.path().join("shot.png"));
write_three_page_pdf(&tmp.path().join("doc.pdf"));
for name in [
"plain.txt",
"code.rs",
"notes.md",
"data.csv",
"data.tsv",
"conf.json",
"shot.png",
"doc.pdf",
] {
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
open_from_explorer(&mut app, name);
assert!(
matches!(app.focus, Pane::Editor),
"{name}: opening it must hand the keyboard to the editor, or its navigation keys are dead"
);
}
}
/// Root cause of the frozen preview: the overlay's re-emit key held the path
/// and the rect but not the page, so a page turn looked like "same layout" and
/// the picture on screen never changed. Baking twice across a page turn must
/// produce two different payloads.
#[test]
fn turning_a_pdf_page_rebakes_the_inline_image_overlay() {
require_pdf_backend();
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("doc.pdf");
write_three_page_pdf(&path);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
app.cell_pixel = Some((8, 16));
app.editor.open(&path).unwrap();
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
app.update_editor_image_overlay(0, area);
let page1 = app
.editor_image_payload(0)
.map(|(osc, _)| osc.to_string())
.expect("page 1 must bake");
assert!(app.editor.change_pdf_page(1));
app.update_editor_image_overlay(0, area);
let page2 = app
.editor_image_payload(0)
.map(|(osc, _)| osc.to_string())
.expect("page 2 must bake");
assert_ne!(
page1, page2,
"the overlay must re-bake on a page turn, or the reader stares at a frozen page"
);
}
/// Click a file's row in the Explorer, the way a user opens a file with the
/// mouse. Returns nothing: the assertions live in the callers.
fn click_open_in_explorer(app: &mut App, name: &str) {
app.tree.last_area = Rect {
x: 4,
y: 0,
width: 32,
height: 20,
};
app.tree.last_inner = Rect {
x: 5,
y: 1,
width: 30,
height: 18,
};
app.focus_pane(Pane::Tree);
let idx = app
.tree
.nodes
.iter()
.position(|n| n.path.file_name().is_some_and(|f| f == name))
.unwrap_or_else(|| panic!("{name} must be visible in the Explorer"));
let row = app.tree.last_inner.y + idx as u16;
let col = app.tree.last_inner.x + 2;
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row));
}
/// The gesture the bug report actually used: one click on the PDF in the
/// Explorer, then the arrow keys. A single click opened the file but left the
/// keyboard on the tree, so every page-turn key walked the file list instead.
#[test]
fn a_pdf_opened_with_one_click_in_the_explorer_pages_with_the_arrow_keys() {
require_pdf_backend();
let tmp = tempfile::tempdir().unwrap();
write_three_page_pdf(&tmp.path().join("doc.pdf"));
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
click_open_in_explorer(&mut app, "doc.pdf");
assert_eq!(current_pdf_page(&app), 1, "the click must open the PDF");
assert!(
matches!(app.focus, Pane::Editor),
"one click on a file must hand the keyboard to the editor, as VS Code does"
);
app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
.unwrap();
assert_eq!(current_pdf_page(&app), 2, "Right must turn the page");
app.handle_key(key(KeyCode::Char(' '), KeyModifiers::NONE))
.unwrap();
assert_eq!(current_pdf_page(&app), 3, "Space must turn the page");
}
#[test]
fn clicking_any_file_type_in_the_explorer_lands_the_keyboard_in_the_editor() {
require_pdf_backend();
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("plain.txt"), "alpha\nbeta\n").unwrap();
std::fs::write(tmp.path().join("data.csv"), csv_body(5)).unwrap();
std::fs::write(tmp.path().join("notes.md"), "# Title\n").unwrap();
write_test_png(&tmp.path().join("shot.png"));
write_three_page_pdf(&tmp.path().join("doc.pdf"));
for name in ["plain.txt", "data.csv", "notes.md", "shot.png", "doc.pdf"] {
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
click_open_in_explorer(&mut app, name);
assert!(
matches!(app.focus, Pane::Editor),
"{name}: one click must hand the keyboard to the editor"
);
}
}
/// A click on a spreadsheet must leave the arrow keys scrolling the grid, not
/// the file list - the same defect as the PDF, one tab type over.
#[test]
fn a_spreadsheet_opened_with_one_click_scrolls_with_the_arrow_keys() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("data.csv"), csv_body(40)).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
click_open_in_explorer(&mut app, "data.csv");
app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
.unwrap();
assert_eq!(
sheet_cursor(&app).0,
1,
"Down must act on the grid (cell cursor), not the file list"
);
}
/// Selecting a folder row must not move focus: the click is a tree gesture and
/// the user is still browsing.
#[test]
fn clicking_a_folder_in_the_explorer_keeps_the_keyboard_in_the_tree() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join("src")).unwrap();
std::fs::write(tmp.path().join("src/lib.rs"), "fn main() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
click_open_in_explorer(&mut app, "src");
assert!(
matches!(app.focus, Pane::Tree),
"expanding a folder is a tree gesture: the keyboard stays in the Explorer"
);
}
/// With no enabled runner claiming the workspace (`runner_for` is `None` —
/// no recognised project, or its runner extension disabled), every Testing
/// run gesture must refuse with a status instead of shelling `cargo test`
/// in a directory cargo knows nothing about. Only discovery was guarded;
/// the four run entry points started a spurious run.
#[test]
fn a_workspace_with_no_test_runner_refuses_every_run_gesture() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("notes.txt"), "no project here\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
fn assert_refused(app: &mut App, label: &str) {
assert!(!app.testing.is_busy(), "{label} must not start");
assert!(
app.status.contains("No test runner"),
"{label} must say why it refused: {:?}",
app.status
);
app.status.clear();
}
app.run_all_tests();
assert_refused(&mut app, "run-all");
app.run_test(String::from("some::test"));
assert_refused(&mut app, "single run");
app.run_suite(String::from("suite"));
assert_refused(&mut app, "suite run");
app.run_named_test(String::from("named"));
assert_refused(&mut app, "named run");
}
/// cargo's positional filter is a substring match, so running suite `parse`
/// with a bare pattern also sweeps `parse_utils::b` and every other
/// prefix-sharing sibling. The suite gesture must anchor on `parse::`.
#[test]
fn running_a_suite_never_sweeps_prefix_sharing_siblings() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("Cargo.toml"),
"[package]\nname = \"t\"\nversion = \"0.0.0\"\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for n in ["parse::a", "parse_utils::b"] {
app.testing.apply_case(crate::testing::model::TestCase {
name: n.into(),
status: crate::testing::model::TestStatus::NotRun,
});
}
app.run_suite(String::from("parse"));
use crate::testing::model::TestStatus;
assert_eq!(
app.testing.status_of("parse::a"),
Some(TestStatus::Running),
"the suite's own case runs"
);
assert_eq!(
app.testing.status_of("parse_utils::b"),
Some(TestStatus::NotRun),
"a prefix-sharing sibling suite must stay untouched"
);
}
/// Run-at-cursor knows only the fn's leaf name. When the discovered tree
/// holds exactly one case with that leaf, the run must target it exactly
/// instead of handing cargo a bare substring that also matches `run_fast`.
#[test]
fn run_at_cursor_with_a_unique_leaf_runs_exactly_that_test() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("Cargo.toml"),
"[package]\nname = \"t\"\nversion = \"0.0.0\"\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for n in ["parse::run", "other::run_fast"] {
app.testing.apply_case(crate::testing::model::TestCase {
name: n.into(),
status: crate::testing::model::TestStatus::NotRun,
});
}
app.run_named_test(String::from("run"));
use crate::testing::model::TestStatus;
assert_eq!(
app.status, "Running test parse::run",
"a unique leaf resolves to its full name for an exact run"
);
assert_eq!(
app.testing.status_of("other::run_fast"),
Some(TestStatus::NotRun),
"a test merely containing the leaf must stay untouched"
);
}
/// Clicking a test's name greps the workspace for its `fn`; that walk runs
/// on a background thread and the editor jump lands via the drain, so a big
/// workspace can't freeze the render loop. Covers hit and miss.
#[test]
fn a_test_name_click_jumps_to_source_via_the_background_locator() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("Cargo.toml"),
"[package]\nname = \"t\"\nversion = \"0.0.0\"\n",
)
.unwrap();
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
let lib = tmp.path().join("src/lib.rs");
std::fs::write(
&lib,
"#[cfg(test)]\nmod tests {\n #[test]\n fn target_case() { assert!(true); }\n}\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.jump_to_test_source(String::from("tests::target_case"));
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
app.sync_explorer_panels();
if app.editor.path.as_deref() == Some(lib.as_path()) {
break;
}
assert!(
std::time::Instant::now() < deadline,
"the locator result never arrived; editor at {:?}",
app.editor.path
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert_eq!(app.editor.cursor_row, 3, "caret lands on `fn target_case`");
app.jump_to_test_source(String::from("nope::missing"));
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
app.sync_explorer_panels();
if app
.status
.contains("No source found for test nope::missing")
{
break;
}
assert!(
std::time::Instant::now() < deadline,
"the miss status never arrived, status {:?}",
app.status
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
/// Ctrl+Shift+H on a tiny host window: the popup clamps inverted
/// (min > max) below 40 columns or 10 rows and `Ord::clamp` panics,
/// taking the raw-mode TUI down.
#[test]
fn the_history_popup_survives_a_tiny_frame() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.open_command_history();
let backend = ratatui::backend::TestBackend::new(30, 8);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
}
/// A zero-sized frame (a host window mid-collapse) has no cells at all:
/// the fallback geometry used to floor each axis to one cell, handing
/// back a 1×1 popup that sits outside the frame it was asked to fit.
#[test]
fn a_zero_sized_frame_gets_no_fallback_popup() {
let r = fallback_popup_rect(Rect::new(0, 0, 0, 0), 100);
assert_eq!(r.area(), 0, "no cells exist to draw into: {r:?}");
let r = fallback_popup_rect(Rect::new(0, 0, 80, 0), 110);
assert_eq!(r.area(), 0, "a zero-height frame cannot host rows: {r:?}");
let r = fallback_popup_rect(Rect::new(2, 3, 30, 8), 110);
assert!(
r.x >= 2 && r.y >= 3 && r.right() <= 32 && r.bottom() <= 11,
"a real frame keeps the popup inside it: {r:?}"
);
}
/// vim's `e` at the last word of a row hops to the next row's first word
/// end, exactly like `w` and `b` already wrap; it used to be a dead key
/// there because the scan ran into the row's trailing padding.
#[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);
// A fresh row first: whatever the spawned shell printed (a prompt, a
// banner — it varies by environment) must not shift the fed text, and
// the navigation below is cursor-relative rather than jumping to the
// scrollback top, so the test is hermetic against prior output.
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'");
}
/// vim's `e` keeps advancing across word-less lines: from the last word
/// before a run of blank rows it lands on the end of the next word below
/// them, not at column 0 of the first blank row.
#[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'");
}
/// A 100x1 blue PNG: one cell tall at any pane geometry, so a scrolled
/// anchor changes only the placement row, never the baked cell size.
fn wide_short_png() -> Vec<u8> {
let mut png = Vec::new();
image::RgbaImage::from_pixel(100, 1, image::Rgba([0, 0, 255, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.expect("encode test png");
png
}
/// Stage an app with an inline image captured at the pane's bottom row and
/// the overlay freshly baked, on the given protocol.
fn app_with_baked_terminal_image(
protocol: crate::iterm2_inline::InlineImageProtocol,
) -> (tempfile::TempDir, App) {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.inline_protocol = protocol;
app.cell_pixel = Some((8, 16));
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
// The pane owns a REAL shell, and its startup output arrives whenever the
// machine gets round to it (#326). Every assertion built on this fixture
// reads the picture's position, so a prompt landing after the bake scrolls
// the grid out from under it and the test fails for a reason that has
// nothing to do with what it is testing. Wait for the shell to go quiet
// first: two consecutive idle reads, so a gap between two bursts is not
// mistaken for the end of them.
let mut quiet = 0;
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while quiet < 2 && std::time::Instant::now() < deadline {
let _ = app.terminals[0].take_dirty();
std::thread::sleep(std::time::Duration::from_millis(60));
if app.terminals[0].peek_pending_bytes() == 0 && !app.terminals[0].peek_dirty() {
quiet += 1;
} else {
quiet = 0;
}
}
// The deadline is a failure, not a fallback. Falling through it would hand
// the caller exactly the unsynchronised fixture this wait exists to
// prevent, and the resulting flake would look like the picture logic
// rather than a shell that never settled.
assert!(
quiet >= 2,
"the pane's shell never went quiet within 10s, so the fixture cannot bake against a stable grid"
);
let h = app.terminals[0].last_inner.height as usize;
app.terminals[0].feed_bytes_for_test("\r\n".repeat(h * 2).as_bytes());
app.terminals[0].push_image_for_test(wide_short_png());
app.update_terminal_image_overlay();
assert!(
app.overlays.terminal_image.has_image(),
"staging: the picture must have baked"
);
(tmp, app)
}
/// Output scrolling under an on-screen inline image moves only the
/// placement row; re-running the full decode + Lanczos resize + PNG encode
/// per scrolled row froze the render thread for the whole pane height on
/// any real photo.
#[test]
fn a_scrolled_inline_image_reuses_its_baked_payload() {
let (_tmp, mut app) =
app_with_baked_terminal_image(crate::iterm2_inline::InlineImageProtocol::Kitty);
let y0 = app.overlays.terminal_image.layout().unwrap().cell_y;
let bakes = crate::iterm2_inline::FIT_IMAGE_BAKES.with(|c| c.get());
app.terminals[0].feed_bytes_for_test(b"\r\n\r\n");
app.update_terminal_image_overlay();
let l = app.overlays.terminal_image.layout().unwrap();
assert_eq!(l.cell_y, y0 - 2, "the placement follows the anchor");
assert_eq!(
crate::iterm2_inline::FIT_IMAGE_BAKES.with(|c| c.get()),
bakes,
"a pure row move must not re-decode the image"
);
}
/// On iTerm2/Sixel the image blit happens after ratatui draws the frame:
/// with the pane's right-click menu open over the picture, the blit erased
/// the overlapped menu rows. The editor preview already suppresses its
/// image under an open context menu; the terminal overlay must too.
#[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();
// The pane's right-click menu, opened on the picture itself.
app.context_menu = Some(ContextMenu {
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"
);
}
/// A wheel notch on the pane BORDER while the child tracks the mouse used
/// to vanish: the report was undeliverable (the border sits outside the
/// inner grid) and the handler had no fall-through, so nothing scrolled —
/// yet the same cell scrolls croft's scrollback fine on a non-tracking
/// pane. An undeliverable report now falls back the same way.
#[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();
// Fill scrollback so there is history to scroll into, then have the
// child enable mouse tracking.
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"
);
}
/// In the alternate screen there is no scrollback, so Shift+End must fall
/// through to the program like its comment promises and like Shift+Home /
/// Shift+PageUp/PageDown already do; it used to be swallowed because the
/// bottom-reset arm had no alt-screen guard.
#[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() {
// The deterministic half of #397's quick-select entry. Its sibling below
// was measured at 3 failures in 20 runs under load, because a REAL
// shell's prompt wraps to several rows and the pane had one row of slack;
// a rate is the best evidence a race allows, and it is not a test. Both
// now run on a silent pane.
//
// This one feeds the prompt itself, so the geometry is the whole claim
// and the machine has no say. Four rows of it, then the same park,
// stream and assert. On the unmaximized pane, which is five rows here,
// this fails on every machine on every run.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// The pane's child writes nothing, so the grid holds only the bytes fed
// below: a real shell's startup prompt landing between them adds rows
// the geometry does not count (#641).
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;
// The same tripwire the sibling carries. This fixture's own band is
// wider - it needs eight rows, not sixteen - but a panel that shrank
// below the sibling's threshold should fail in both, not silently pass
// here while failing there.
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();
// The prompt arrives AFTER the URL is on screen, which is the race: one
// that lands before the flood is scrolled away by it and costs nothing.
// Four rows of it, the shape a hostname-and-path prompt takes when it
// wraps at this width, and then the stream that scrolls the URL.
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();
// The label clause is what makes `open_terminal_quick_select` above
// load-bearing: without it the bare URL satisfies this assertion just as
// well as a labelled one, and deleting the call left the test green.
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:?}"
);
}
/// Quick-select labels ride the scroll clock like every other overlay:
/// output streaming under an open label set used to leave the gold labels
/// at fixed viewport rows while their matches scrolled away, so the user
/// typed the label next to one thing and copied another.
#[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();
// A SILENT pane (#397). The row slack below was this test's first fix,
// and it held until a full-suite run captured the pane holding ONLY the
// shell's wrapped prompt and the trailing x1 x2 x3, the URL gone: the
// shell's prompt repaint after the maximize's SIGWINCH landed between
// the feeds and rewrote the rows the URL sat on. Slack absorbs a prompt
// that appends; it cannot absorb one that repaints. A child that prints
// nothing removes the writer entirely, and the subject here -- croft's
// label overlay following content the pane streams -- needs a grid, not
// a shell. The slack assertion stays: the scroll this test drives still
// needs the rows.
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();
// The panel over the editor, so the pane has ROWS. Unmaximized it is a
// few rows tall here, and this test parks its URL four rows from the
// bottom. When the pane still ran the workspace shell that was almost
// no slack against a wrapped prompt (this test's first entry in #397,
// 3 failures in 20 runs under load); with a silent child the rows are
// simply what the scroll below needs, and the maximize is how it gets
// them.
app.toggle_terminal_maximize();
term.draw(|f| app.render(f)).unwrap();
// Park the cursor at the pane bottom so every further row SCROLLS.
let h = app.terminals[0].last_inner.height as usize;
// The precondition this fix IS, checked in the same run as the claim it
// supports: if a future panel change shrank the pane back toward five
// rows, the test would quietly return to flaking instead of failing.
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());
// One atomic feed, opening with its own newline, so "\r\n" + URL lands
// under one grid lock with the URL at column 0. #62 saw the match wrap
// the pane edge when another writer got between two feeds; the pane is
// silent now, and the shape is kept because it is the one that cannot
// wrap whatever else is on screen.
app.terminals[0].feed_bytes_for_test(b"\r\nhttp://drift.io");
app.open_terminal_quick_select();
// The URL by name, not `is_some()`: quick select stages every match on
// screen, and naming the one this test planted keeps the assertion
// about it rather than about whatever else happens to match.
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();
// Join the pane's inner rows into one stream before searching, so pane
// geometry can't split the needle across a row boundary (#62), and
// don't pin WHICH gold label the URL drew: label assignment is
// bottom-priority over every match on screen, and the letter is not the
// claim. The invariant is that SOME label still covers the URL's first
// cell after the scroll — the 'h' is overlaid, the rest is intact.
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:?}"
);
}
/// The #64 defect end-to-end: a URL wrapping the pane edge was invisible as
/// a URL — the scanner saw display rows independently, so the head fragment
/// matched nothing and the tail was labelled as a filesystem path, and
/// typing the label copied `/drift.io` instead of what the user sees.
/// Stitched scanning must stage the WHOLE URL, anchored on its head.
#[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();
// One atomic feed (#62): its own newline pins the pad to column 0, the
// pad parks the URL six cells before the pane edge, so "http:/" fills
// the row (setting WRAPLINE) and "/drift.io" continues on the next.
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");
// `starts_with`, not equality: the live child shell's prompt can land
// right after the fed chunk, gluing itself onto the URL's tail within
// the same logical line — the head is the invariant.
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<_>>()
);
// Committing the URL's label copies the whole URL, not the fragment.
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
);
}
/// Quick-select is bound to the pane it opened on, exactly like copy mode:
/// after a pane switch its labels must close, never be pushed onto (or
/// pasted into) the newly active pane at the old pane's coordinates.
#[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);
// Three URLs per row across ten rows: >26 matches forces two-char
// labels, so the first typed char takes the PUSH path (a live re-push
// of the hint set) rather than committing and closing.
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");
// A label PREFIX char (the first char of some two-char label).
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"
);
}
/// The find anchor rides the scroll clock like every other line-anchored
/// overlay: output streaming while the bar is open used to leave the
/// stored match line pointing N rows below its text, so the next
/// Enter/Shift+Enter walked from a phantom position — re-finding the same
/// occurrence or skipping others — and the bright active highlight
/// detached from its row.
#[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);
// Fill the screen first so later output rotates rows into scrollback
// (line indices only drift once the grid is full).
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, top, now) = app.terminals[0].grid_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 = (abs - top).clamp(0, lines.len() as i32 - 1) as usize;
lines[row].clone()
};
assert!(
anchored_line(&app).contains("match-three"),
"staging: the first anchor is the bottom-most occurrence"
);
// Output streams while the bar is open: every stored line drifts.
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)
);
}
/// Clearing a pane invalidates find's whole world: the anchored match
/// names content that no longer exists (and the clear can kill the scroll
/// clock's tracer), so the anchor and active highlight must drop and the
/// match count must honestly read zero instead of navigation walking from
/// a phantom position over the emptied grid.
#[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"
);
}
/// Terminal find is bound to the pane it opened on: a gesture that
/// activates a sibling pane must close it AND clear the highlight on the
/// pane that owned it. Closing against the newly active pane instead left
/// the owning pane's needle painted for the rest of the session and
/// applied the stored jump anchor to the wrong pane's 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"
);
}
/// Copy mode is bound to the pane it opened on: a gesture that activates a
/// sibling pane closes the mode (tmux-style) instead of folding the other
/// pane's independent scroll clock into the stored coordinates and
/// painting a garbage selection there.
#[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"
);
}
/// #37: a failed external reload was silently discarded — the sweep tried,
/// the re-read died (file replaced by a directory), and nothing said so.
/// The tab keeps its last good view and the status line reports it.
#[test]
fn a_failed_external_reload_reports_in_the_status_line() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("f.txt");
std::fs::write(&f, "one\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
std::fs::remove_file(&f).unwrap();
std::fs::create_dir(&f).unwrap();
assert!(
app.reload_open_file_after_external_change(),
"a failed reload is redraw-worthy, not an empty sweep"
);
assert!(
app.status.contains("Reload failed"),
"the status line must name the failure; got: {}",
app.status
);
assert_eq!(
app.editor.lines[0], "one",
"the last good buffer survives the failed reload"
);
}
#[test]
fn clicking_a_commit_graph_row_opens_the_commit_patch_tab() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.txt"), "one\n").unwrap();
let git = |args: &[&str]| {
std::process::Command::new("git")
.arg("-C")
.arg(tmp.path())
.args(args)
.env("GIT_AUTHOR_NAME", "t")
.env("GIT_AUTHOR_EMAIL", "t@t")
.env("GIT_COMMITTER_NAME", "t")
.env("GIT_COMMITTER_EMAIL", "t@t")
.output()
.unwrap()
};
git(&["init", "-q"]);
git(&["add", "-A"]);
git(&["commit", "-qm", "first commit"]);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// The arming step of #103: render the DEFAULT Explorer sidebar once so
// its bottom sections (OPEN EDITORS / TIMELINE / DEPENDENCIES) record
// their hit rects — real sessions always do this before the user ever
// reaches Source Control. Stale copies of those rects must not shadow
// the COMMITS strip that paints in the same rows afterwards.
{
let backend = ratatui::backend::TestBackend::new(140, 44);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
}
app.set_sidebar_view(SidebarView::SourceControl);
// Let the git worker deliver status + graph, then render so every
// sidebar rect (including the COMMITS strip) records its hit area.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
let mut graph_rect = Rect::default();
let mut row = 0u16;
let mut ready = false;
while std::time::Instant::now() < deadline {
let _ = app.drain_git_responses();
let _ = app.sync_explorer_panels();
let backend = ratatui::backend::TestBackend::new(140, 44);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
graph_rect = app.commit_graph.last_area;
// Border row, then the section header, then the first commit row.
row = graph_rect.y + 2;
if graph_rect.height > 1 && app.commit_graph.commit_at(row).is_some() {
ready = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert!(
ready,
"precondition: the COMMITS graph must render with a clickable row; rect {graph_rect:?}, \
inflight {:?}, probes {:?}",
app.graph_fetch_inflight,
(40u16..44)
.map(|y| app.commit_graph.commit_at(y).map(|c| c.short_hash.clone()))
.collect::<Vec<_>>()
);
let col = graph_rect.x + 6;
let short = app
.commit_graph
.commit_at(row)
.map(|c| c.short_hash.clone())
.expect("precondition established a commit at the click row");
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
// The patch is read off the UI thread.
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"the commit patch",
|| {
app.drain_git_view();
app.git_view_job.is_none()
},
);
assert!(
app.status.contains("Opened commit"),
"clicking a commit row must open its patch tab; status: {:?}",
app.status
);
assert_eq!(
app.editor.path.as_deref(),
Some(Path::new(&format!("commit {short}"))),
"the active tab must be the clicked commit's patch"
);
let body = app.editor.lines.join("\n");
assert!(
body.contains("first commit") && body.contains("diff --git"),
"the patch tab must carry the commit message and its diff"
);
}
#[test]
fn status_elision_never_fires_on_a_message_that_fits() {
let tmp = tempfile::tempdir().unwrap();
// A git repo puts the branch segment in the bar, like any real session.
let git = |args: &[&str]| {
std::process::Command::new("git")
.arg("-C")
.arg(tmp.path())
.args(args)
.env("GIT_AUTHOR_NAME", "t")
.env("GIT_AUTHOR_EMAIL", "t@t")
.env("GIT_COMMITTER_NAME", "t")
.env("GIT_COMMITTER_EMAIL", "t@t")
.output()
.unwrap()
};
git(&["init", "-q", "-b", "main"]);
std::fs::write(tmp.path().join("a.txt"), "x\n").unwrap();
git(&["add", "-A"]);
git(&["commit", "-qm", "init"]);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while std::time::Instant::now() < deadline {
let _ = app.drain_git_responses();
if app.git.status().branch.is_some() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
app.status = String::from("Quick select: type a label to copy, UPPERCASE pastes, Esc cancels");
// 153 cols: prefix (with the branch segment and zone dividers) + message
// + right cluster (with its │ seams) total 152, so the message fits and
// must paint verbatim — elision may only fire when the arithmetic says
// the message truly cannot fit.
let backend = ratatui::backend::TestBackend::new(153, 40);
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 last_row: String = (a.x..a.x + a.width)
.map(|x| buf[(x, a.y + a.height - 1)].symbol().to_string())
.collect();
// The WHOLE message must be present: middle-elision keeps both ends, so a
// substring from one end would pass even after a regression elided the
// other.
assert!(
last_row.contains(app.status.as_str()),
"a transient that fits beside the right cluster must paint verbatim, \
not elide; the bar showed: {last_row:?}"
);
}
#[test]
fn create_prompt_labels_speak_workspace_relative() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join("src")).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_create_prompt(CreateKind::File, tmp.path().join("src"));
let label = app.prompt.as_ref().unwrap().label.clone();
assert_eq!(
label, "New File in src",
"the prompt title's one job is naming the target directory; a deep \
absolute workspace path truncates it out of the popup (#105)"
);
app.prompt = None;
app.open_create_prompt(CreateKind::Folder, tmp.path().to_path_buf());
let label = app.prompt.as_ref().unwrap().label.clone();
assert_eq!(
label, "New Folder in .",
"the workspace root itself reads as '.'"
);
}
/// A repo with a real merge conflict in `shared.txt` (two blocks) produced
/// by an actual `git merge`, plus a clean second file.
fn conflicted_repo(tmp: &std::path::Path) {
let git = |args: &[&str]| {
std::process::Command::new("git")
.arg("-C")
.arg(tmp)
.args(args)
.env("GIT_AUTHOR_NAME", "t")
.env("GIT_AUTHOR_EMAIL", "t@t")
.env("GIT_COMMITTER_NAME", "t")
.env("GIT_COMMITTER_EMAIL", "t@t")
.output()
.unwrap()
};
git(&["init", "-q", "-b", "main"]);
std::fs::write(
tmp.join("shared.txt"),
"alpha\nbase-one\nm1\nm2\nm3\nm4\nm5\nbase-two\nomega\n",
)
.unwrap();
std::fs::write(tmp.join("clean.txt"), "untouched\n").unwrap();
git(&["add", "-A"]);
git(&["commit", "-qm", "base"]);
git(&["checkout", "-q", "-b", "feature"]);
std::fs::write(
tmp.join("shared.txt"),
"alpha\nfeature-one\nm1\nm2\nm3\nm4\nm5\nfeature-two\nomega\n",
)
.unwrap();
git(&["commit", "-aqm", "feature edit"]);
git(&["checkout", "-q", "main"]);
std::fs::write(
tmp.join("shared.txt"),
"alpha\nmain-one\nm1\nm2\nm3\nm4\nm5\nmain-two\nomega\n",
)
.unwrap();
git(&["commit", "-aqm", "main edit"]);
let merge = git(&["merge", "feature"]);
assert!(
!merge.status.success(),
"the merge must conflict for these tests"
);
}
/// Wait for the git worker to deliver entries, then return the index of the
/// conflicted `shared.txt` entry in the Source Control panel.
/// Wait for the git worker - which spawns a real `git` per query - to report
/// the conflicted entry, and return its index.
///
/// The budget is load-scaled (#307). This helper is where
/// `accept_all_incoming_then_complete_merge_stages_the_resolved_file` was
/// actually failing under load: the untimed `git status --porcelain` at the
/// end of that test cannot time out at all, so the fixed 5s deadline here was
/// the only clock in the test, which puts it in the same family as the other
/// three rather than in a category of its own.
fn wait_for_conflicted_entry(app: &mut App) -> usize {
app.set_sidebar_view(SidebarView::SourceControl);
let mut found = None;
crate::test_budget::await_spawned(
std::time::Duration::from_millis(1000),
"the git worker to report the conflicted entry",
|| {
let _ = app.drain_git_responses();
found = app
.source_control
.entries
.iter()
.position(|e| e.kind == crate::git::ChangeKind::Conflicted);
found.is_some()
},
);
found.expect("await_spawned returns only once the entry is present")
}
#[test]
fn scm_click_on_a_conflicted_entry_opens_the_merge_editor_on_the_stages() {
let tmp = tempfile::tempdir().unwrap();
conflicted_repo(tmp.path());
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let idx = wait_for_conflicted_entry(&mut app);
app.open_source_control_entry(idx);
assert_eq!(
app.editor.path.as_deref().map(|p| p.file_name().unwrap()),
Some(std::ffi::OsStr::new("shared.txt")),
"the conflicted file must open"
);
let mv = app.editor.merge.as_ref().expect("the merge editor is up");
assert!(!mv.from_markers, "git stages, not marker synthesis");
assert_eq!(mv.conflicts.len(), 2, "both overlapping hunks tracked");
// The base pane holds the stage-1 (common ancestor) content.
assert_eq!(mv.base[1], "base-one");
assert_eq!(mv.conflicts[0].ours, vec!["main-one".to_string()]);
assert_eq!(mv.conflicts[0].theirs, vec!["feature-one".to_string()]);
// The Result starts as base for conflict regions (nothing else
// differed in this fixture, so the whole buffer equals base).
assert_eq!(app.editor.lines[1], "base-one");
assert_eq!(
app.editor.cursor_row, mv.conflicts[0].result_start,
"the cursor lands on the first conflict region"
);
assert!(
app.status.contains("2 conflicts"),
"the status counts the conflicts; was {:?}",
app.status
);
// "Reopen as Text" reaches the unchanged in-buffer marker flow.
app.run_command(crate::widgets::command_palette::Command::ReopenAsText);
assert!(app.editor.merge.is_none(), "back to a plain text tab");
assert_eq!(
app.editor.conflicts().len(),
2,
"the marker scan sees the on-disk conflict blocks again"
);
}
#[test]
fn f7_cycles_conflicts_in_a_plain_editor_tab() {
let tmp = tempfile::tempdir().unwrap();
conflicted_repo(tmp.path());
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor
.open_pinned(&tmp.path().join("shared.txt"))
.unwrap();
app.focus_pane(Pane::Editor);
let headers: Vec<usize> = app
.editor
.conflicts()
.iter()
.map(|b| b.ours_start)
.collect();
assert_eq!(headers.len(), 2, "precondition: two conflict blocks");
app.editor.cursor_row = 0;
let f7 = |app: &mut App, shift: bool| {
let mut key = crossterm::event::KeyEvent::new(KeyCode::F(7), KeyModifiers::NONE);
if shift {
key.modifiers = KeyModifiers::SHIFT;
}
app.handle_key(key).unwrap();
};
f7(&mut app, false);
assert_eq!(
app.editor.cursor_row, headers[0],
"first F7 reaches conflict 1"
);
assert!(
app.status.contains("Conflict 1 of 2"),
"status names the position; was {:?}",
app.status
);
f7(&mut app, false);
assert_eq!(
app.editor.cursor_row, headers[1],
"second F7 reaches conflict 2"
);
f7(&mut app, false);
assert_eq!(app.editor.cursor_row, headers[0], "F7 wraps to conflict 1");
f7(&mut app, true);
assert_eq!(
app.editor.cursor_row, headers[1],
"Shift+F7 walks backwards with wrap"
);
}
#[test]
fn accept_all_incoming_then_complete_merge_stages_the_resolved_file() {
let tmp = tempfile::tempdir().unwrap();
conflicted_repo(tmp.path());
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let idx = wait_for_conflicted_entry(&mut app);
app.open_source_control_entry(idx);
// Completing while conflicts remain must refuse.
app.complete_merge();
assert!(
app.status.contains("unresolved"),
"complete must refuse while blocks remain; was {:?}",
app.status
);
app.run_command(crate::widgets::command_palette::Command::MergeAcceptAllIncoming);
assert_eq!(
app.editor
.merge
.as_ref()
.map(|mv| mv.unresolved_count())
.unwrap_or(usize::MAX),
0,
"every conflict resolved"
);
assert_eq!(
app.editor.lines.join("\n"),
"alpha\nfeature-one\nm1\nm2\nm3\nm4\nm5\nfeature-two\nomega",
"the Result keeps only the incoming side of both conflicts"
);
app.complete_merge();
assert!(
app.status.contains("Merge complete: staged shared.txt"),
"complete must save and stage; was {:?}",
app.status
);
let disk = std::fs::read_to_string(tmp.path().join("shared.txt")).unwrap();
assert!(
!disk.contains("<<<<<<<"),
"the resolved file must be on disk, marker-free"
);
let porcelain = std::process::Command::new("git")
.args(["-C", tmp.path().to_str().unwrap(), "status", "--porcelain"])
.output()
.unwrap();
let out = String::from_utf8_lossy(&porcelain.stdout).to_string();
let line = out
.lines()
.find(|l| l.contains("shared.txt"))
.expect("shared.txt still in status");
assert!(
line.starts_with("M "),
"after staging, shared.txt must be index-modified (M ), not unmerged; was {line:?}"
);
}
#[test]
fn merge_editor_accepts_toggles_and_manual_edits_update_the_counter() {
let tmp = tempfile::tempdir().unwrap();
conflicted_repo(tmp.path());
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let idx = wait_for_conflicted_entry(&mut app);
app.open_source_control_entry(idx);
assert!(app.editor.merge.is_some());
// Accept Current on conflict 1 (cursor already there).
app.run_command(crate::widgets::command_palette::Command::MergeAcceptCurrent);
assert_eq!(app.editor.lines[1], "main-one");
// F7 lands on conflict 2; Accept Combination (Incoming First).
app.merge_jump(false);
assert!(app.status.contains("Conflict 2 of 2"), "{:?}", app.status);
app.run_command(crate::widgets::command_palette::Command::MergeAcceptBothReverse);
assert_eq!(
app.editor.lines.join("\n"),
"alpha\nmain-one\nm1\nm2\nm3\nm4\nm5\nfeature-two\nmain-two\nomega",
"incoming-first combination splices theirs then ours"
);
assert_eq!(app.editor.merge.as_ref().unwrap().resolved_count(), 2);
// Checkbox toggling: unchecking the only accepted side reverts the
// region to base and the conflict back to unresolved.
use crate::merge_editor::{CheckSide, ConflictState};
app.merge_toggle_side(0, CheckSide::Incoming); // Current -> Both
assert_eq!(
app.editor.merge.as_ref().unwrap().conflicts[0].state,
ConflictState::Both
);
assert_eq!(app.editor.lines[1], "main-one");
assert_eq!(app.editor.lines[2], "feature-one");
app.merge_toggle_side(0, CheckSide::Current); // Both -> Incoming
app.merge_toggle_side(0, CheckSide::Incoming); // Incoming -> Unresolved
let mv = app.editor.merge.as_ref().unwrap();
assert_eq!(mv.conflicts[0].state, ConflictState::Unresolved);
assert_eq!(app.editor.lines[1], "base-one", "back to base text");
assert_eq!(mv.resolved_count(), 1);
// A manual edit inside the region marks it manually resolved.
let row = app.editor.merge.as_ref().unwrap().conflicts[0].result_start;
app.editor.cursor_row = row;
app.editor.cursor_col = 0;
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
app.merge_view_sync();
let mv = app.editor.merge.as_ref().unwrap();
assert_eq!(mv.conflicts[0].state, ConflictState::Manual);
assert_eq!(mv.resolved_count(), 2, "manual edits count as resolved");
// Base pane toggle.
assert!(!app.editor.merge.as_ref().unwrap().show_base);
app.run_command(crate::widgets::command_palette::Command::MergeToggleBase);
assert!(app.editor.merge.as_ref().unwrap().show_base);
assert_eq!(app.status, "Base pane shown");
}
#[test]
fn merge_editor_works_on_a_marker_only_file_outside_any_merge() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("plain.txt"),
"top\n<<<<<<< HEAD\nmine\n=======\nyours\n>>>>>>> other\nbottom\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor
.open_pinned(&tmp.path().join("plain.txt"))
.unwrap();
app.focus_pane(Pane::Editor);
app.run_command(crate::widgets::command_palette::Command::MergeOpenEditor);
let mv = app.editor.merge.as_ref().expect("marker synthesis worked");
assert!(mv.from_markers);
assert_eq!(mv.conflicts.len(), 1);
assert_eq!(mv.conflicts[0].ours, vec!["mine".to_string()]);
assert_eq!(mv.conflicts[0].theirs, vec!["yours".to_string()]);
assert!(
!app.editor.lines.iter().any(|l| l.starts_with("<<<<<<<")),
"the Result holds no markers"
);
app.run_command(crate::widgets::command_palette::Command::MergeAcceptBoth);
assert_eq!(
app.editor.lines.join("\n"),
"top\nmine\nyours\nbottom",
"Accept Both keeps ours then theirs"
);
// Undo steps back through the accept and the initial transform to
// the marker text.
app.editor.undo();
app.editor.undo();
assert!(
app.editor.lines.iter().any(|l| l.starts_with("<<<<<<<")),
"the marker buffer is one undo chain away"
);
}
#[test]
fn merge_editor_renders_source_panes_and_result_at_100_columns() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("plain.txt"),
"top\n<<<<<<< HEAD\nmine\n=======\nyours\n>>>>>>> other\nbottom\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor
.open_pinned(&tmp.path().join("plain.txt"))
.unwrap();
app.focus_pane(Pane::Editor);
app.run_command(crate::widgets::command_palette::Command::MergeOpenEditor);
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("MERGE"), "header row painted");
assert!(text.contains("0/1 conflict resolved"), "counter painted");
assert!(text.contains("CURRENT (yours)"), "current pane titled");
assert!(text.contains("INCOMING (theirs)"), "incoming pane titled");
assert!(
text.contains("RESULT (editable)"),
"result separator painted"
);
assert!(
text.contains("[ ]"),
"the unresolved conflict shows unchecked boxes"
);
let spans = app.editor.merge.as_ref().unwrap().check_spans.clone();
assert_eq!(spans.len(), 2, "one checkbox per source pane");
// Clicking the Current checkbox accepts that side.
let (y, xs, idx, _) = &spans[0];
let m = crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: xs.start,
row: *y,
modifiers: KeyModifiers::NONE,
};
app.handle_mouse(m);
let mv = app.editor.merge.as_ref().unwrap();
assert_eq!(
mv.conflicts[*idx].state,
crate::merge_editor::ConflictState::Current,
"the checkbox click accepted Current"
);
assert_eq!(app.editor.lines[1], "mine");
}
#[test]
fn clicking_an_accept_action_on_the_header_row_resolves_that_block() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
conflicted_repo(tmp.path());
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor
.open_pinned(&tmp.path().join("shared.txt"))
.unwrap();
app.focus_pane(Pane::Editor);
let backend = ratatui::backend::TestBackend::new(160, 44);
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("[Accept Current]") && text.contains("[Accept Incoming]"),
"the header row must carry the accept actions"
);
let span = app
.editor
.merge_action_spans
.iter()
.find(|(_, _, _, res)| *res == crate::merge::Resolution::Incoming)
.cloned()
.expect("an incoming action span must be recorded");
let before = app.editor.conflicts().len();
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
span.1.start,
span.0,
));
assert_eq!(
app.editor.conflicts().len(),
before - 1,
"the clicked block must resolve; status: {:?}",
app.status
);
assert!(
app.editor.lines.contains(&String::from("feature-one")),
"the incoming side must be kept"
);
assert!(
app.status.contains("Accepted incoming change"),
"status must confirm; was {:?}",
app.status
);
}
#[test]
fn add_watch_via_the_palette_prompt_then_clear_all() {
use crate::widgets::input_prompt::InputPurpose;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(crate::widgets::command_palette::Command::DebugAddWatch);
let prompt = app
.input_prompt
.as_ref()
.expect("Debug: Add Watch Expression must open an input prompt");
assert_eq!(prompt.purpose, InputPurpose::AddWatch);
for c in "len(cart)".chars() {
app.input_prompt.as_mut().unwrap().push_char(c);
}
app.submit_input_prompt();
assert!(app.input_prompt.is_none(), "submitting closes the prompt");
assert_eq!(app.watch_exprs, vec!["len(cart)"]);
assert!(app.status.contains("Watching len(cart)"));
// Duplicates are refused silently, whitespace trimmed.
app.add_watch_expression(String::from(" len(cart) "));
assert_eq!(app.watch_exprs.len(), 1, "no duplicate watches");
app.add_watch_expression(String::from("t"));
app.watch_vals
.insert(String::from("t"), (String::from("9.99"), true));
app.remove_watch_expression(0);
assert_eq!(
app.watch_exprs,
vec!["t"],
"removal is by display index, later rows keep their values"
);
assert!(app.watch_vals.contains_key("t"));
app.run_command(crate::widgets::command_palette::Command::DebugClearWatch);
assert!(app.watch_exprs.is_empty() && app.watch_vals.is_empty());
assert!(app.status.contains("Removed 1 watch expression"));
}
#[test]
fn peek_excerpt_windows_clamp_to_the_file() {
let lines: Vec<String> = (1..=20).map(|i| format!("line-{i}")).collect();
let (start, ex) = peek_excerpt(&lines, 10, 4, 12);
assert_eq!(
(start, ex.len()),
(6, 12),
"centered window: 4 above, 7 below"
);
let (start, ex) = peek_excerpt(&lines, 1, 4, 12);
assert_eq!(start, 0, "top of file clamps the above-context");
assert_eq!(ex.len(), 12);
let (start, ex) = peek_excerpt(&lines, 19, 4, 12);
assert_eq!(
(start, ex.len()),
(8, 12),
"bottom of file pulls the window up to keep it full"
);
let short: Vec<String> = (1..=3).map(|i| format!("s{i}")).collect();
let (start, ex) = peek_excerpt(&short, 1, 4, 12);
assert_eq!((start, ex.len()), (0, 3), "short files return whole");
let (_, empty) = peek_excerpt(&[], 0, 4, 12);
assert!(empty.is_empty());
}
#[test]
fn peek_popup_shows_the_target_then_enter_jumps_and_esc_closes() {
let tmp = tempfile::tempdir().unwrap();
let other = tmp.path().join("lib.rs");
let body: String = (1..=30)
.map(|i| {
if i == 15 {
String::from("fn the_answer() -> u32 {\n")
} else {
format!("// filler {i}\n")
}
})
.collect();
std::fs::write(&other, &body).unwrap();
let here = tmp.path().join("main.rs");
std::fs::write(&here, "fn main() { the_answer(); }\n// next line\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&here).unwrap();
app.focus_pane(Pane::Editor);
// The drain's consumer, driven directly (a live server is not needed to
// pin the popup contract).
app.open_peek_popup(other.clone(), 14, 3);
let popup = app.peek_popup.as_ref().expect("the peek popup must open");
let text = popup.lines.join("\n");
assert!(
text.starts_with("lib.rs:15"),
"header names the workspace-relative target; was {text:?}"
);
assert!(
text.contains("\u{25b6}15 fn the_answer"),
"the definition line is numbered and marked; was {text:?}"
);
assert!(text.contains("Enter jumps"), "the footer teaches the keys");
// Esc closes without moving.
app.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Esc,
KeyModifiers::NONE,
))
.unwrap();
assert!(app.peek_popup.is_none() && app.peek_target.is_none());
assert_eq!(app.editor.path.as_deref(), Some(here.as_path()));
// Enter jumps to the target and records it as a definition jump.
app.open_peek_popup(other.clone(), 14, 3);
app.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Enter,
KeyModifiers::NONE,
))
.unwrap();
assert!(app.peek_popup.is_none());
assert_eq!(
app.editor.path.as_deref(),
Some(other.as_path()),
"Enter converts the peek into the real jump"
);
assert_eq!(app.editor.cursor_row, 14);
// Any other key closes the popup AND keeps its meaning.
app.editor.open_pinned(&here).unwrap();
app.editor.cursor_row = 0;
app.open_peek_popup(other.clone(), 14, 3);
app.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Down,
KeyModifiers::NONE,
))
.unwrap();
assert!(app.peek_popup.is_none(), "a plain key dismisses the glance");
assert_eq!(
app.editor.cursor_row, 1,
"the dismissing key keeps its normal meaning — Down still moves"
);
}
#[test]
fn peek_references_steps_through_every_reference_with_up_and_down() {
// #616: the reply's references in the peek popup, "N of M" in the title,
// Up/Down wrapping through them, Enter jumping to the one shown.
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.rs");
let b = tmp.path().join("b.rs");
std::fs::write(&a, "fn f() {}\nfn g() { f(); }\n").unwrap();
std::fs::write(&b, "fn h() {\n f();\n}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.focus_pane(Pane::Editor);
app.peek_refs = Some((vec![(a.clone(), 1, 9), (b.clone(), 1, 4)], 0));
app.show_peeked_reference();
let text = |app: &App| app.peek_popup.as_ref().expect("popup").lines.join("\n");
assert!(text(&app).starts_with("Reference 1 of 2"), "{}", text(&app));
assert!(text(&app).contains("a.rs:2"));
let press = |app: &mut App, code| {
app.handle_key(crossterm::event::KeyEvent::new(code, KeyModifiers::NONE))
.unwrap()
};
press(&mut app, KeyCode::Down);
assert!(
text(&app).starts_with("Reference 2 of 2"),
"Down steps, not dismisses"
);
assert!(text(&app).contains("b.rs:2"));
press(&mut app, KeyCode::Down);
assert!(text(&app).starts_with("Reference 1 of 2"), "and wraps");
press(&mut app, KeyCode::Up);
press(&mut app, KeyCode::Enter);
assert!(app.peek_popup.is_none() && app.peek_refs.is_none());
assert_eq!(app.editor.path.as_deref(), Some(b.as_path()));
assert_eq!(app.editor.cursor_row, 1);
}
#[test]
fn alt_shift_f12_is_peek_references_not_go_to_references() {
let key_of = |m| crossterm::event::KeyEvent::new(KeyCode::F(12), m);
let peek = key_of(KeyModifiers::ALT | KeyModifiers::SHIFT);
assert!(is_peek_references_key(peek));
assert!(!is_peek_references_key(key_of(KeyModifiers::SHIFT)));
assert!(is_go_to_references_key(key_of(KeyModifiers::SHIFT)));
}
#[test]
fn f12_family_chords_route_alt_to_peek() {
let plain = crossterm::event::KeyEvent::new(KeyCode::F(12), KeyModifiers::NONE);
let alt = crossterm::event::KeyEvent::new(KeyCode::F(12), KeyModifiers::ALT);
assert!(is_go_to_definition_key(plain) && !is_peek_definition_key(plain));
assert!(is_peek_definition_key(alt) && !is_go_to_definition_key(alt));
let shift_alt =
crossterm::event::KeyEvent::new(KeyCode::F(12), KeyModifiers::ALT | KeyModifiers::SHIFT);
assert!(
!is_peek_definition_key(shift_alt),
"peek requires ALT alone in the F12 family"
);
}
#[test]
fn build_scan_installs_problems_replaces_per_pane_and_merges_with_lsp() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let cwd = tmp.path().join("proj");
std::fs::create_dir(&cwd).unwrap();
let cargo_out = "error[E0308]: mismatched types\n --> src/main.rs:12:5\n";
assert!(app.apply_build_scan(0, Some(&cwd), "cargo build", cargo_out));
let expected = cwd.join("src/main.rs");
let groups = app.problems.groups().to_vec();
let g = groups
.iter()
.find(|g| g.path == expected)
.expect("the resolved file must group in PROBLEMS");
assert_eq!(g.items.len(), 1);
assert_eq!(g.items[0].source, "rustc");
assert_eq!((g.items[0].line, g.items[0].col), (11, 4));
// A second pane contributes a different file; both coexist.
assert!(app.apply_build_scan(1, Some(&cwd), "make", "main.c:7:3: error: boom\n"));
assert_eq!(app.problems.groups().len(), 2);
// Pane 0 rebuilds clean: its contribution clears, pane 1's stays.
assert!(app.apply_build_scan(0, Some(&cwd), "cargo build", " Finished dev profile\n"));
let groups = app.problems.groups().to_vec();
assert_eq!(groups.len(), 1, "pane 0's fixed errors must vanish");
assert!(groups[0].path.ends_with("main.c"));
// Clean output from a pane with no history is a no-op.
assert!(!app.apply_build_scan(5, Some(&cwd), "true", "all good\n"));
app.clear_build_diagnostics();
assert!(app.problems.groups().is_empty());
assert!(app.status.contains("Cleared 1 build diagnostic"));
}
#[test]
fn replace_all_requires_confirmation_and_esc_cancels() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.txt"), "beta one\nbeta two\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.search.root = tmp.path().to_path_buf();
app.search.query = String::from("beta");
app.search.replace = String::from("delta");
app.search.run_query();
assert_eq!(app.search.hits.len(), 2, "precondition: two hits");
// A still-streaming search refuses: hits arriving after confirmation
// would be silently missed.
app.search.complete = false;
app.run_search_replace_all();
assert!(app.pending_replace_all.is_none());
assert!(app.status.contains("still running"));
app.search.complete = true;
app.run_search_replace_all();
assert_eq!(
app.pending_replace_all,
Some((2, 1, 0)),
"Enter must raise the modal with counts, not write"
);
let disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
assert!(
disk.contains("beta"),
"nothing is written before confirmation"
);
app.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Esc,
KeyModifiers::NONE,
))
.unwrap();
assert!(app.pending_replace_all.is_none());
assert!(app.status.contains("cancelled"));
let disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
assert!(disk.contains("beta"), "Esc leaves the files alone");
app.run_search_replace_all();
app.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Enter,
KeyModifiers::NONE,
))
.unwrap();
let disk = std::fs::read_to_string(tmp.path().join("a.txt")).unwrap();
assert_eq!(disk, "delta one\ndelta two\n", "Enter commits the rewrite");
assert!(app.status.contains("replaced 2 occurrence"));
}
#[test]
fn replace_all_skips_files_open_with_unsaved_changes() {
let tmp = tempfile::tempdir().unwrap();
let clean = tmp.path().join("clean.txt");
let dirty = tmp.path().join("dirty.txt");
std::fs::write(&clean, "beta here\n").unwrap();
std::fs::write(&dirty, "beta there\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&dirty).unwrap();
app.editor.insert_char('x'); // unsaved edit
assert!(app.editor.dirty);
app.search.root = tmp.path().to_path_buf();
app.search.query = String::from("beta");
app.search.replace = String::from("delta");
app.search.run_query();
app.search.complete = true;
app.run_search_replace_all();
assert_eq!(
app.pending_replace_all,
Some((1, 1, 1)),
"the modal counts exclude the dirty file and name the skip"
);
app.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Enter,
KeyModifiers::NONE,
))
.unwrap();
assert_eq!(
std::fs::read_to_string(&clean).unwrap(),
"delta here\n",
"the clean file is rewritten"
);
assert_eq!(
std::fs::read_to_string(&dirty).unwrap(),
"beta there\n",
"the dirty-open file is untouched on disk"
);
assert!(
app.status.contains("skipped dirty.txt") && app.status.contains("unsaved"),
"the skip is named; was {:?}",
app.status
);
}
#[test]
fn drag_target_over_the_sticky_band_is_the_pinned_directory() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("outer/inner")).unwrap();
for i in 0..25 {
std::fs::write(tmp.path().join(format!("outer/inner/f{i:02}.rs")), "x\n").unwrap();
}
std::fs::write(tmp.path().join("loose.txt"), "x\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let outer = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("outer"))
.unwrap();
app.tree.selected = outer;
app.tree.expand_selected();
let inner = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("inner"))
.unwrap();
app.tree.selected = inner;
app.tree.expand_selected();
// Scroll deep so the band pins ancestors, selection far below.
let deep = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("f20.rs"))
.unwrap();
app.tree.selected = deep;
app.tree.scroll = deep.saturating_sub(3);
let backend = ratatui::backend::TestBackend::new(120, 20);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let (band_y, pinned_idx) = {
let rows = app.tree.sticky_rows_for_test();
// The MIDDLE pinned row ("outer") is where the behaviors diverge:
// the outermost is the workspace root (dropping a root-level file
// into its own parent is correctly refused), and the deepest
// ("inner") coincides with the covered rows' parent, where the old
// sticky-blind resolution accidentally agreed.
assert!(rows.len() >= 3, "band must pin root/outer/inner here");
rows[1]
};
let loose = tmp.path().join("loose.txt");
let target = drag_target_index(&app.tree, band_y, std::slice::from_ref(&loose))
.expect("a pinned directory is a valid drop target");
assert_eq!(
target, pinned_idx,
"the drop target under the band is the PINNED directory, not the covered row"
);
let covered = app.tree.node_at_y(band_y);
assert_ne!(
covered,
Some(target),
"precondition: the band actually covers a different row there"
);
let _ = MouseEventKind::Down(MouseButton::Left); // silence unused import paths on some cfgs
}
// The 2026-08-09 gitcgr report: the installer slid into the slow
// compile-on-remote fallback without asking. `answer_install_fallback` is the
// decision point behind both the Enter and the click handler, so the y/yes
// parsing and the decline teardown are pinned here rather than at each caller.
#[test]
fn install_fallback_proceeds_only_on_an_explicit_yes() {
let tmp = tempfile::tempdir().unwrap();
for reply in ["y", "Y", "yes", "YES", " yes "] {
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.connect_dialog = Some(crate::widgets::connect_dialog::ConnectDialog::new(
"gitcgr".to_string(),
));
app.answer_install_fallback(reply);
let dialog = app.connect_dialog.as_ref().unwrap_or_else(|| {
panic!("{reply:?} accepts the slow compile, so the dialog stays up")
});
assert_eq!(
dialog.phase,
crate::widgets::connect_dialog::DialogPhase::Installing,
"{reply:?} should hand over to the installing phase"
);
}
}
#[test]
fn install_fallback_declines_and_tears_down_on_anything_else() {
let tmp = tempfile::tempdir().unwrap();
// An empty submit (bare Enter) is the important one: the footer offers it
// as Cancel, so it must never read as consent.
for reply in ["", " ", "n", "no", "yep", "later"] {
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.connect_dialog = Some(crate::widgets::connect_dialog::ConnectDialog::new(
"gitcgr".to_string(),
));
app.pending_remote_launch_host = Some("gitcgr".to_string());
app.answer_install_fallback(reply);
assert!(
app.connect_dialog.is_none(),
"{reply:?} declines, which closes the dialog"
);
assert!(
app.pending_remote_launch_host.is_none(),
"{reply:?} declines, so the pending launch is torn down too"
);
assert!(
app.status.contains("setup-cross"),
"the decline must point at the fast-path fix, got {:?}",
app.status
);
}
}
#[test]
fn install_fallback_without_a_dialog_does_not_panic() {
// The install thread can answer after the dialog is gone (user hit Esc
// while the prompt was in flight); both arms must tolerate the absence.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.answer_install_fallback("y");
assert!(app.connect_dialog.is_none());
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.answer_install_fallback("");
assert!(app.connect_dialog.is_none());
}
// 2026-08-22 (#242): a Mac croft shipped a remote main @ 84a31a0 while itself
// running an hour-old binary — locally, nothing ever compares the installed
// croft against the repo it came from. The drift hint claims bare F9 only
// while it is armed and no update is otherwise in flight, so the key keeps
// its debugger meaning everywhere else.
#[test]
fn drift_hint_arms_f9_only_while_idle() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(
!app.f9_update_armed(),
"no drift, no landed update: F9 stays a breakpoint key"
);
app.local_drift = Some(String::from("def456"));
assert!(app.f9_update_armed(), "an armed drift hint claims F9");
app.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[]));
assert!(
!app.f9_update_armed(),
"a spawned install must latch F9 even before its InProgress event \
is drained - two F9s in one input batch must not double-spawn"
);
app.self_install = None;
app.update_status = UpdateStatus::InProgress;
assert!(
!app.f9_update_armed(),
"a running rebuild must not re-trigger on F9"
);
app.local_drift = None;
app.update_status = UpdateStatus::Ready;
assert!(
app.f9_update_armed(),
"a landed update claims F9 for the re-exec"
);
}
// The probe end-to-end against a real repo: a baked hash that differs from
// the repo's HEAD must arm the hint and say how to act on it.
#[test]
fn drift_probe_verdict_arms_the_rebuild_hint() {
let repo = tempfile::tempdir().unwrap();
let git = |args: &[&str]| {
let out = std::process::Command::new("git")
.arg("-C")
.arg(repo.path())
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "git {args:?} failed");
String::from_utf8(out.stdout).unwrap().trim().to_string()
};
git(&["init", "-q"]);
git(&[
"-c",
"user.email=t@t",
"-c",
"user.name=t",
"commit",
"-q",
"--allow-empty",
"-m",
"one",
]);
let head = git(&["rev-parse", "--short", "HEAD"]);
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.drift_probe = Some(crate::update_watch::DriftProbe::start(
repo.path().to_string_lossy().into_owned(),
String::from("0000000"),
));
let mut armed = false;
for _ in 0..50 {
if app.poll_drift_probe() {
armed = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
assert!(armed, "the probe's verdict must arrive and report drift");
assert!(app.drift_probe.is_none(), "the probe answers exactly once");
assert_eq!(app.local_drift.as_deref(), Some(head.as_str()));
assert!(
app.status.contains("F9"),
"the status must say how to act on the drift: {:?}",
app.status
);
}
// CodeRabbit on #243: a failed rebuild used to strand the user — the drift
// marker was cleared when the install started and nothing restored it, so
// after a failure F9 silently reverted to its breakpoint meaning and only a
// full relaunch re-probed. A failure must leave the hint armed for a retry.
#[test]
fn a_failed_reinstall_rearms_the_drift_hint_for_retry() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.local_drift = Some(String::from("def456"));
app.self_install = Some(crate::update_watch::SelfInstall::preloaded(&[
crate::update_watch::UpdateEvent::InProgress,
crate::update_watch::UpdateEvent::Failed,
]));
assert!(app.poll_update_watch());
assert_eq!(app.update_status, UpdateStatus::Idle);
assert!(
app.status
.contains(&format!("self-install-{}.log", std::process::id())),
"a failure must say where THIS process's build log is: {:?}",
app.status
);
assert!(
app.f9_update_armed(),
"the drift hint must survive a failed rebuild so F9 retries"
);
}
#[test]
fn workspace_settings_layer_applies_at_startup_and_reloads_live() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::write(
tmp.path().join(".croft/config.json"),
r#"{"format_on_save":true,"disable_indent_guides":true}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// The workspace layer is later in the chain than any user layer, and
// test builds read no user layer at all (`config_layers::user_layers_dir`).
assert!(app.format_on_save, "committed workspace setting applies");
assert!(!app.indent_guides_enabled);
assert_eq!(
crate::config_layers::layer_of(&app.settings_provenance, "format_on_save"),
crate::config_layers::LayerKind::Workspace
);
// Saving an edited layer file re-merges and applies live, no relaunch.
std::fs::write(
tmp.path().join(".croft/config.json"),
r#"{"format_on_save":false,"disable_indent_guides":true}"#,
)
.unwrap();
let layer = crate::config_layers::workspace_config_path(tmp.path());
app.reload_config_for_path(&layer);
assert!(!app.format_on_save, "the edit applied without a restart");
assert!(app.status.contains("Settings reloaded"), "{}", app.status);
}
#[test]
fn settings_hub_shows_provenance_and_the_layer_rows() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::write(
tmp.path().join(".croft/config.json"),
r#"{"format_on_save":true}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_settings_view();
let rows = app.list_picker.as_ref().expect("hub open").rows.clone();
let fos = rows
.iter()
.find(|r| r.id == "toggle:format_on_save")
.unwrap();
assert!(
fos.label.contains("· workspace"),
"a workspace-won value says so: {}",
fos.label
);
for id in [
"cmd:open_settings_json",
"cmd:open_user_settings_local_json",
"cmd:open_workspace_settings_json",
"cmd:open_workspace_settings_local_json",
] {
assert!(rows.iter().any(|r| r.id == id), "missing hub row {id}");
}
}
#[test]
fn opening_workspace_local_settings_gitignores_it_first() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_workspace_settings(true);
let gi = std::fs::read_to_string(tmp.path().join(".croft/.gitignore")).unwrap();
assert!(gi.contains("config.local.json"), "{gi}");
let local = crate::config_layers::workspace_local_config_path(tmp.path());
assert_eq!(app.editor.path.as_deref(), Some(local.as_path()));
let seeded = std::fs::read_to_string(&local).unwrap();
assert!(seeded.contains("settings overlay"), "{seeded}");
}
#[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 lldb_program_resolves_against_the_session_cwd_not_crofts() {
let tmp = tempfile::tempdir().unwrap();
let cwd = tmp.path().join("proj");
std::fs::create_dir_all(cwd.join("target/debug")).unwrap();
std::fs::write(cwd.join("target/debug/app"), b"bin").unwrap();
let resolved = resolve_lldb_program("target/debug/app", &cwd).expect("exists under cwd");
assert_eq!(resolved, cwd.join("target/debug/app"));
assert!(resolved.is_absolute());
// A missing relative program errors with the RESOLVED path, so the
// message says where croft actually looked.
let err = resolve_lldb_program("target/release/app", &cwd).unwrap_err();
assert!(
err.contains(&cwd.join("target/release/app").display().to_string()),
"{err}"
);
// Absolute programs are taken as written.
let abs = cwd.join("target/debug/app");
let abs_str = abs.to_string_lossy().into_owned();
assert_eq!(
resolve_lldb_program(&abs_str, Path::new("/somewhere/else")).unwrap(),
abs
);
}
#[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"
);
}
/// #250: the compound layer reaches the user through
/// `open_debug_config_picker` -> `discover_compounds` -> rows ->
/// `confirm_list_picker` -> `resolve_compound`. Nothing but clippy's dead-code
/// lint currently guards that chain: a refactor dropping the compound rows
/// would leave `resolve_compound` with test-only callers and NO TEST FAILING,
/// which is the exact regression this PR exists to correct.
#[test]
fn the_picker_lists_compounds_and_selecting_one_reports_why_it_cannot_launch() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(
tmp.path().join(".vscode/launch.json"),
r#"{ "configurations": [
{ "name": "Server", "type": "python", "request": "launch", "program": "s.py" },
{ "name": "Client", "type": "python", "request": "launch", "program": "c.py" }
],
"compounds": [
{ "name": "Full Stack", "configurations": ["Server", "Client"] },
{ "name": "Broken", "configurations": ["Server", "Missing"] }
]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_debug_config_picker();
let picker = app.list_picker.as_ref().expect("picker open");
assert_eq!(
picker.rows.len(),
6,
"zero-config entry + two configurations + two compounds + Add Configuration"
);
let compound_row = picker
.rows
.iter()
.find(|r| r.label.starts_with("Full Stack"))
.expect("the compound is listed");
assert!(
compound_row.label.contains("Server"),
"the row names its members: {}",
compound_row.label
);
assert!(
compound_row.id.starts_with("compound:"),
"compound rows carry their own id space so they cannot collide with \
a configuration index: {}",
compound_row.id
);
// Selecting a resolvable MULTI-MEMBER compound launches every member
// (#310). It used to defer and name the issue; the session model holds a
// set now, so the assertion inverts. What must NOT happen is a subset
// launch, which would debug something other than what was asked for, so
// the count is what this checks rather than mere success.
let idx = picker
.rows
.iter()
.position(|r| r.label.starts_with("Full Stack"))
.unwrap();
app.list_picker.as_mut().unwrap().selected = idx;
app.confirm_list_picker();
// The old refusal ALSO named the compound and set feedback, so neither
// of those separates it from a launch. Only the launch path says this.
assert!(
app.status.contains("started no sessions") || app.status.starts_with("Debugging compound"),
"the compound went down the launch path rather than being refused: {}",
app.status
);
assert!(
!app.status.contains("#310"),
"and does not cite a limit that is gone: {}",
app.status
);
// A compound naming a configuration no launch.json declares is a config
// error, reported as such rather than folded into the not-yet message.
app.open_debug_config_picker();
let bad = app
.list_picker
.as_ref()
.unwrap()
.rows
.iter()
.position(|r| r.label.starts_with("Broken"))
.expect("the second compound is listed");
app.list_picker.as_mut().unwrap().selected = bad;
app.confirm_list_picker();
assert!(
app.status.contains("Missing"),
"the error names the member that does not exist: {}",
app.status
);
}
#[test]
fn debug_config_picker_lists_configs_and_selection_drives_f5() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(
tmp.path().join(".vscode/launch.json"),
r#"{ "configurations": [
{ "name": "API", "type": "python", "request": "launch", "program": "api.py" },
{ "name": "Javan", "type": "java", "program": "Main.java" }
]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_debug_config_picker();
let picker = app.list_picker.as_ref().expect("picker open");
assert_eq!(
picker.rows.len(),
4,
"zero-config entry + the two configs + Add Configuration"
);
assert!(picker.rows[0].label.contains("active file"));
assert!(picker.rows[1].label.contains("API"));
// Confirming a config remembers it as the F5 target. The unsupported
// type must surface a named error, not vanish from the picker silently.
app.list_picker.as_mut().unwrap().selected = 2;
app.confirm_list_picker();
assert_eq!(app.selected_debug_config.as_deref(), Some("Javan"));
assert!(
app.run_debug.feedback_is_error,
"unsupported type is an error: {:?}",
app.run_debug.feedback
);
assert!(
app.status.contains("unsupported type \"java\""),
"{}",
app.status
);
// The zero-config entry clears the selection.
app.open_debug_config_picker();
app.list_picker.as_mut().unwrap().selected = 0;
app.confirm_list_picker();
assert_eq!(app.selected_debug_config, None);
}
#[test]
fn missing_pre_launch_task_and_stale_selection_error_loudly() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::write(
tmp.path().join(".croft/launch.json"),
r#"[ { "name": "Built", "type": "lldb", "program": "/nope/bin", "preLaunchTask": "make everything" } ]"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_debug_config_picker();
app.list_picker.as_mut().unwrap().selected = 1;
app.confirm_list_picker();
assert!(
app.status
.contains("preLaunchTask \"make everything\" not found"),
"{}",
app.status
);
assert!(
app.pending_debug_launch.is_none(),
"nothing parked on error"
);
// A selection whose config was deleted falls back to zero-config.
app.selected_debug_config = Some(String::from("Deleted"));
app.start_selected_debug();
assert_eq!(app.selected_debug_config, None, "stale selection cleared");
}
/// #250: the Run and Debug panel's config row is the documented way to reach
/// the picker — both KEYBINDINGS.md and LAYOUT.md say so, and LAYOUT.md says
/// compounds "are listed too". But the row is gated on a count that only
/// covered `discover_configs`, so a workspace declaring ONLY compounds had no
/// row at all: `config_row_label`'s `(None, 0)` arm suppresses it, the render
/// never runs, `last_config_area` stays zero-sized, and the click guard on
/// `width > 0` refuses. The picker lists the compounds; nothing opens it.
#[test]
fn the_config_row_counts_compounds_so_a_compounds_only_workspace_still_has_one() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::write(
tmp.path().join(".croft/launch.json"),
r#"{"configurations":[{"name":"Server","type":"python","program":"s.py"}],
"compounds":[{"name":"Full Stack","configurations":["Server"]}]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.refresh_run_debug();
assert_eq!(
app.run_debug.config_count, 2,
"one configuration plus one compound — the row counts what the picker lists"
);
// The case that loses the row entirely rather than merely undercounting.
let only = tempfile::tempdir().unwrap();
std::fs::create_dir_all(only.path().join(".croft")).unwrap();
std::fs::write(
only.path().join(".croft/launch.json"),
r#"{"configurations":[],
"compounds":[{"name":"Orphan","configurations":["Nothing"]}]}"#,
)
.unwrap();
let mut app2 = App::new(only.path().to_path_buf()).unwrap();
app2.refresh_run_debug();
assert_eq!(
app2.run_debug.config_count, 1,
"a compounds-only workspace must still get a row, or the documented \
route to the picker does not exist for it"
);
// `config_row_label` is private to the widget module; the count is the
// input its `(None, 0)` suppression arm reads, so a non-zero count here is
// what makes the row exist. run_debug.rs's own unit test covers the arm.
}
#[test]
fn refresh_run_debug_syncs_the_config_row() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::write(
tmp.path().join(".croft/launch.json"),
r#"[ { "name": "One", "type": "python", "program": "a.py" } ]"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.selected_debug_config = Some(String::from("One"));
app.refresh_run_debug();
assert_eq!(app.run_debug.config_count, 1);
assert_eq!(app.run_debug.selected_config.as_deref(), Some("One"));
}
#[test]
fn rename_symbol_defers_the_prompt_until_a_verdict_arrives() {
// #254 item 6: F2 no longer opens the prompt straight away — it fires
// prepareRename and parks, so the prompt can pre-fill the server's own
// validated name. (The document here was never opened through the LSP
// layer, so the worker's answer is the unknown-document `unsupported`
// verdict; the verdict shapes themselves are covered by
// `a_prepare_rename_verdict_routes_to_the_prompt_status_or_fallback`.)
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("lib.rs"),
"fn main() {\n let value = 1;\n}\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&tmp.path().join("lib.rs")).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 1;
app.editor.cursor_col = 9; // inside `value`
app.start_rename_symbol();
assert!(app.prompt.is_none(), "the prompt waits on the verdict");
assert_eq!(app.status, "Preparing rename…");
assert!(
app.prepare_rename_request.is_some(),
"the request is armed for the verdict to match against"
);
}
#[test]
fn a_prepare_rename_verdict_routes_to_the_prompt_status_or_fallback() {
// Every shape the server can answer with (#254 item 6). The reply
// channel's sender lives inside the LSP worker, so these drive the
// verdict handler the drain loop delegates to.
use crate::lsp::manager::PrepareRenameResult;
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("lib.rs");
std::fs::write(&path, "fn main() {\n let value = 1;\n}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&path).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 1;
app.editor.cursor_col = 9; // inside `value`
let verdict = |target, error, unsupported| PrepareRenameResult {
request_id: 4,
path: path.clone(),
unsupported,
error,
target,
};
let arm = |app: &mut App| {
app.prepare_rename_request = Some((4, path.clone(), 1, 9, app.editor.edit_seq));
app.prompt = None;
app.status = String::from("Preparing rename…");
};
// A placeholder wins over the range text.
arm(&mut app);
assert!(app.apply_prepare_rename_verdict(verdict(
Some(((1, 8, 1, 13), Some(String::from("renamed")))),
None,
false
)));
assert_eq!(
app.prompt.as_ref().expect("prompt opened").buffer,
"renamed",
"the server's placeholder pre-fills the prompt"
);
// No placeholder: the validated range's own text.
arm(&mut app);
assert!(app.apply_prepare_rename_verdict(verdict(Some(((1, 8, 1, 13), None)), None, false)));
assert_eq!(
app.prompt.as_ref().expect("prompt opened").buffer,
"value",
"the range text pre-fills when no placeholder is offered"
);
// The server refused the position.
arm(&mut app);
assert!(app.apply_prepare_rename_verdict(verdict(
None,
Some(String::from("cannot rename a keyword")),
false
)));
assert_eq!(app.status, "Rename rejected: cannot rename a keyword");
assert!(app.prompt.is_none(), "a refusal opens no prompt");
// The server answered "nothing here".
arm(&mut app);
assert!(app.apply_prepare_rename_verdict(verdict(None, None, false)));
assert_eq!(app.status, "Nothing renameable at the cursor");
assert!(app.prompt.is_none());
// No prepare support: the word-under-cursor fallback.
arm(&mut app);
assert!(app.apply_prepare_rename_verdict(verdict(None, None, true)));
assert_eq!(
app.prompt.as_ref().expect("fallback prompt opened").buffer,
"value"
);
// The buffer moved under the in-flight request: say so rather than
// leaving "Preparing rename…" wedged on screen forever.
arm(&mut app);
app.editor.edit_seq += 1;
assert!(app.apply_prepare_rename_verdict(verdict(
Some(((1, 8, 1, 13), Some(String::from("renamed")))),
None,
false
)));
assert_eq!(app.status, "Rename cancelled");
assert!(app.prompt.is_none(), "a stale verdict opens no prompt");
// A superseded reply must not disarm the newer in-flight request.
arm(&mut app);
let stale = PrepareRenameResult {
request_id: 3,
path: path.clone(),
unsupported: false,
error: None,
target: None,
};
assert!(!app.apply_prepare_rename_verdict(stale));
assert!(
app.prepare_rename_request.is_some(),
"the armed request survives an older reply"
);
}
#[test]
fn a_multi_line_validated_range_falls_back_to_the_word_prompt() {
// The server may validate a span crossing lines; there is no single-line
// text to pre-fill from, so the word-under-cursor fallback takes over
// rather than opening a prompt with an empty buffer.
use crate::lsp::manager::PrepareRenameResult;
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("lib.rs");
std::fs::write(&path, "fn main() {\n let value = 1;\n}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&path).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 1;
app.editor.cursor_col = 9; // inside `value`
app.prepare_rename_request = Some((4, path.clone(), 1, 9, app.editor.edit_seq));
assert!(app.apply_prepare_rename_verdict(PrepareRenameResult {
request_id: 4,
path: path.clone(),
unsupported: false,
error: None,
target: Some(((1, 8, 2, 4), None)),
}));
assert_eq!(
app.prompt.as_ref().expect("fallback prompt opened").buffer,
"value",
"a cross-line range yields no pre-fill text, so the fallback runs"
);
}
#[test]
fn a_cancelled_rename_disarms_the_in_flight_prepare_request() {
// Esc on the prompt abandons the caret. A verdict landing afterwards must
// not reopen the prompt — it would carry the stale (row, col) into the
// rename request and rename the wrong symbol.
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("lib.rs");
std::fs::write(&path, "fn main() {\n let value = 1;\n}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&path).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 1;
app.editor.cursor_col = 9;
app.start_rename_symbol();
assert!(
app.prepare_rename_request.is_some(),
"the request is armed while it is in flight"
);
app.prompt = Some(Prompt {
label: String::from("Rename Symbol 'value'"),
buffer: String::from("value"),
kind: PromptKind::RenameSymbol {
path: path.clone(),
row: 1,
col: 9,
},
target_dir: std::path::PathBuf::new(),
error: None,
});
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(app.prompt.is_none(), "Esc closes the prompt");
assert!(
app.prepare_rename_request.is_none(),
"and disarms the in-flight prepare so a late verdict cannot reopen it"
);
}
#[test]
fn format_selection_needs_a_selection_and_reports_unsupported_via_the_reply() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("lib.rs"), "fn main( ) {\n}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&tmp.path().join("lib.rs")).unwrap();
app.focus_pane(Pane::Editor);
// No selection: refused up front with guidance.
app.run_command(crate::widgets::command_palette::Command::FormatSelection);
assert_eq!(app.status, "Select something to format");
// With a selection: the request fires; with no server spawned in
// tests, the worker's always-answer contract reports unsupported
// through the SAME drain as whole-document formatting, with
// selection-specific wording.
app.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: (0, 0),
head: (1, 1),
});
app.run_command(crate::widgets::command_palette::Command::FormatSelection);
assert_eq!(app.status, "Formatting selection");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while app.format_request_id.is_some() && std::time::Instant::now() < deadline {
app.drain_lsp_format();
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert_eq!(app.status, "No range formatter available for this file");
}
#[test]
fn linked_editing_set_clears_when_the_caret_leaves_and_mirrors_through_handle_key() {
// #254 item 3: keystrokes inside a linked range mirror to the pair
// on the tick; moving the caret out of every range drops the set.
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("page.html"), "<title>t</title>\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor
.open_pinned(&tmp.path().join("page.html"))
.unwrap();
app.focus_pane(Pane::Editor);
app.editor
.set_linked_ranges(&[(0, 1, 0, 6), (0, 10, 0, 15)]);
app.editor.cursor_row = 0;
app.editor.cursor_col = 6;
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
assert!(app.tick_linked_editing(), "the keystroke mirrored");
assert_eq!(app.editor.lines[0], "<titles>t</titles>");
// Caret leaves the set: the next tick clears it.
app.editor.cursor_row = 0;
app.editor.cursor_col = 9; // inside the body text
app.tick_linked_editing();
assert!(!app.editor.has_linked_ranges());
// Typing there no longer mirrors.
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert!(!app.tick_linked_editing());
assert_eq!(app.editor.lines[0], "<titles>tx</titles>");
}
#[test]
fn fold_all_regions_command_works_with_no_language_server_attached() {
// #254's fallback criterion: region folding must work when no LSP
// ever answers — here the file's language has no server at all.
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("notes.txt"),
"#region setup\nline a\nline b\n#endregion\nrest\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor
.open_pinned(&tmp.path().join("notes.txt"))
.unwrap();
app.focus_pane(Pane::Editor);
app.run_command(crate::widgets::command_palette::Command::FoldAllRegions);
assert!(app.editor.is_line_hidden(1) && app.editor.is_line_hidden(2));
assert!(!app.editor.is_line_hidden(0) && !app.editor.is_line_hidden(4));
app.run_command(crate::widgets::command_palette::Command::UnfoldAllRegions);
assert!(!app.editor.is_line_hidden(1), "regions expanded again");
}
#[test]
fn expand_selection_falls_back_to_tree_sitter_when_the_lsp_cannot_route() {
// #254 item 2's serverless criterion, end to end: the worker answers
// `unsupported` for an untracked doc, and the drained verdict grows
// the selection from tree-sitter node ancestry — the gesture never
// hangs and never needs a real server.
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("lib.rs"),
"fn main() {\n let value = 1;\n}\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&tmp.path().join("lib.rs")).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 1;
app.editor.cursor_col = 9; // inside `value`
app.run_command(crate::widgets::command_palette::Command::ExpandSelection);
// The request is in flight; the worker's unsupported verdict lands
// asynchronously. Drain until it resolves the queued press.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while app.editor.selection.is_none() && std::time::Instant::now() < deadline {
app.drain_lsp_selection_ranges();
std::thread::sleep(std::time::Duration::from_millis(20));
}
let sel = app
.editor
.selection
.expect("the fallback grew a selection")
.normalised();
assert!(
sel.0 <= (1, 8) && sel.1 >= (1, 13),
"the identifier (or an enclosing node) is selected: {sel:?}"
);
// Shrink retraces locally, no LSP involved.
app.run_command(crate::widgets::command_palette::Command::ShrinkSelection);
assert!(app.editor.selection.is_none(), "back to the bare caret");
}
#[test]
fn a_caret_move_between_selection_range_request_and_reply_drops_the_stale_chains() {
// #272 review: a click moves the caret WITHOUT bumping edit_seq, so
// the pending gate must also compare the cursor positions the
// request was fired for — the old caret's chains must not apply at
// the new spot.
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("lib.rs"),
"fn main() {\n let value = 1;\n}\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&tmp.path().join("lib.rs")).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 1;
app.editor.cursor_col = 9;
app.run_command(crate::widgets::command_palette::Command::ExpandSelection);
assert!(app.selection_range_request.is_some(), "request in flight");
// A caret move (no edit) before the reply lands.
app.editor.clear_selection();
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while app.selection_range_request.is_some() && std::time::Instant::now() < deadline {
app.drain_lsp_selection_ranges();
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert!(
app.selection_range_request.is_none(),
"the stale reply cleared the pending slot"
);
assert!(
app.editor.selection.is_none(),
"the old caret's chains were dropped, not applied at the new caret"
);
}
#[test]
fn change_color_presentation_needs_a_color_and_defers_the_picker_on_the_reply() {
use crate::lsp::manager::ColorItem;
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("style.css"), "a { color: #ff0000; }\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor
.open_pinned(&tmp.path().join("style.css"))
.unwrap();
app.focus_pane(Pane::Editor);
// No color at the cursor: refused up front.
app.editor.cursor_row = 0;
app.editor.cursor_col = 2;
app.run_command(crate::widgets::command_palette::Command::ChangeColorPresentation);
assert_eq!(app.status, "No color value at the cursor");
// Inject a color set (as a documentColor reply would) and ask on it.
let path = tmp.path().join("style.css");
app.editor.apply_document_colors(
path.clone(),
vec![ColorItem {
line: 0,
character: 11,
end_line: 0,
end_character: 18,
red: 255,
green: 0,
blue: 0,
raw: (1.0, 0.0, 0.0, 1.0),
}],
);
app.editor.cursor_row = 0;
app.editor.cursor_col = 12;
app.run_command(crate::widgets::command_palette::Command::ChangeColorPresentation);
assert_eq!(app.status, "Fetching color presentations…");
// No server in tests: the worker's always-answer contract resolves
// the deferred picker to the empty-offering status.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while app.color_presentations_request.is_some() && std::time::Instant::now() < deadline {
app.drain_lsp_color_presentations();
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert_eq!(app.status, "No color presentations offered here");
}
#[test]
fn a_stale_color_presentation_pick_is_refused_after_a_buffer_change() {
use crate::widgets::editor::TextSpanEdit;
use crate::widgets::list_picker::{ListPicker, ListPurpose, ListRow};
// #277 review: an external reload while the picker is open bumps
// edit_seq; the pick must refuse rather than splice stale offsets.
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("style.css"), "a { color: #ff0000; }\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let path = tmp.path().join("style.css");
app.editor.open_pinned(&path).unwrap();
app.focus_pane(Pane::Editor);
app.pending_color_presentations = vec![(
String::from("rgb(255, 0, 0)"),
vec![TextSpanEdit {
start: (0, 11),
end: (0, 18),
new_text: String::from("rgb(255, 0, 0)"),
utf16: false,
}],
)];
app.pending_color_context = Some((path.clone(), app.editor.edit_seq));
app.open_list_picker(
ListPicker::new(
ListPurpose::ColorPresentation,
"Change Color Presentation",
vec![ListRow {
id: String::from("0"),
label: String::from("rgb(255, 0, 0)"),
}],
),
"empty",
);
// The buffer changes while the picker is open.
app.editor.insert_char('x');
let before = app.editor.lines[0].clone();
app.confirm_list_picker();
assert_eq!(app.editor.lines[0], before, "no stale edit applied");
assert_eq!(
app.status,
"The buffer changed — re-run Change Color Presentation"
);
assert!(app.pending_color_presentations.is_empty());
}
#[test]
fn a_custom_matcher_from_matchers_json_feeds_problems() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.matchers = std::sync::Arc::new(crate::problem_matchers::MatcherSet::from_json(
r##"[ { "name": "mylint",
"pattern": "^(?P<file>\\S+):(?P<line>\\d+):(?P<col>\\d+) (?P<severity>\\w+) (?P<message>.+)$",
"severity_map": { "E": "error" },
"applies_to": "mylint*" } ]"##,
));
let cwd = tmp.path().join("proj");
std::fs::create_dir(&cwd).unwrap();
let out = "src/a.py:12:5 E undefined name 'x'\n";
assert!(app.apply_build_scan(0, Some(&cwd), "mylint src/", out));
let groups = app.problems.groups().to_vec();
let g = groups
.iter()
.find(|g| g.path == cwd.join("src/a.py"))
.expect("the custom matcher's file must group in PROBLEMS");
assert_eq!(g.items.len(), 1);
assert_eq!(g.items[0].source, "mylint");
assert_eq!(
g.items[0].severity,
crate::lsp::manager::DiagnosticSeverity::Error,
"severity_map turns E into an error"
);
assert_eq!((g.items[0].line, g.items[0].col), (11, 4));
// The applies_to glob keeps the matcher off other commands: the same
// output under `cargo build` matches nothing, clearing the pane.
assert!(app.apply_build_scan(0, Some(&cwd), "cargo build", out));
assert!(app.problems.groups().is_empty(), "non-matching command");
}
#[test]
fn a_task_problem_matcher_owns_its_pane_and_watch_publishes_win() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let cwd = tmp.path().join("proj");
std::fs::create_dir(&cwd).unwrap();
// A tasks.json "$gcc" matcher is exclusive for its pane: gcc-shaped
// rows report, the tsc-shaped line in the same output does not
// (VS Code's model — an explicit matcher replaces the defaults).
let gcc = std::sync::Arc::new(crate::problem_matchers::well_known("$gcc").unwrap());
app.assign_task_matcher(7, Some(gcc));
let out = "main.c:7:3: error: expected ';'\nsrc/app.ts(4,10): error TS2322: nope\n";
assert!(app.apply_build_scan(7, Some(&cwd), "make", out));
let groups = app.problems.groups().to_vec();
assert_eq!(groups.len(), 1, "{groups:?}");
assert!(groups[0].path.ends_with("main.c"));
// A watch publish replaces the pane's batch wholesale — and the
// watcher's own exit (a FinishedCommand rescan over its whole
// history) must not resurrect old cycles: that one scan is skipped.
assert!(app.install_build_diags(7, Some(&cwd), Vec::new()));
assert!(app.problems.groups().is_empty(), "empty batch clears");
app.watch_published_panes.insert(7);
assert!(
!app.apply_build_scan(7, Some(&cwd), "tsc --watch", out),
"the post-watch rescan is skipped"
);
// One skip only: the pane's next ordinary command scans normally.
assert!(app.apply_build_scan(7, Some(&cwd), "make", "main.c:1:1: error: x\n"));
assert_eq!(app.problems.groups().len(), 1);
// Clearing the assignment restores the built-in first-match scan.
app.assign_task_matcher(7, None);
assert!(app.apply_build_scan(7, Some(&cwd), "make", out));
assert_eq!(
app.problems.groups().len(),
2,
"without the task matcher both formats report"
);
}
#[test]
fn ctrl_click_follows_a_document_link_before_go_to_definition() {
use crate::lsp::manager::DocumentLinkItem;
// #254 item 8: a file:// link opens the target in the editor; the
// definition request is never fired for a linked range.
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.rs"), "// link here\n").unwrap();
std::fs::write(tmp.path().join("b.rs"), "fn target() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
app.focus_pane(Pane::Editor);
let target = lsp_types::Url::from_file_path(tmp.path().join("b.rs")).unwrap();
app.editor.apply_document_links(
tmp.path().join("a.rs"),
vec![DocumentLinkItem {
line: 0,
character: 3,
end_line: 0,
end_character: 12,
target: target.to_string(),
}],
);
app.open_document_link(target.as_ref());
assert_eq!(
app.editor.path.as_deref().and_then(|p| p.file_name()),
Some(std::ffi::OsStr::new("b.rs")),
"the file link opened in the editor"
);
// And the editor-side lookup that the click dispatch consults.
app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
app.editor.apply_document_links(
tmp.path().join("a.rs"),
vec![DocumentLinkItem {
line: 0,
character: 3,
end_line: 0,
end_character: 12,
target: String::from("https://example.com"),
}],
);
assert_eq!(
app.editor.document_link_at(0, 5),
Some("https://example.com")
);
}
#[test]
fn the_bound_go_to_definition_follows_a_document_link_like_the_builtin() {
use crate::lsp::manager::DocumentLinkItem;
// A bound gesture is meant to be able to REPLACE the built-in it mirrors,
// so it must keep the built-in's #254 precedence: a server-resolved
// document link outranks Go to Definition at that spot, because a URL in
// a comment has no definition at all. `trigger_definition_at` checks the
// link first; the bound command jumped straight to the LSP request, so
// rebinding ctrl+click silently regressed link-following.
//
// Observable is a file:// link, which opens the target in the editor --
// fully inert. A web link would reach `open_url` and launch a browser.
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.rs"), "// link here\n").unwrap();
std::fs::write(tmp.path().join("b.rs"), "fn target() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
app.focus_pane(Pane::Editor);
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let target = lsp_types::Url::from_file_path(tmp.path().join("b.rs")).unwrap();
app.editor.apply_document_links(
tmp.path().join("a.rs"),
vec![DocumentLinkItem {
line: 0,
character: 3,
end_line: 0,
end_character: 12,
target: target.to_string(),
}],
);
let area = app.editor.last_inner;
assert!(area.width > 6 && area.height > 1, "editor must be laid out");
// Text starts past the line-number gutter: `buffer_pos_at` computes
// `last_inner.x + last_gutter_width + 1`, so a column measured from
// `area.x` alone lands in the gutter and resolves to the wrong char.
let text_x = area.x + app.editor.last_gutter_width + 1;
let (col, row) = (text_x + 5, area.y);
assert!(
app.editor.buffer_pos_at(col, row).is_some(),
"the click must resolve to a buffer position, or nothing downstream runs"
);
let (bl, bc) = app.editor.buffer_pos_at(col, row).unwrap();
assert_eq!(
app.editor.document_link_at(bl, bc),
Some(target.as_str()),
"the clicked cell must sit INSIDE the link range, or this test cannot \
tell link-following from its absence"
);
app.last_mouse_pos = Some((col, row));
app.run_command(crate::widgets::command_palette::Command::MouseGoToDefinitionAtClick);
assert_eq!(
app.editor.path.as_deref().and_then(|p| p.file_name()),
Some(std::ffi::OsStr::new("b.rs")),
"the bound Go to Definition must follow the document link first, as \
`trigger_definition_at` does -- a bound gesture that drops the \
built-in's link precedence is not a replacement for it"
);
}
#[test]
fn the_bound_open_link_works_in_the_editor_not_only_the_terminal() {
use crate::lsp::manager::DocumentLinkItem;
// `editor` is the DEFAULT `when` region per docs/KEYBINDINGS.md, so the
// most natural binding a user writes for this command lands there. It
// consulted only the terminal grid (`terminal_url_click` ->
// `terminal_file_click`), both of which hit-test `last_inner` of the
// TERMINAL, so an editor click could never resolve: it reported
// "No link there" over a link that was there.
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.rs"), "// link here\n").unwrap();
std::fs::write(tmp.path().join("b.rs"), "fn target() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
app.focus_pane(Pane::Editor);
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let target = lsp_types::Url::from_file_path(tmp.path().join("b.rs")).unwrap();
app.editor.apply_document_links(
tmp.path().join("a.rs"),
vec![DocumentLinkItem {
line: 0,
character: 3,
end_line: 0,
end_character: 12,
target: target.to_string(),
}],
);
let area = app.editor.last_inner;
assert!(area.width > 6 && area.height > 1, "editor must be laid out");
// Text starts past the line-number gutter: `buffer_pos_at` computes
// `last_inner.x + last_gutter_width + 1`, so a column measured from
// `area.x` alone lands in the gutter and resolves to the wrong char.
let text_x = area.x + app.editor.last_gutter_width + 1;
let (col, row) = (text_x + 5, area.y);
let (bl, bc) = app
.editor
.buffer_pos_at(col, row)
.expect("the click must resolve to a buffer position");
assert_eq!(
app.editor.document_link_at(bl, bc),
Some(target.as_str()),
"the clicked cell must sit inside the link range, or a failure here \
would mean 'no link' rather than 'the command ignored the editor'"
);
app.last_mouse_pos = Some((col, row));
app.run_command(crate::widgets::command_palette::Command::MouseOpenLinkAtClick);
assert_eq!(
app.editor.path.as_deref().and_then(|p| p.file_name()),
Some(std::ffi::OsStr::new("b.rs")),
"Open Link at Click must follow an editor document link. It consulted \
only the terminal, so in the DEFAULT `editor` region it was a \
permanent no-op that reported {:?}",
app.status
);
}
#[test]
fn on_type_formatting_stays_inert_when_disabled_or_unadvertised() {
// #254 item 4: gated behind editor.format_on_type (default OFF,
// matching VS Code), and even when on, nothing fires unless a
// server advertised the trigger set for the language.
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("lib.rs"), "fn main() {\n}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&tmp.path().join("lib.rs")).unwrap();
app.focus_pane(Pane::Editor);
assert!(!app.format_on_type, "off by default");
app.editor.cursor_row = 1;
app.editor.cursor_col = 0;
app.handle_key(key(KeyCode::Char(';'), KeyModifiers::NONE))
.unwrap();
app.tick_on_type_formatting();
assert!(app.on_type_request.is_none(), "disabled: nothing fires");
assert!(
app.editor.last_typed.is_none(),
"the tick consumes the record even while disabled, so enabling \
the setting later cannot replay a stale trigger"
);
// Enable via the settings toggle; still inert because no server has
// advertised any trigger characters for Rust in this test.
app.toggle_format_on_type();
assert!(app.format_on_type);
assert_eq!(app.status, "Format on Type: on");
app.handle_key(key(KeyCode::Char(';'), KeyModifiers::NONE))
.unwrap();
app.tick_on_type_formatting();
assert!(
app.on_type_request.is_none(),
"no advertised trigger set: the request is never sent"
);
assert!(
app.editor.last_typed.is_none(),
"each keystroke is examined exactly once"
);
}
#[test]
fn a_tab_switch_disarms_the_background_tabs_on_type_trigger() {
// A keystroke and a tab switch can drain in the same input burst, so
// the tick can run with a different tab active than the one that
// typed. The record on the now-background tab must be swept, or
// returning to it minutes later would fire a request for a long-dead
// keystroke — its per-tab edit_seq still matches, nothing having been
// edited in between.
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.rs"), "fn a() {\n}\n").unwrap();
std::fs::write(tmp.path().join("b.rs"), "fn b() {\n}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 1;
app.editor.cursor_col = 0;
app.handle_key(key(KeyCode::Char(';'), KeyModifiers::NONE))
.unwrap();
assert!(
app.editor.last_typed.is_some(),
"keystroke recorded on tab A"
);
// Switch to tab B before any tick runs, then tick with B active.
app.editor.open_pinned(&tmp.path().join("b.rs")).unwrap();
app.tick_on_type_formatting();
// Return to tab A: the armed record must be gone.
app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
assert!(
app.editor.last_typed.is_none(),
"the sweep disarms background tabs — returning to one must not \
replay the pre-switch keystroke"
);
// Same hazard one level out: the typing tab is in a split group that
// loses focus before the tick runs.
app.handle_key(key(KeyCode::Char(';'), KeyModifiers::NONE))
.unwrap();
assert!(app.editor.last_typed.is_some(), "keystroke recorded again");
app.split_editor_dir(editor_layout::SplitDir::Horizontal, true);
assert_eq!(app.editor_layout.leaf_count(), 2, "really split");
app.tick_on_type_formatting();
let armed = app
.editor_layout
.inactive_groups_mut()
.iter()
.any(|g| g.editors.iter().any(|e| e.last_typed.is_some()));
assert!(
!armed,
"the sweep reaches editors in inactive split groups too"
);
}
#[test]
fn a_settings_reload_applies_format_on_type_live() {
// The live-reload path (save a config file inside croft →
// remerge_settings → apply_merged_settings) must carry the key like
// every other allowlisted preference; startup-only application would
// leave the Settings row showing a provenance whose value is not in
// force until the next launch.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(!app.format_on_type, "off by default");
let p = crate::prefs::Prefs {
format_on_type: true,
..Default::default()
};
app.apply_merged_settings(&p);
assert!(app.format_on_type, "a reloaded merge turns it on");
app.apply_merged_settings(&crate::prefs::Prefs::default());
assert!(!app.format_on_type, "and back off");
}
#[test]
fn an_on_type_reply_applies_only_while_its_buffer_and_tab_are_unmoved() {
// The four dispositions of a reply. The channel's sender lives in the
// LSP worker, so the decision is tested through the pure helper the
// drain loop delegates to.
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.rs");
let b = tmp.path().join("b.rs");
std::fs::write(&a, "fn a() {\n}\n").unwrap();
std::fs::write(&b, "fn b() {\n}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.focus_pane(Pane::Editor);
let reply = |id: u64, path: &std::path::Path| crate::lsp::manager::FormatResult {
request_id: id,
path: path.to_path_buf(),
edits: Some(Vec::new()),
unsupported: false,
};
// Nothing armed: any reply is a leftover.
assert_eq!(
app.on_type_reply_disposition(&reply(1, &a)),
OnTypeReply::NotOurs
);
// Armed and everything matches.
app.on_type_request = Some((7, app.editor.edit_seq, a.clone()));
assert_eq!(
app.on_type_reply_disposition(&reply(7, &a)),
OnTypeReply::Apply
);
// A superseded id must NOT disarm the newer in-flight request.
assert_eq!(
app.on_type_reply_disposition(&reply(6, &a)),
OnTypeReply::NotOurs,
"an older reply is ignored without consuming the armed request"
);
assert!(
app.on_type_request.is_some(),
"the helper never clears; the newer request stays armed"
);
// Buffer moved since the request.
app.on_type_request = Some((7, app.editor.edit_seq.wrapping_sub(1), a.clone()));
assert_eq!(
app.on_type_reply_disposition(&reply(7, &a)),
OnTypeReply::Stale,
"edits computed against text that has since changed are dropped"
);
// Reply is for a different file than the one requested.
app.on_type_request = Some((7, app.editor.edit_seq, a.clone()));
assert_eq!(
app.on_type_reply_disposition(&reply(7, &b)),
OnTypeReply::Stale,
"a reply for another path never applies to this tab"
);
// The requested tab is no longer active: edit_seq is per-tab, so the
// counter alone would compare two unrelated buffers.
app.editor.open_pinned(&b).unwrap();
app.on_type_request = Some((7, app.editor.edit_seq, a.clone()));
assert_eq!(
app.on_type_reply_disposition(&reply(7, &a)),
OnTypeReply::Stale,
"the tab that typed must still be the active one"
);
}
#[test]
fn a_document_link_refuses_a_non_web_scheme_and_records_nav_history() {
use crate::lsp::manager::DocumentLinkItem;
// The target comes from a language server and the text it decorates says
// nothing about where it points, so anything but file://, http and https
// is refused rather than handed to the system opener — the same rule
// `open_detected_url` applies to terminal OSC 8 links.
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("a.rs"),
"// link here
",
)
.unwrap();
std::fs::write(
tmp.path().join("b.rs"),
"fn target() {}
",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
app.focus_pane(Pane::Editor);
for hostile in [
"vscode://file/etc/passwd",
"VSCode://file/etc/passwd",
"cursor://file/etc/passwd",
"javascript:alert(1)",
"mailto:a@b.c",
"ssh://host/x",
" HTTP-ish-but-not://x",
] {
app.open_document_link(hostile);
assert!(
app.status.starts_with("Refused to open non-web link:"),
"{hostile} must be refused, got {:?}",
app.status
);
}
// A control character never belongs in a URI, and the relay's own
// validator rejects one; refuse before anything downstream sees it.
for malformed in [
"https://example.com\nopen\tevil",
"https://exa\u{0}mple.com",
// The check runs before the branch, so a file:// target carrying one
// is refused too rather than reaching Url::parse.
"file:///etc/hosts\nopen\tevil",
] {
app.open_document_link(malformed);
assert!(
app.status.starts_with("Refused to open malformed link:"),
"{malformed:?} must be refused, got {:?}",
app.status
);
}
// A file:// link still opens, and records where the user was so Back
// returns to it.
app.editor.cursor_row = 0;
app.editor.cursor_col = 4;
let target = lsp_types::Url::from_file_path(tmp.path().join("b.rs")).unwrap();
app.editor.apply_document_links(
tmp.path().join("a.rs"),
vec![DocumentLinkItem {
line: 0,
character: 3,
end_line: 0,
end_character: 12,
target: target.to_string(),
}],
);
app.open_document_link(target.as_ref());
assert_eq!(
app.editor.path.as_deref().and_then(|p| p.file_name()),
Some(std::ffi::OsStr::new("b.rs")),
"the file link opened"
);
let back = app
.nav
.back(None)
.expect("the jump recorded a Back location, like go-to-definition");
assert_eq!(
back.path.file_name(),
Some(std::ffi::OsStr::new("a.rs")),
"Back returns to the file the link was clicked in"
);
assert_eq!((back.row, back.col), (0, 4), "and to the click's caret");
// URI schemes are case-insensitive (RFC 3986) and `file_ref` already
// matches them that way; a server spelling it `FILE://` must open, not
// fall through to the web guard and get refused.
app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
let upper = target.as_ref().replacen("file://", "FILE://", 1);
app.open_document_link(&upper);
assert_eq!(
app.editor.path.as_deref().and_then(|p| p.file_name()),
Some(std::ffi::OsStr::new("b.rs")),
"an upper-case file scheme still opens in the editor"
);
// Surrounding whitespace is trimmed rather than smuggled downstream.
app.editor.open_pinned(&tmp.path().join("a.rs")).unwrap();
app.open_document_link(&format!(" {} ", target.as_ref()));
assert_eq!(
app.editor.path.as_deref().and_then(|p| p.file_name()),
Some(std::ffi::OsStr::new("b.rs")),
"a padded target is normalised, not refused"
);
}
#[test]
fn editing_drops_stale_document_links() {
use crate::lsp::manager::DocumentLinkItem;
// Link ranges are measured against the text the server saw; an edit
// shifts them, so a Ctrl+click would otherwise follow the wrong span
// until the next batch lands.
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("a.rs");
std::fs::write(
&path,
"// link here
",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&path).unwrap();
app.focus_pane(Pane::Editor);
app.editor.apply_document_links(
path.clone(),
vec![DocumentLinkItem {
line: 0,
character: 3,
end_line: 0,
end_character: 12,
target: String::from("https://example.com"),
}],
);
assert_eq!(
app.editor.document_link_at(0, 5),
Some("https://example.com"),
"the link is live before the edit"
);
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
app.editor.insert_char('x');
assert_eq!(
app.editor.document_link_at(0, 5),
None,
"the edit dropped the stale ranges"
);
}
/// #249: after a restart the panes came back in the right directories with
/// the right names — and completely BLANK, which is what the report means by
/// "opens all old terminals empty". The pane's own output is now carried in
/// the session store and repainted above the fresh prompt.
///
/// A real panel (two panes) is used deliberately: a lone unnamed pane at the
/// workspace root is still pruned as the default layout, so that the store
/// does not grow for every directory a shell was ever run in.
#[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();
// Pin an explicit geometry so the assertions below do not depend on the
// spawn default. (A pane is born 80x24, so this is not waking a
// zero-column grid — an earlier comment here claimed that and was wrong.)
app.terminals[0].resize(80, 24);
// Put a recognisable line on the pane, as the child would have printed.
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}"
);
// A fresh app restores the panel; the marker must be on screen.
let mut app2 = App::new(tmp.path().to_path_buf()).unwrap();
app2.terminal_session_path = session_path.clone();
app2.restore_terminal_session();
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:?}"
);
}
/// #298 review: the restored output must sit ABOVE the new shell's prompt.
/// Asserting only that the marker is somewhere on screen passes whether the
/// transcript landed above the prompt, below it, or interleaved — which is
/// exactly what the replay-after-spawn race produced. Painting the preamble
/// before the reader thread starts is what makes the ordering deterministic.
#[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();
// The preamble is in the grid before the child can write a byte, so the
// rows are readable immediately — no waiting on the shell.
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:?}"
);
// Whatever the shell prints lands on a later row than the restored text.
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:?}"
);
}
/// #298 review: a full-screen program's frame is not scrollback. Quitting
/// with vim or htop open used to persist that frame and replay it as inert
/// text above the next prompt — the alternate screen exists precisely so its
/// contents vanish on exit.
#[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);
// Real scrollback first, then a full-screen program takes over.
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}"
);
}
/// The window keeps the NEWEST lines. An inverted slice would still be
/// bounded and still look right in a small test, so pin the direction.
#[test]
fn the_transcript_window_keeps_the_newest_lines() {
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);
let n = crate::terminal_session::TRANSCRIPT_LINES + 50;
for i in 1..=n {
app.terminals[0].feed_bytes_for_test(format!("line-{i}\r\n").as_bytes());
}
app.save_terminal_session();
// The store is keyed by workspace root; read it back through the module's
// own loader rather than reparsing its shape here.
let store = crate::terminal_session::load(&session_path);
let rec = store
.values()
.next()
.expect("a session record for this workspace");
let t = &rec.panes[0].transcript;
assert!(
t.len() <= crate::terminal_session::TRANSCRIPT_LINES,
"bounded to the window: {}",
t.len()
);
let joined = t.join("\n");
assert!(
joined.contains(&format!("line-{n}")),
"the newest line survives"
);
assert!(
!joined.contains("line-1\n") && !joined.ends_with("line-1"),
"the oldest line was dropped, not the newest"
);
}
/// A store written before transcripts existed must still load: `serde(default)`
/// is the mechanism, and nothing else pins it.
#[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());
}
/// The transcript is plain text by design: a replay must not be able to
/// re-run a cursor move or a screen clear that the original output carried.
#[test]
fn a_replayed_transcript_cannot_execute_control_sequences() {
let tmp = tempfile::tempdir().unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
// A hostile line: were this fed raw, the erase would wipe the screen and
// the cursor move would scramble the layout.
app.terminals[0].replay_transcript(&[String::from("before\u{1b}[2J\u{1b}[Hafter")]);
let (lines, _) = app.terminals[0].grid_lines();
let joined = lines.join("\n");
assert!(
joined.contains("before") && joined.contains("after"),
"the text survives: {joined:?}"
);
assert!(
!joined.contains('\u{1b}'),
"and no escape byte reaches the grid: {joined:?}"
);
}
/// #260: with auto-hide on, moving focus to the editor collapses the sidebar,
/// and a deliberate sidebar action brings it back and HOLDS it — the reveal
/// must not be undone by the focus change it performs itself.
#[test]
fn auto_hide_collapses_on_editor_focus_and_deliberate_actions_restore_it() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.rs"), "fn main() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = true;
// #302: the collapse is now delivered by the dwell tick rather than by the
// focus move itself. What this test protects — that focusing the editor
// DOES collapse, and that deliberate sidebar actions bring it back and
// hold it — is unchanged; only the moment of the collapse moved.
app.focus_pane(Pane::Editor);
assert!(
app.tick_sidebar_auto_hide_at(
std::time::Instant::now() + crate::app::sidebar_dwell::AUTO_HIDE_DWELL
),
"the grace delay elapses and the collapse fires"
);
assert!(!app.show_tree, "focusing the editor collapses the sidebar");
// An activity-bar view switch is a deliberate sidebar action: it reveals
// the sidebar AND lands focus there, so the pin it takes is released by
// that same focus move — the sidebar stays open because focus is in it,
// not because it is pinned.
app.set_sidebar_view(SidebarView::Search);
assert!(app.show_tree, "choosing a view reveals the sidebar");
assert!(app.focus == Pane::Tree, "and puts focus in it");
assert!(
!app.sidebar_pinned_open,
"focus landed in the sidebar, so the pin has done its job"
);
// Leaving again collapses.
app.focus_pane(Pane::Editor);
assert!(
app.tick_sidebar_auto_hide_at(
std::time::Instant::now() + crate::app::sidebar_dwell::AUTO_HIDE_DWELL
),
"the collapse fires after the delay"
);
assert!(!app.show_tree, "leaving collapses it again");
// Terminal focus collapses too, not just the editor.
app.set_sidebar_view(SidebarView::Explorer);
app.focus_pane(Pane::Tree);
app.focus_pane(Pane::Terminal);
assert!(
app.tick_sidebar_auto_hide_at(
std::time::Instant::now() + crate::app::sidebar_dwell::AUTO_HIDE_DWELL
),
"and for a terminal too"
);
assert!(!app.show_tree, "a terminal is also 'not the sidebar'");
}
/// The flapping cases from #260: a seam drag, an open prompt or menu, and Zen
/// Mode must all suppress the collapse. Each is a state where the sidebar is
/// either being manipulated or deliberately borrowed.
#[test]
fn auto_hide_is_suppressed_while_dragging_prompting_or_in_zen_mode() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
// Baseline: it would collapse.
app.show_tree = true;
assert!(app.sidebar_auto_hide_allowed());
// Mid seam-drag the pointer is over the editor by definition; collapsing
// under the cursor is exactly the flapping the issue calls out.
app.splitter_drag = Some(SplitterDrag::Sidebar);
assert!(!app.sidebar_auto_hide_allowed(), "a drag suppresses it");
app.focus_pane(Pane::Editor);
// Tick past the delay: since #302 defers the collapse, asserting
// `show_tree` right after the focus move is true for any deferring
// implementation and says nothing about the drag suppression.
assert!(
!app.tick_sidebar_auto_hide_at(std::time::Instant::now() + AUTO_HIDE_DWELL),
"the drag suppresses the collapse even once the window elapses"
);
assert!(app.show_tree, "and the sidebar survives the drag");
app.splitter_drag = None;
// Zen Mode already owns chrome visibility and wins, as it does today.
app.zen_mode = true;
assert!(!app.sidebar_auto_hide_allowed(), "zen mode wins");
app.zen_mode = false;
// Off by default: a user who never opted in never loses their sidebar.
app.sidebar_auto_hide = false;
assert!(!app.sidebar_auto_hide_allowed());
app.focus_pane(Pane::Editor);
assert!(app.show_tree, "opt-in only");
}
/// Reveal-in-explorer targets the sidebar, so it must work even when
/// auto-hide has collapsed it — otherwise the command silently does nothing
/// visible.
#[test]
fn reveal_in_explorer_shows_a_collapsed_sidebar() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("a.rs");
std::fs::write(&f, "fn main() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = true;
app.focus_pane(Pane::Editor);
// #302: the collapse arrives on the dwell tick rather than the focus move.
// What this test protects — that a sidebar-targeting command reveals an
// ALREADY-COLLAPSED sidebar — is unchanged; it just has to reach that
// collapsed state the way the app now does.
app.tick_sidebar_auto_hide_at(
std::time::Instant::now() + crate::app::sidebar_dwell::AUTO_HIDE_DWELL,
);
assert!(!app.show_tree, "collapsed first");
app.reveal_in_explorer(f);
assert!(
app.show_tree,
"a sidebar-targeting command reveals the sidebar"
);
}
/// The Customize Layout rows carry hardcoded re-open indices (each toggle
/// reopens the menu with itself selected), so inserting a row in the middle
/// silently mis-selects every row after it. #260's Auto-Hide row is appended
/// after Minimap for that reason; this pins the positions so a future insert
/// fails here rather than in someone's hands.
#[test]
fn customize_layout_toggle_rows_keep_their_reopen_indices() {
let tmp = tempfile::tempdir().unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
let items = app.customize_layout_items();
let label = |i: usize| match &items[i] {
MenuEntry::Item { label, .. } => label.clone(),
_ => panic!("row {i} is not an item"),
};
assert!(label(0).contains("Activity Bar"));
assert!(label(1).contains("Primary Side Bar"));
assert!(label(2).contains("Secondary Side Bar"));
assert!(label(3).contains("Panel"));
assert!(label(4).contains("Status Bar"));
assert!(label(5).contains("Minimap"));
assert!(
label(6).contains("Auto-Hide Side Bar"),
"the new row is appended, not inserted"
);
}
/// #294 review: the palette and menu toggles must not drift. Both funnel
/// through one method, so they set the same state and report the same status;
/// previously the menu route set neither the status nor any persistence.
#[test]
fn both_auto_hide_toggle_routes_agree() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(!app.sidebar_auto_hide, "off by default");
app.toggle_sidebar_auto_hide();
assert!(app.sidebar_auto_hide);
assert!(
app.status.contains("on"),
"the toggle reports its new state: {}",
app.status
);
app.toggle_sidebar_auto_hide();
assert!(!app.sidebar_auto_hide);
assert!(
app.status.contains("off"),
"and reports off: {}",
app.status
);
}
/// #294 re-review found the blocker this pins: the pin was set only on the
/// palette route, while a real Cmd+B keypress is handled earlier and returns
/// before `Cmd` dispatch — so the headline reveal gesture revealed the panel
/// and the very next click into the editor collapsed it again. Driving the
/// key event is the whole point; every other test here sets the flag by hand
/// and so could not see it.
#[test]
fn the_real_cmd_b_keypress_reveals_and_holds_the_sidebar() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = false;
app.handle_key(key(KeyCode::Char('b'), KeyModifiers::SUPER))
.unwrap();
assert!(app.show_tree, "Cmd+B reveals the sidebar");
// #302: each collapse is now delivered by the dwell tick. The guarantee
// under test — that the reveal survives the focus move it performs, and is
// one-shot rather than sticky — is unchanged.
let dwell = crate::app::sidebar_dwell::AUTO_HIDE_DWELL;
app.focus_pane(Pane::Editor);
app.tick_sidebar_auto_hide_at(std::time::Instant::now() + dwell);
assert!(
app.show_tree,
"and the reveal survives the next move to the editor"
);
// Still one-shot: the exemption is spent, so the following move collapses.
app.focus_pane(Pane::Tree);
app.focus_pane(Pane::Editor);
app.tick_sidebar_auto_hide_at(std::time::Instant::now() + dwell);
assert!(!app.show_tree, "the exemption was consumed, not sticky");
// Ctrl+B is the same gesture on the other platform convention.
app.handle_key(key(KeyCode::Char('b'), KeyModifiers::CONTROL))
.unwrap();
assert!(app.show_tree);
app.focus_pane(Pane::Editor);
app.tick_sidebar_auto_hide_at(std::time::Instant::now() + dwell);
assert!(app.show_tree, "Ctrl+B pins exactly as Cmd+B does");
}
/// A pin taken while the feature is OFF must not be banked: it would sit
/// unconsumed and silently eat the first collapse after the user turns
/// auto-hide on, which reads as "the setting did nothing".
#[test]
fn a_reveal_while_auto_hide_is_off_does_not_bank_an_exemption() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = false;
app.show_tree = false;
app.handle_key(key(KeyCode::Char('b'), KeyModifiers::SUPER))
.unwrap();
assert!(app.show_tree);
assert!(
!app.sidebar_pinned_open,
"no pin is banked while the feature is off"
);
app.sidebar_auto_hide = true;
app.focus_pane(Pane::Editor);
// #302: delivered by the tick, not the focus move. The guarantee under
// test — that no exemption was banked while the feature was off, so the
// first collapse after enabling it is not silently eaten — is unchanged.
assert!(
app.tick_sidebar_auto_hide_at(
std::time::Instant::now() + crate::app::sidebar_dwell::AUTO_HIDE_DWELL
),
"the collapse fires"
);
assert!(
!app.show_tree,
"so the first collapse after enabling it actually happens"
);
}
/// #294 review: the reveal exemption is ONE-SHOT. Cmd+B reveals without
/// moving focus, so a sticky flag would never be cleared (focus never lands
/// on the tree) and auto-hide would be silently dead for the session.
///
/// #302 moved WHEN the exemption is spent — from the focus move itself to the
/// collapse the dwell later fires — but not WHETHER it is spent. The
/// one-shot guarantee this test exists to protect is unchanged, so the test
/// keeps its assertions and gains the tick that now delivers the collapse.
#[test]
fn the_reveal_exemption_is_consumed_rather_than_sticky() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = true;
// Cmd+B-style reveal: exempt the next collapse.
app.sidebar_pinned_open = true;
app.focus_pane(Pane::Editor);
let t0 = std::time::Instant::now();
let fired = app.tick_sidebar_auto_hide_at(t0 + crate::app::sidebar_dwell::AUTO_HIDE_DWELL);
assert!(!fired, "the exemption protects this collapse");
assert!(app.show_tree, "so the sidebar is still up");
assert!(
!app.sidebar_pinned_open,
"and is consumed rather than latching auto-hide off"
);
// The very next move collapses, proving the feature re-armed itself.
app.focus_pane(Pane::Editor);
let t1 = std::time::Instant::now();
assert!(
app.tick_sidebar_auto_hide_at(t1 + crate::app::sidebar_dwell::AUTO_HIDE_DWELL),
"auto-hide is live again"
);
assert!(!app.show_tree, "and the sidebar went down");
}
/// #294 review: the suppression list must cover the modal states the codebase
/// already treats as modal — several are sidebar-targeting flows that are
/// their own fields rather than `Prompt`s, so checking `prompt` alone missed
/// exactly the ones the comment claimed were covered.
#[test]
fn auto_hide_yields_to_real_modal_overlays_and_explorer_drags() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = true;
assert!(app.sidebar_auto_hide_allowed(), "baseline collapses");
// A command palette is modal and may sit over sidebar space.
app.command_palette = Some(crate::widgets::command_palette::CommandPalette::new());
assert!(
!app.sidebar_auto_hide_allowed(),
"a modal overlay suppresses the collapse"
);
app.command_palette = None;
// With no activity bar there is no on-screen way back to a collapsed
// sidebar, so a mouse-only user would be stranded.
app.activity_bar_visible = false;
assert!(
!app.sidebar_auto_hide_allowed(),
"no reveal affordance means no auto-hide"
);
app.activity_bar_visible = true;
// A focus move the user did not ask for is not a reason to hide chrome.
// Tick PAST the grace delay: with the collapse deferred (#302), asserting
// `show_tree` right after the focus move is trivially true for any
// implementation that defers, suppressed or not. The suppression is only
// observable once the window has elapsed.
app.without_auto_hide(|a| a.focus_pane(Pane::Editor));
assert!(
!app.tick_sidebar_auto_hide_at(std::time::Instant::now() + AUTO_HIDE_DWELL),
"a programmatic focus move must not collapse, even after the delay"
);
assert!(app.show_tree, "programmatic focus leaves the sidebar alone");
}
/// #302: a click that PASSES THROUGH the panel on its way to the editor must
/// not collapse it under the pointer. #294 collapsed on the focus change
/// itself, so the panel flapped; the collapse now waits out a grace delay, and
/// a return to the sidebar inside that window cancels it outright.
///
/// Written against `focus_pane` and `show_tree` alone, so it fails on the
/// missing BEHAVIOUR rather than on a missing method. The clock-injected
/// assertions live in the tests below.
#[test]
fn a_click_passing_through_the_sidebar_does_not_collapse_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = true;
// Precondition: the collapse must be POSSIBLE, or "it stayed up" passes
// vacuously against a sidebar that could never have gone down.
assert!(
app.sidebar_auto_hide_allowed(),
"precondition: nothing is suppressing auto-hide, so a collapse is live"
);
// Focus crosses into the editor. Under #294 this collapsed immediately;
// under #302 the collapse is only ARMED and the panel is still up.
app.focus_pane(Pane::Editor);
assert!(
app.show_tree,
"the sidebar stays up for the length of the grace delay"
);
// Focus comes back inside the window — the click was passing through.
app.focus_pane(Pane::Tree);
assert!(
app.show_tree,
"a click through the panel leaves it exactly where it was"
);
// Assert the DISARM directly. Ticking alone does not pin it: with focus
// parked on `Pane::Tree` the tick declines via its own `focus == Pane::Tree`
// early return, so this test passes even with the disarm deleted. The
// dwell's own state is the only thing that distinguishes "cancelled" from
// "declined for an unrelated reason".
assert!(
!app.sidebar_dwell.armed(),
"the return to the sidebar cancelled the pending collapse outright"
);
// And nothing fires once the window elapses.
assert!(
!app.tick_sidebar_auto_hide_at(std::time::Instant::now() + AUTO_HIDE_DWELL),
"no collapse after the deadline"
);
assert!(
app.show_tree,
"so the panel is still up after the window closes"
);
}
/// #302: a focus move that stays away must still collapse — the grace delay is
/// a delay, not a reprieve. Public-surface half: after the move the panel is
/// still up but a collapse is PENDING, which `tick_sidebar_auto_hide` will
/// deliver. Timing precision is covered by the unit tests on the timer itself.
#[test]
fn leaving_the_sidebar_arms_a_collapse_rather_than_doing_it_immediately() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = true;
assert!(
app.sidebar_auto_hide_allowed(),
"precondition: a collapse is possible here"
);
app.focus_pane(Pane::Editor);
assert!(app.show_tree, "not collapsed on the focus change itself");
// Several more focus moves land inside the grace window. None of them may
// collapse it, and — the trap the issue names — none may push the
// deadline out either, which the timer's own unit tests pin.
//
// Stamped AFTER the arming move on purpose. `due` is `>=`, so an exact
// deadline would be fine, but a stamp taken BEFORE `focus_pane` is strictly
// earlier than the anchor `focus_pane` records — `armed_at + DWELL` would
// then land before the real deadline and the tick would correctly decline.
// Taken here it is a hair LATER than the anchor, so the tick is genuinely
// due; the re-arming bug this guards against would push the deadline a full
// AUTO_HIDE_DWELL out, far beyond that sub-microsecond slack.
let armed_at = std::time::Instant::now();
app.focus_pane(Pane::Terminal);
app.focus_pane(Pane::Editor);
assert!(app.show_tree, "still up while the window is open");
// The deadline is measured from the FIRST arm, not the last focus move, so
// a tick at the original deadline still fires. Without this the pane hops
// above prove nothing: `show_tree` is set either way before any tick, and
// a re-arming bug that pushed the deadline out would pass unnoticed.
assert!(
app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL),
"the hops did not push the deadline out — it fires on the original one"
);
assert!(!app.show_tree, "and the collapse actually happened");
}
// Sidebar auto-hide tests, a trap worth knowing before you write one: routing
// focus through `Pane::Tree` CLEARS the one-shot reveal pin by design (moving
// into the sidebar means you are using it, so the exemption is released). A
// Tree->Editor round trip is the obvious way to re-arm a collapse, and it
// silently wipes the flag under test. Re-arm via `Pane::Terminal` instead when
// the pin has to survive. This is invisible from the test side and cost one
// misdiagnosed green.
/// #302, the part that is new work rather than a port: #294's one-shot pin is
/// consumed by "the next collapse attempt", but with a timer that stops being
/// a single well-defined event. A deliberate reveal must not lose its
/// protection to an attempt the dwell then CANCELS.
#[test]
fn arming_a_collapse_does_not_consume_the_reveal_pin() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = true;
// Precondition: a collapse is otherwise live here, so the exemption is
// protecting against something real rather than a case that would never
// have fired.
assert!(
app.sidebar_auto_hide_allowed(),
"precondition: without the pin, this focus move would collapse"
);
// A deliberate reveal (Cmd+B) banks the one-shot exemption.
app.sidebar_pinned_open = true;
// Focus leaves: this ARMS a collapse but must not spend the exemption,
// because the collapse has not happened and may yet be cancelled.
app.focus_pane(Pane::Editor);
assert!(
app.sidebar_pinned_open,
"arming a collapse must not spend the exemption — only firing one does"
);
assert!(app.show_tree, "and the sidebar is still up");
}
/// #302: the pin must survive a tick that declines to collapse for a reason
/// that has nothing to do with the pin. Every EARLY decline in
/// `tick_sidebar_auto_hide_at` returns before spending it; the LATE decline —
/// `sidebar_auto_hide_allowed()` being false — sits after the take, so a
/// transient suppression (a seam drag, an open palette, a modal) burns a pin
/// the user never got the benefit of. The suppression clears a moment later
/// and the next collapse proceeds unpinned.
#[test]
fn a_suppressed_tick_does_not_spend_the_reveal_pin() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = true;
// Precondition, checked before either the pin or the suppression is set:
// a collapse is otherwise live here, so both are suppressing something
// real rather than a case that was never going to fire.
assert!(
app.sidebar_auto_hide_allowed(),
"precondition: without pin or drag, this focus move would collapse"
);
// A deliberate reveal (Cmd+B) banks the one-shot exemption.
app.sidebar_pinned_open = true;
// Focus leaves: arms the collapse.
app.focus_pane(Pane::Editor);
// The user starts dragging the sidebar seam. This suppresses the collapse
// on its own — independently of the pin — and is transient: it ends when
// they release the mouse.
app.splitter_drag = Some(SplitterDrag::Sidebar);
// Precondition: the drag alone is enough to stop this collapse, so the
// tick below declines for a reason that is not the pin.
assert!(
!app.sidebar_auto_hide_allowed(),
"precondition: the seam drag suppresses the collapse by itself"
);
let now = std::time::Instant::now();
let collapsed = app.tick_sidebar_auto_hide_at(now + AUTO_HIDE_DWELL);
assert!(!collapsed, "the drag suppressed this collapse");
assert!(app.show_tree, "so the sidebar is still up");
assert!(
app.sidebar_pinned_open,
"a collapse stopped by an unrelated suppression must not spend the \
one-shot exemption — the user never saw the collapse it was banked for"
);
// The pin surviving is only half the contract: it must still be SPENDABLE.
// A fix that keeps the pin by making the collapse permanently unreachable
// satisfies the assertion above and is strictly worse than the bug. So
// release the drag and let the collapse the pin was banked for happen.
//
// Re-arm WITHOUT routing focus through `Pane::Tree`: moving into the
// sidebar deliberately releases the pin (mod.rs, the `Pane::Tree` arm), so
// a Tree->Editor round trip would clear the very flag under test. Focus is
// already on Editor here; the dwell is what needs re-arming.
app.splitter_drag = None;
app.focus_pane(Pane::Terminal);
let pinned_collapse = app.tick_sidebar_auto_hide_at(now + AUTO_HIDE_DWELL * 2);
assert!(!pinned_collapse, "the pin exempts this one");
assert!(app.show_tree, "so the sidebar survives it");
assert!(
!app.sidebar_pinned_open,
"and NOW the exemption is spent — it was banked for exactly this"
);
app.focus_pane(Pane::Editor);
let unpinned_collapse = app.tick_sidebar_auto_hide_at(now + AUTO_HIDE_DWELL * 3);
assert!(
unpinned_collapse,
"with the exemption spent, the next collapse fires — a pin that can \
never be spent is a sidebar that can never auto-hide"
);
assert!(!app.show_tree, "and the sidebar is finally down");
}
/// #302: a reveal under Zen Mode must not bank a pin. No collapse can fire
/// while Zen owns the chrome, so the pin would sit unconsumed and then eat the
/// first legitimate collapse after Zen exits — the exact failure
/// `toggle_side_bar` already guards against when auto-hide is off.
#[test]
fn a_reveal_under_zen_mode_banks_no_pin() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = false;
// Precondition: with Zen off, this same reveal DOES bank a pin — so the
// assertion below is about Zen, not about the reveal failing generally.
app.toggle_side_bar();
assert!(
app.sidebar_pinned_open,
"precondition: a normal reveal banks the one-shot pin"
);
// Back to a hidden sidebar, now under Zen Mode.
app.toggle_side_bar();
app.zen_mode = true;
app.activity_bar_visible = false;
app.toggle_side_bar();
assert!(app.show_tree, "the reveal still shows the sidebar");
assert!(
!app.sidebar_pinned_open,
"but banks no pin: nothing can spend it until Zen exits, and a pin \
held that long eats a collapse the user never connected to it"
);
}
/// #302: a collapse blocked by a TRANSIENT suppression must be retried once
/// that suppression lifts, not abandoned. The tick disarming before it asks
/// `sidebar_auto_hide_allowed()` drops the pending collapse on the floor, and
/// nothing re-arms it but a fresh focus move — so a user whose palette was open
/// during the grace window keeps a sidebar that never auto-hides again.
#[test]
fn a_transiently_suppressed_collapse_is_retried_once_the_suppression_lifts() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = true;
// Precondition: a collapse is genuinely live here.
assert!(
app.sidebar_auto_hide_allowed(),
"precondition: nothing is suppressing auto-hide yet"
);
// NOTE: `maybe_auto_hide_sidebar` stamps the anchor with its OWN
// `Instant::now()`, so a deadline computed from a timestamp taken HERE is
// fractionally too early and the tick declines as not-yet-due — which
// looks exactly like the suppression working. Anchor the deadlines to a
// point comfortably past any real arm instead.
app.focus_pane(Pane::Editor);
let armed_at = std::time::Instant::now();
// A transient suppression appears DURING the grace window.
app.command_palette = Some(crate::widgets::command_palette::CommandPalette::new());
assert!(
!app.sidebar_auto_hide_allowed(),
"precondition: the open palette suppresses the collapse"
);
// The window elapses while it is still open: correctly declines.
// Precondition: the deadline really has elapsed, so a decline here is the
// palette and not the timer. Proven by the far-future tick at the end,
// which fires with the identical deadline once the palette is gone.
assert!(
!app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 5),
"the palette suppresses this collapse"
);
assert!(app.show_tree, "so the sidebar is still up");
// The user closes the palette. NO new focus move — focus never left the
// editor, so nothing re-arms; the pending collapse must survive on its own.
app.command_palette = None;
assert!(
app.sidebar_auto_hide_allowed(),
"precondition: with the palette closed the collapse is live again"
);
assert!(
app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 5),
"the collapse the palette deferred must still fire once it closes — \
a transient suppression delays the collapse, it does not cancel it"
);
assert!(!app.show_tree, "and the sidebar is finally down");
}
/// #302: toggling the auto-hide SETTING drops any pending collapse. The
/// function's own comment promises turning it on "takes effect at the next
/// focus move rather than retroactively yanking it away" — a dwell left armed
/// across an off/on round trip breaks that promise on the next idle tick, with
/// no focus move of the user's own.
#[test]
fn toggling_the_auto_hide_setting_drops_a_pending_collapse() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = true;
assert!(
app.sidebar_auto_hide_allowed(),
"precondition: collapse is live"
);
let armed_at = std::time::Instant::now();
app.focus_pane(Pane::Editor);
assert!(
app.sidebar_dwell.armed(),
"precondition: a collapse is pending"
);
// The user turns the feature off, then changes their mind.
app.toggle_sidebar_auto_hide();
app.toggle_sidebar_auto_hide();
assert!(app.sidebar_auto_hide, "precondition: back on");
assert!(
!app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 1000),
"the collapse armed before the setting was touched must not fire"
);
assert!(app.show_tree, "so the sidebar is still up");
}
/// #302: the activity bar is a STRUCTURAL suppression that flips on its own,
/// independently of Zen Mode. A collapse armed while it is hidden must not sit
/// armed and then fire — spending a banked reveal pin — on the first idle tick
/// after the bar comes back.
#[test]
fn hiding_the_activity_bar_drops_a_pending_collapse_and_its_pin() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = true;
// A deliberate reveal banks the one-shot pin while the bar is visible.
app.sidebar_pinned_open = true;
let armed_at = std::time::Instant::now();
app.focus_pane(Pane::Editor);
assert!(
app.sidebar_dwell.armed(),
"precondition: a collapse is pending"
);
// The user hides the activity bar, then shows it again.
let root = app.active_workspace_root();
app.dispatch_menu_action(MenuAction::ToggleActivityBar, root.clone());
assert!(!app.activity_bar_visible, "precondition: the bar is hidden");
app.dispatch_menu_action(MenuAction::ToggleActivityBar, root);
assert!(app.activity_bar_visible, "precondition: the bar is back");
// Two things mask this test if left alone, and either alone is enough.
// `dispatch_menu_action` ends by opening the Customize Layout popup, and
// `sidebar_auto_hide_allowed()` bails on `context_menu.is_some()` — so the
// tick declines before reaching anything this test is named for. And the
// pin banked above would absorb the collapse anyway, leaving `!fired` and
// `show_tree` both true while the pin is silently spent, which IS the
// failure the hunk exists to prevent. Assert the dwell and the pin
// directly, with the popup cleared.
app.context_menu = None;
assert!(
app.sidebar_auto_hide_allowed(),
"precondition: nothing else is suppressing the collapse now"
);
assert!(
!app.sidebar_dwell.armed(),
"the activity-bar toggle cancelled the pending collapse"
);
assert!(
!app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 1000),
"an idle tick must not collapse after the bar returns"
);
assert!(app.show_tree, "so the sidebar is still up");
assert!(
!app.sidebar_pinned_open,
"and hiding the bar dropped the pin rather than holding an \
unconsumable one across a period where no collapse can fire — the \
same reason `toggle_side_bar` refuses to bank one in that state"
);
// The pin was dropped, so the next deliberate focus move collapses as the
// user expects rather than being silently exempted by a stale reveal.
let t1 = std::time::Instant::now();
app.focus_pane(Pane::Tree);
app.focus_pane(Pane::Editor);
assert!(
app.tick_sidebar_auto_hide_at(t1 + AUTO_HIDE_DWELL * 2),
"a fresh focus move after the bar returns collapses — no stale pin ate it"
);
}
/// #302's actual payload: the collapse WAITS. Every other app-level test ticks
/// at the deadline or beyond, so all of them pass against a zero-length window
/// — i.e. against #294's immediate collapse delivered through a tick. Deleting
/// the `due()` check leaves them all green. This is the only test that fails
/// when the grace delay itself is removed, which is what makes it the
/// acceptance test for the feature rather than for its plumbing.
#[test]
fn a_collapse_does_not_fire_inside_the_grace_window() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = true;
assert!(
app.sidebar_auto_hide_allowed(),
"precondition: a collapse is live here"
);
// Stamp BEFORE the arm. `maybe_auto_hide_sidebar` anchors on its own
// `Instant::now()`, so a deadline derived from a later stamp could land
// outside the real window and decline as not-yet-due for the wrong reason.
let before = std::time::Instant::now();
app.focus_pane(Pane::Editor);
// Half a window in: the collapse is pending and must not have fired.
assert!(
!app.tick_sidebar_auto_hide_at(before + AUTO_HIDE_DWELL / 2),
"a tick INSIDE the grace window must not collapse — this is the delay"
);
assert!(app.show_tree, "so the sidebar is still up mid-window");
assert!(
app.sidebar_dwell.armed(),
"and the collapse is still pending rather than cancelled"
);
// Past the window, with focus still away: now it fires.
assert!(
app.tick_sidebar_auto_hide_at(before + AUTO_HIDE_DWELL * 3),
"once the window elapses the collapse delivers"
);
assert!(!app.show_tree, "and the sidebar is down");
}
/// #302: a deliberate Cmd+B reveal supersedes a pending automatic collapse.
/// Once a declined tick stays ARMED (so a transient suppression defers rather
/// than cancels), the dwell can outlive the sidebar state it was armed
/// against: the user hides and re-reveals by hand, the reveal banks its
/// one-shot pin, and the very next idle frame tick finds the stale dwell due
/// and spends that pin on a collapse nobody ever saw. The next focus move then
/// takes the sidebar down — the #294 bug, reached by a different door.
#[test]
fn a_manual_reveal_cancels_a_pending_collapse() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = true;
assert!(
app.sidebar_auto_hide_allowed(),
"precondition: a collapse is live here"
);
app.focus_pane(Pane::Editor);
let armed_at = std::time::Instant::now();
// A modal defers the collapse. It stays armed by design (that is the
// transient-suppression retry this PR added).
app.command_palette = Some(crate::widgets::command_palette::CommandPalette::new());
assert!(
!app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 5),
"precondition: the palette defers this collapse"
);
app.command_palette = None;
// The user hides and re-reveals the sidebar by hand.
app.toggle_side_bar();
app.toggle_side_bar();
assert!(
app.show_tree && app.sidebar_pinned_open,
"precondition: the manual reveal banked a one-shot pin"
);
// An IDLE frame tick — no focus move, no gesture at all.
assert!(
!app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 6),
"an idle tick must not collapse a sidebar the user just revealed"
);
assert!(
app.sidebar_pinned_open,
"and must not spend the pin on a collapse the user never saw"
);
// So the deliberate reveal still holds across the next move out.
app.focus_pane(Pane::Editor);
assert!(
!app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 20),
"the reveal survives the next focus move, as #294 guarantees"
);
assert!(app.show_tree, "the sidebar is still up");
}
/// #302: disabling and re-enabling auto-hide drops a pin banked beforehand.
/// `toggle_side_bar` refuses to bank one while the feature is off — "a pin set
/// while the feature is off would sit unconsumed and silently eat the first
/// collapse after they turn it on" — and a pin banked BEFORE the user disables
/// it reaches that same stranded state by the other route. The existing
/// `a_reveal_while_auto_hide_is_off_does_not_bank_an_exemption` covers
/// off -> reveal -> enable; this is reveal -> disable -> enable.
#[test]
fn disabling_auto_hide_drops_a_pin_banked_before_it_was_turned_off() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = false;
app.toggle_side_bar();
assert!(
app.show_tree && app.sidebar_pinned_open,
"precondition: the reveal banked a pin while the feature was on"
);
app.toggle_sidebar_auto_hide();
assert!(!app.sidebar_auto_hide, "precondition: the feature is off");
assert!(
!app.sidebar_pinned_open,
"turning the feature off drops the pin: nothing can consume it while \
off, so it would eat the first collapse after re-enabling"
);
app.toggle_sidebar_auto_hide();
assert!(app.sidebar_auto_hide, "precondition: back on");
assert!(
app.sidebar_auto_hide_allowed(),
"precondition: a collapse is live again"
);
let t0 = std::time::Instant::now();
app.focus_pane(Pane::Editor);
assert!(
app.tick_sidebar_auto_hide_at(t0 + AUTO_HIDE_DWELL * 2),
"and the first collapse after re-enabling fires — no stranded pin ate it"
);
}
/// #302: Zen entry must drop the reveal pin as well as the dwell. Zen sets
/// BOTH structural conditions — `activity_bar_visible = false` and
/// `zen_mode = true` — so `toggle_side_bar`'s reason for refusing to bank a
/// pin there ("no collapse can fire for as long as it lasts") applies in full
/// to a pin already held.
///
/// This is a REGRESSION guard, not just an edge case: on main
/// `maybe_auto_hide_sidebar` did an unconditional `mem::take` of the pin on
/// every focus move into the editor or terminal, so any move during or after
/// Zen cleared it. Moving consumption to fire time removed that incidental
/// cleanup, and nothing replaced it at the Zen boundary.
#[test]
fn entering_zen_mode_drops_the_reveal_pin_as_well_as_the_dwell() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = false;
// A deliberate Cmd+B reveal banks the one-shot exemption.
app.toggle_side_bar();
assert!(
app.show_tree && app.sidebar_pinned_open,
"precondition: the reveal banked a pin"
);
app.toggle_zen_mode();
assert!(app.zen_mode, "precondition: Zen is on");
assert!(
!app.sidebar_pinned_open,
"Zen entry drops the pin: no collapse can fire while Zen owns the \
chrome, so a pin held across it is unconsumable and eats the first \
real collapse afterwards"
);
// The user-visible consequence: after Zen, the next deliberate focus move
// collapses as expected rather than being silently exempted.
app.toggle_zen_mode();
assert!(
!app.zen_mode && app.show_tree,
"precondition: Zen off, sidebar back"
);
assert!(
app.sidebar_auto_hide_allowed(),
"precondition: a collapse is live again"
);
let t0 = std::time::Instant::now();
app.focus_pane(Pane::Editor);
assert!(
app.tick_sidebar_auto_hide_at(t0 + AUTO_HIDE_DWELL * 2),
"and it fires — no stale pin from before Zen absorbed it"
);
}
/// #302: Zen Mode is a STRUCTURAL suppression, not a transient one. The tick
/// stays armed when a drag or a palette defers a collapse, because those end in
/// moments — but Zen can last the session, and a dwell left armed across it
/// fires on the very frame Zen exits, collapsing the sidebar for a focus move
/// the user made an hour earlier.
#[test]
fn entering_zen_mode_cancels_a_pending_collapse_rather_than_deferring_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = true;
assert!(
app.sidebar_auto_hide_allowed(),
"precondition: a collapse is live here"
);
app.focus_pane(Pane::Editor);
let armed_at = std::time::Instant::now();
// Zen takes over the chrome while the collapse is still pending.
app.toggle_zen_mode();
assert!(app.zen_mode, "precondition: Zen is on");
assert!(!app.show_tree, "precondition: Zen hid the sidebar");
// The user works in Zen for a long time, then leaves.
app.toggle_zen_mode();
assert!(!app.zen_mode, "precondition: Zen is off");
assert!(
app.show_tree,
"precondition: leaving Zen restored the sidebar"
);
// A tick far past the original deadline must not fire: that collapse
// belonged to a focus move from before Zen.
assert!(
!app.tick_sidebar_auto_hide_at(armed_at + AUTO_HIDE_DWELL * 1000),
"a collapse armed before Zen must not fire on the frame Zen exits"
);
assert!(app.show_tree, "so the restored sidebar stays up");
}
/// A checker that failed to RUN must not read as a clean project (#256).
///
/// `tsc` prints global errors (`error TS5023: Unknown compiler option`)
/// with no `file(line,col)` prefix, so no matcher claims them and the row
/// count is zero - which is exactly what a clean project looks like.
/// Reporting "no problems" there tells the user their code is fine when the
/// checker never checked it. The exit status is the only thing separating
/// the two, which is why it cannot simply be ignored.
#[cfg(unix)]
#[test]
fn a_project_checker_that_failed_to_run_does_not_report_a_clean_project() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// A failed invocation: non-zero exit, output no matcher claims.
app.finish_project_check_for_test(
tmp.path(),
"error TS5023: Unknown compiler option '--nosuchflag'.\n",
"",
false,
);
assert!(
app.status.contains("failed"),
"an invocation failure must say so, got {:?}",
app.status
);
assert!(
!app.status.contains("no problems"),
"and must NOT read as a clean project, got {:?}",
app.status
);
assert!(
app.status.contains("TS5023"),
"naming the reason, got {:?}",
app.status
);
// npx reports a missing compiler on STDOUT, not stderr, and opens with
// a blank line and an ANSI-coloured banner. The earlier version of this
// test put the text on stderr - the implementation's own wrong
// assumption, encoded in the fixture, so the bug passed the suite.
app.finish_project_check_for_test(
tmp.path(),
"\n\x1b[41m\x1b[37m This is not the tsc command you are looking for \x1b[0m\n",
"",
false,
);
assert!(
app.status.contains("not the tsc command"),
"the reason is found past a blank line and escapes, got {:?}",
app.status
);
assert!(
!app.status.contains('\u{1b}'),
"and carries no escape sequences, got {:?}",
app.status
);
assert_ne!(
app.status, "The project checker failed: ",
"an empty reason is the bug this replaced"
);
// A genuinely clean project: zero rows AND a zero exit.
app.finish_project_check_for_test(tmp.path(), "", "", true);
assert_eq!(
app.status, "Whole-project check: no problems",
"a real clean run still reports clean"
);
}
/// Each producer clears only ITS OWN rows from a shared file (#532).
///
/// `build_diagnostics` held one flat `Vec` per file, so a re-run removed the
/// whole entry and took the other producer's rows with it - and
/// `install_build_diags` recorded a path in `touched` only when the entry was
/// empty, so the SECOND producer to reach a file never listed it and could
/// not clear its rows at all. Two halves of one problem: rows did not carry
/// who produced them.
///
/// #530 made this routine rather than rare: the whole-project sweep reports
/// every file in the project, so it overlaps any pane build by default.
#[test]
fn each_producer_clears_only_its_own_rows_from_a_shared_file() {
let tmp = tempfile::tempdir().unwrap();
let shared = tmp.path().join("shared.ts");
std::fs::write(&shared, "export const a = 1;\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let line = |code: &str| format!("shared.ts(1,1): error {code}: boom.\n");
// Pane 1 reports the file, then the sweep reports it too.
app.apply_build_scan(1, Some(tmp.path()), "tsc", &line("TS1001"));
app.ingest_project_check(Some(tmp.path()), &line("TS2002"));
app.rebuild_problems();
let rows = |app: &App| -> Vec<String> {
app.problems
.groups()
.iter()
.filter(|g| g.path == shared)
.flat_map(|g| g.items.iter().map(|i| i.message.clone()))
.collect()
};
assert_eq!(
rows(&app).len(),
2,
"both producers' rows are on the shared file, got {:?}",
rows(&app)
);
// The SECOND producer re-runs clean. Its row must go; the pane's stays.
app.ingest_project_check(Some(tmp.path()), "");
app.rebuild_problems();
let after = rows(&app);
assert_eq!(
after.len(),
1,
"the sweep's row goes and the pane's remains, got {after:?}"
);
assert!(
after[0].contains("TS1001"),
"the surviving row is the PANE's, not the sweep's: {after:?}"
);
// And the reverse: the pane re-runs clean, leaving nothing.
app.apply_build_scan(1, Some(tmp.path()), "tsc", "");
app.rebuild_problems();
assert!(
rows(&app).is_empty(),
"with both producers clean the file has no rows, got {:?}",
rows(&app)
);
}
/// A file BOTH the sweep and a pane report is counted once, by whoever is
/// reporting (#256).
///
/// `build_diagnostics[f]` holds every producer's items for that file, so
/// summing the store double-counts a shared file. Both orderings are pinned
/// because they fail in opposite directions and one alone would look
/// correct.
///
/// The undercount this doc used to also describe - the second producer never
/// listing a shared file, so it could not clear its rows - was the other half
/// of #532 and is fixed; the rows carry an owner now.
#[cfg(unix)]
#[test]
fn a_file_both_producers_report_is_not_double_counted() {
let tmp = tempfile::tempdir().unwrap();
let shared = tmp.path().join("shared.ts");
let only = tmp.path().join("only.ts");
std::fs::write(&shared, "export const a = 1;\n").unwrap();
std::fs::write(&only, "export const b = 2;\n").unwrap();
let line = |f: &str| format!("{f}(1,1): error TS2322: Type error.\n");
// Sweep first, then a pane reports the SAME file.
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.finish_project_check_for_test(tmp.path(), &line("shared.ts"), "", false);
assert_eq!(app.status, "Whole-project check: 1 problem");
app.apply_build_scan(1, Some(tmp.path()), "tsc", &line("shared.ts"));
app.finish_project_check_for_test(tmp.path(), &line("shared.ts"), "", false);
assert_eq!(
app.status, "Whole-project check: 1 problem",
"the pane's row for the same file is not the sweep's to count"
);
// Pane first, then the sweep reports that file AND another.
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.apply_build_scan(1, Some(tmp.path()), "tsc", &line("shared.ts"));
app.finish_project_check_for_test(
tmp.path(),
&format!("{}{}", line("shared.ts"), line("only.ts")),
"",
false,
);
assert_eq!(
app.status, "Whole-project check: 2 problems",
"the sweep found two, even though a pane got to one of them first"
);
}
/// The sweep's status counts ITS OWN findings, not the whole panel (#256).
///
/// `problems.total_count()` is the panel's projection: it mixes in every
/// language server's diagnostics and every pane's build output, and the
/// Open Files scope filters it. Under that scope a sweep whose findings are
/// all in unopened files would have reported "no problems" - defeating the
/// one thing the feature exists to do.
#[cfg(unix)]
#[test]
fn the_project_check_count_is_its_own_not_the_panels() {
use crate::lsp::manager::DiagnosticSeverity;
let tmp = tempfile::tempdir().unwrap();
let swept = tmp.path().join("swept.ts");
let other = tmp.path().join("other.rs");
std::fs::write(&swept, "export const x: string = 1;\n").unwrap();
std::fs::write(&other, "fn main() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// An unrelated language-server diagnostic is already in the panel.
let mut by_server = std::collections::HashMap::new();
by_server.insert(
String::from("rust-analyzer"),
vec![diag(0, 4, DiagnosticSeverity::Error)],
);
app.lsp_diagnostics.insert(other.clone(), by_server);
app.finish_project_check_for_test(
tmp.path(),
"swept.ts(1,14): error TS2322: Type 'number' is not assignable.\n",
"",
false,
);
assert_eq!(
app.status, "Whole-project check: 1 problem",
"the sweep found one; the LSP's row is not its to count"
);
assert!(
app.problems.total_count() > 1,
"staging check: the panel really does hold more than the sweep's row"
);
// Under Open Files the panel hides the unopened file - the count must
// not follow it down, or the sweep reports nothing it just found.
app.problems.scope = crate::widgets::problems::ProblemScope::OpenFiles;
app.rebuild_problems();
app.finish_project_check_for_test(
tmp.path(),
"swept.ts(1,14): error TS2322: Type 'number' is not assignable.\n",
"",
false,
);
assert_eq!(
app.status, "Whole-project check: 1 problem",
"the scope filters the PANEL, not what the sweep found"
);
}
/// The sweep's auto-enable is capped by workspace size, and the setting
/// overrides the cap in both directions (#256, criterion 5).
///
/// `auto` is a size question, so it has to be answered by counting - but
/// counting a giant tree to decide not to walk a giant tree is the cost the
/// cap exists to avoid. `workspace_exceeds` stops at the threshold rather
/// than completing the walk, so the answer costs at most `limit + 1`
/// entries however large the root is.
#[test]
fn the_sweep_auto_enables_only_under_the_file_threshold() {
let tmp = tempfile::tempdir().unwrap();
for i in 0..12 {
std::fs::write(tmp.path().join(format!("f{i}.ts")), "export const x = 1;\n").unwrap();
}
// Under the cap: auto enables.
assert!(
!App::workspace_exceeds(tmp.path(), 100),
"12 files is under a cap of 100"
);
// The exact boundary, both sides. "Exceeds" means strictly more, so a
// root holding exactly `limit` files does NOT exceed it - without this
// pair, `>` and `>=` are indistinguishable and the doc comment's claim
// is unverified.
assert!(
!App::workspace_exceeds(tmp.path(), 12),
"exactly 12 files does not exceed a cap of 12"
);
assert!(
App::workspace_exceeds(tmp.path(), 11),
"12 files exceeds a cap of 11"
);
assert!(
App::project_check_auto_enabled(tmp.path(), "auto", 100),
"auto enables under the cap"
);
// Over the cap: auto declines.
assert!(
App::workspace_exceeds(tmp.path(), 5),
"12 files exceeds a cap of 5"
);
assert!(
!App::project_check_auto_enabled(tmp.path(), "auto", 5),
"auto declines over the cap"
);
// The setting overrides the count in BOTH directions - a cap that only
// ever said no would make `on` meaningless on the roots that need it.
assert!(
App::project_check_auto_enabled(tmp.path(), "on", 5),
"`on` runs on a root the cap would have declined"
);
assert!(
!App::project_check_auto_enabled(tmp.path(), "off", 100),
"`off` declines a root the cap would have allowed"
);
// An unrecognised value reads as `auto` rather than silently enabling a
// sweep on a monorepo: a typo must not cost more than it saves.
assert!(
!App::project_check_auto_enabled(tmp.path(), "definitely-not-a-mode", 5),
"an unknown setting falls back to auto, which declines here"
);
assert!(
App::project_check_auto_enabled(tmp.path(), "definitely-not-a-mode", 100),
"and to auto's yes under the cap, not a blanket no"
);
}
/// A check that warrants no hint does not spend the one-shot (#256).
///
/// The flag was set when a check STARTED, so any run under `on`, `off`, or
/// an under-cap `auto` consumed the only hint opportunity and a later
/// oversized `auto` run stayed silent forever. It is now set where the hint
/// is received, which is the only point that knows one was warranted.
#[cfg(unix)]
#[test]
fn a_check_that_warrants_no_hint_does_not_spend_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// A run that produces no hint: the flag must stay unspent.
app.queue_project_check_result_for_test(tmp.path(), "", "", true);
app.sync_explorer_panels();
assert!(
!app.project_check_hinted_for_test(),
"a check with no hint must not consume the one-shot"
);
// A later run that DOES warrant one still gets it.
app.send_project_hint_for_test();
app.queue_project_check_result_for_test(tmp.path(), "", "", true);
app.sync_explorer_panels();
assert!(
app.status.contains("too large"),
"the hint the earlier run would have eaten still arrives: {:?}",
app.status
);
assert!(
app.project_check_hinted_for_test(),
"and NOW the one-shot is spent"
);
}
/// The size hint survives a result landing in the same tick (#256).
///
/// Both drains run in one `sync_explorer_panels` body with no paint
/// between them, and the result sets `status` unconditionally. Writing the
/// hint before it DESTROYED the hint rather than deprioritising it - and
/// the hint is one-shot, so it never returned. The fast-failure path (an
/// over-cap root with no compiler installed) is exactly where the checker
/// finishes inside a single tick.
#[cfg(unix)]
#[test]
fn the_size_hint_is_not_erased_by_a_result_in_the_same_tick() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Both messages in flight before ONE drain, which is the race. Driven
// through `sync_explorer_panels` rather than the direct-drain helper:
// the hint logic lives in that function, so calling `drain_project_check`
// itself would test a path the app never takes.
app.send_project_hint_for_test();
app.queue_project_check_result_for_test(tmp.path(), "", "", true);
app.sync_explorer_panels();
assert!(
app.status.contains("no problems"),
"the outcome the user asked for still leads: {:?}",
app.status
);
assert!(
app.status.contains("too large"),
"and the one-shot hint survives rather than being overwritten: {:?}",
app.status
);
}
/// The cap hints ONCE per session, and only under `auto` (#256).
///
/// The hint is the cap's user-visible half: an explicit sweep still runs on
/// a huge root, but the user is told once that automatic runs will not
/// start. Repeating it every sweep would train them to ignore the status
/// line, and showing it under `on` would contradict the setting they chose.
#[test]
fn the_size_hint_fires_once_and_only_under_auto() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// `on` means run regardless of size, so a size hint would contradict it.
app.problems_project_scope = String::from("on");
assert!(
App::project_check_auto_enabled(tmp.path(), &app.problems_project_scope, 0),
"`on` runs even against a zero-file cap"
);
// `off` never auto-runs, so the size is not the reason - no hint either.
app.problems_project_scope = String::from("off");
assert!(!App::project_check_auto_enabled(
tmp.path(),
&app.problems_project_scope,
usize::MAX
));
// Only `auto` makes size the deciding factor. The root needs a file for
// a cap of 0 to be EXCEEDED - an empty tree does not exceed zero, and
// asserting against one would have passed for the wrong reason.
std::fs::write(tmp.path().join("a.ts"), "export const a = 1;\n").unwrap();
app.problems_project_scope = String::from("auto");
assert!(
!App::project_check_auto_enabled(tmp.path(), "auto", 0),
"auto declines when the root exceeds the cap"
);
assert!(
App::project_check_auto_enabled(tmp.path(), "auto", usize::MAX),
"and enables under it - the paired case, so the line above cannot \
pass by the predicate always saying no"
);
// Config values are normalised like the sibling pref: a hand-edited
// "Off " must mean off, not a size-dependent maybe.
assert_eq!(App::project_scope_mode(" Off "), "off");
assert_eq!(App::project_scope_mode("ON"), "on");
assert_eq!(App::project_scope_mode("always"), "on");
assert_eq!(App::project_scope_mode("never"), "off");
assert_eq!(
App::project_scope_mode("wat"),
"auto",
"an unknown value is auto, never on"
);
assert!(
!App::project_check_auto_enabled(tmp.path(), " Off ", usize::MAX),
"a padded, capitalised off is honoured rather than read as auto"
);
}
/// Counting stops at the threshold instead of walking the whole tree
/// (#256, criterion 5).
///
/// Pinned by making the tree far larger than the cap and asserting the
/// answer arrives anyway: a full walk of a deep tree is the thing the cap
/// is protecting against, so a cap that walks it has already lost.
#[test]
fn the_threshold_check_stops_counting_at_the_limit() {
let tmp = tempfile::tempdir().unwrap();
// 500 files against a cap of 3.
for d in 0..10 {
let dir = tmp.path().join(format!("d{d}"));
std::fs::create_dir_all(&dir).unwrap();
for i in 0..50 {
std::fs::write(dir.join(format!("f{i}.ts")), "x\n").unwrap();
}
}
assert!(App::workspace_exceeds(tmp.path(), 3), "500 files exceeds 3");
// Ignored directories do not count toward the cap: node_modules alone
// would put every JS project over it, which would disable the sweep for
// exactly the projects the feature is for.
let clean = tempfile::tempdir().unwrap();
let heavy = clean.path().join("node_modules").join("pkg");
std::fs::create_dir_all(&heavy).unwrap();
for i in 0..200 {
std::fs::write(heavy.join(format!("m{i}.js")), "x\n").unwrap();
}
std::fs::write(clean.path().join("a.ts"), "export const a = 1;\n").unwrap();
assert!(
!App::workspace_exceeds(clean.path(), 10),
"node_modules is not the user's code and must not trip the cap"
);
}
/// "Problems: Check Whole Project" puts a whole-project checker's findings
/// into PROBLEMS for files nobody opened, and a re-run REPLACES them (#256).
///
/// Replacement is the half worth pinning. A checker that reports two errors
/// and then one after a fix must leave one row, not three: the panel is a
/// current state, and a stale row sends the reader to a line that is now
/// correct. `apply_build_scan` already owns that semantics per producer, so
/// the project check gets its own producer id rather than borrowing a
/// pane's: a pane's next command would otherwise wipe the sweep's rows, and
/// the sweep would wipe the pane's.
#[test]
fn a_project_check_reports_unopened_files_and_replaces_on_rerun() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.ts");
let b = tmp.path().join("b.ts");
std::fs::write(&a, "export const x: string = 1;\n").unwrap();
std::fs::write(&b, "export const y: string = 2;\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Neither file is opened: the sweep is exactly for files with no buffer.
assert!(app.editor.path.is_none(), "no file is open");
// Two errors, in tsc's parenthesised form.
app.ingest_project_check(
None,
"a.ts(1,14): error TS2322: Type 'number' is not assignable to type 'string'.\n\
b.ts(1,14): error TS2322: Type 'number' is not assignable to type 'string'.\n",
);
app.rebuild_problems();
let paths: Vec<_> = app
.problems
.groups()
.iter()
.map(|g| g.path.clone())
.collect();
assert!(
paths.contains(&a) && paths.contains(&b),
"both unopened files must reach PROBLEMS, got {paths:?}"
);
// The user fixes b.ts and re-runs: one row, not three.
app.ingest_project_check(
None,
"a.ts(1,14): error TS2322: Type 'number' is not assignable to type 'string'.\n",
);
app.rebuild_problems();
let paths: Vec<_> = app
.problems
.groups()
.iter()
.map(|g| g.path.clone())
.collect();
assert!(
paths.contains(&a),
"the still-broken file keeps its row, got {paths:?}"
);
assert!(
!paths.contains(&b),
"a re-run REPLACES the previous sweep: the fixed file's row must go, \
got {paths:?}"
);
// A pane's own build output must not wipe the sweep, which is why the
// sweep does not borrow a pane id. Pane 1 reports on its own file.
let c = tmp.path().join("c.ts");
std::fs::write(&c, "export const z = 3;\n").unwrap();
app.apply_build_scan(
1,
Some(tmp.path()),
"tsc",
"c.ts(1,1): error TS1005: ';' expected.\n",
);
app.rebuild_problems();
let paths: Vec<_> = app
.problems
.groups()
.iter()
.map(|g| g.path.clone())
.collect();
assert!(
paths.contains(&a) && paths.contains(&c),
"a pane's build output and the project sweep coexist, got {paths:?}"
);
}
/// #256 step 1: a server that publishes project-wide diagnostics (rust-analyzer
/// does this from `cargo check`) names files the user never opened. The panel
/// builds from the diagnostics store rather than from open buffers, so those
/// rows DO appear — this pins that half, which the issue lists as unverified.
#[test]
fn problems_shows_diagnostics_for_a_file_that_was_never_opened() {
use crate::lsp::manager::DiagnosticSeverity;
let tmp = tempfile::tempdir().unwrap();
let opened = tmp.path().join("opened.rs");
let never = tmp.path().join("never_opened.rs");
std::fs::write(&opened, "fn main() {}\n").unwrap();
std::fs::write(&never, "fn helper() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&opened).unwrap();
let mut by_server = std::collections::HashMap::new();
by_server.insert(
String::from("rust-analyzer"),
vec![diag(0, 4, DiagnosticSeverity::Error)],
);
app.lsp_diagnostics.insert(never.clone(), by_server);
app.rebuild_problems();
let paths: Vec<_> = app.problems.groups().iter().map(|g| &g.path).collect();
assert!(
paths.contains(&&never),
"a diagnostic for an unopened file must still reach PROBLEMS"
);
}
/// #256: the scope toggle changes which files the panel lists, and the badge
/// counts the same list — both read one projection, so they cannot disagree.
#[test]
fn problems_scope_toggle_filters_unopened_files_and_the_badge_follows() {
use crate::lsp::manager::DiagnosticSeverity;
use crate::widgets::problems::ProblemScope;
let tmp = tempfile::tempdir().unwrap();
let opened = tmp.path().join("opened.rs");
let never = tmp.path().join("never_opened.rs");
std::fs::write(&opened, "fn main() {}\n").unwrap();
std::fs::write(&never, "fn helper() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&opened).unwrap();
for p in [&opened, &never] {
let mut by_server = std::collections::HashMap::new();
by_server.insert(
String::from("rust-analyzer"),
vec![diag(0, 4, DiagnosticSeverity::Error)],
);
app.lsp_diagnostics.insert(p.clone(), by_server);
}
app.problems.scope = ProblemScope::WholeProject;
app.rebuild_problems();
assert_eq!(
app.problems.groups().len(),
2,
"whole project lists the unopened file too"
);
let whole_count = app.problems.total_count();
app.problems.scope = ProblemScope::OpenFiles;
app.rebuild_problems();
let paths: Vec<_> = app.problems.groups().iter().map(|g| &g.path).collect();
assert_eq!(paths, vec![&opened], "open files drops the unopened one");
assert!(
app.problems.total_count() < whole_count,
"the badge counts the same filtered list"
);
}
/// #296 review: Open Files scope filters on the open-buffer set, so the panel
/// must refresh when that set changes — not only when diagnostics do.
/// Previously `rebuild_problems` ran on diagnostic events alone, so opening a
/// file that already had stored diagnostics showed NOTHING until some
/// unrelated churn happened to trigger a rebuild.
#[test]
fn opening_a_file_refreshes_a_scoped_problems_panel() {
use crate::lsp::manager::DiagnosticSeverity;
use crate::widgets::problems::ProblemScope;
let tmp = tempfile::tempdir().unwrap();
let later = tmp.path().join("later.rs");
std::fs::write(&later, "fn helper() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.problems.scope = ProblemScope::OpenFiles;
// A diagnostic arrives for a file that is not open yet.
let mut by_server = std::collections::HashMap::new();
by_server.insert(
String::from("rust-analyzer"),
vec![diag(0, 4, DiagnosticSeverity::Error)],
);
app.lsp_diagnostics.insert(later.clone(), by_server);
app.rebuild_problems();
assert!(
app.problems.groups().is_empty(),
"not open yet, so Open Files scope hides it"
);
// Opening it must bring the row in WITHOUT any new diagnostic push.
app.editor.open_pinned(&later).unwrap();
app.sync_lsp();
let paths: Vec<_> = app.problems.groups().iter().map(|g| &g.path).collect();
assert!(
paths.contains(&&later),
"opening the file refreshes the scoped panel"
);
}
/// The config token round-trips: writing a scope back and reading it must
/// yield the same scope. `label()` is display text, so using it here would
/// produce a value `from_config` only accepts by accident.
#[test]
fn problem_scope_config_tokens_round_trip() {
use crate::widgets::problems::ProblemScope;
for scope in [ProblemScope::OpenFiles, ProblemScope::WholeProject] {
assert_eq!(
ProblemScope::from_config(scope.to_config()),
scope,
"{} must survive a save/load cycle",
scope.to_config()
);
}
// The palette label pasted into a config is understood, not silently
// treated as an unrecognised value.
assert_eq!(
ProblemScope::from_config("Open Files"),
ProblemScope::OpenFiles
);
// Anything genuinely unrecognised shows more rather than hiding rows.
assert_eq!(
ProblemScope::from_config("nonsense"),
ProblemScope::WholeProject
);
}
/// "N of M started" must count sessions, not call sites.
///
/// `launch_resolved_into_set` returns `()` on every validation, spawn and
/// attach failure, so the member launcher reported `Launched` unconditionally
/// and the summary counted members that never started. CI caught the extreme
/// form of it on a runner with no Python adapter: "2 session(s), showing ?"
/// over an entirely empty set.
///
/// The assertion is the INVARIANT, not a number: a session exists for each
/// one the report claims. A literal count would only restate whichever host
/// ran it - this Mac starts the good member, CI starts nothing.
#[test]
fn a_member_that_fails_to_start_is_not_counted_as_started() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
// `Broken` names an adapter croft cannot resolve, so it can never start
// on any host; `Server` starts wherever debugpy exists.
std::fs::write(
tmp.path().join(".vscode/launch.json"),
r#"{ "configurations": [
{ "name": "Server", "type": "python", "request": "launch", "program": "s.py" },
{ "name": "Broken", "type": "no-such-debugger", "request": "launch", "program": "b.py" }
],
"compounds": [
{ "name": "Mixed", "configurations": ["Server", "Broken"] }
]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_debug_config_picker();
let row = app
.list_picker
.as_ref()
.unwrap()
.rows
.iter()
.position(|r| r.label.starts_with("Mixed"))
.expect("the compound is listed");
app.list_picker.as_mut().unwrap().selected = row;
app.confirm_list_picker();
let live = app.debug_sessions.names();
assert!(
!live.contains(&"Broken".to_string()),
"the unresolvable member never joins the set: {live:?}"
);
let reported = app
.run_debug
.feedback
.clone()
.unwrap_or_else(|| app.status.clone());
if live.is_empty() {
assert!(
reported.contains("started no sessions"),
"an empty set is reported as empty, never as live sessions: {reported}"
);
} else {
assert!(
reported.contains(&format!("{} of 2", live.len())),
"the count names the sessions that exist ({}), not the members attempted: {reported}",
live.len()
);
}
assert!(
!reported.contains("showing ?"),
"no session is described that cannot be named: {reported}"
);
}
/// A member croft declines to start must be NAMED where the user will see it.
///
/// `launch_compound_members` builds that line into `run_debug.feedback`, and
/// it is the only place the skipped member's name appears - `status` carries
/// the compound and a count, never which member is missing. `reveal_debug_view`
/// runs `refresh_run_debug`, which clears `feedback`, so calling it AFTER the
/// assignment wiped the line before it could be drawn and the compound ran
/// fewer sessions than asked for with nothing said about it.
///
/// The assertion is on the member's NAME in the surviving feedback. Asserting
/// `feedback.is_some()` would pass on the all-started line too, which names no
/// skipped member and is exactly the case this must distinguish from.
#[test]
fn a_compound_member_skipped_for_its_own_task_is_named_in_the_feedback() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
// `Client` declares its own preLaunchTask, so croft refuses to debug it
// against whatever the last build left behind. `Server` has none and runs.
std::fs::write(
tmp.path().join(".vscode/launch.json"),
r#"{ "configurations": [
{ "name": "Server", "type": "python", "request": "launch", "program": "s.py" },
{ "name": "Client", "type": "python", "request": "launch", "program": "c.py",
"preLaunchTask": "build-client" }
],
"compounds": [
{ "name": "Pair", "configurations": ["Server", "Client"] }
]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_debug_config_picker();
let row = app
.list_picker
.as_ref()
.unwrap()
.rows
.iter()
.position(|r| r.label.starts_with("Pair"))
.expect("the compound is listed");
app.list_picker.as_mut().unwrap().selected = row;
app.confirm_list_picker();
// Whether `Server` can START depends on the host's adapters - CI has none
// and this Mac does - but the SKIP is decided at parse time and happens
// either way. So the naming is what this pins, and it reads whichever
// field carries the report on this path.
let reported = app
.run_debug
.feedback
.clone()
.unwrap_or_else(|| app.status.clone());
assert!(
reported.contains("Client"),
"the skipped member is named: {reported}"
);
assert!(
reported.contains("preLaunchTask"),
"and why it was skipped: {reported}"
);
// The control for the assertions above: `Client` is never in the running
// set, so `contains("Client")` above is not passing on a line that merely
// lists every configuration in the file.
assert!(
!app.debug_sessions.names().contains(&"Client".to_string()),
"the skipped member is not running: {:?}",
app.debug_sessions.names()
);
}
/// #310 defers compounds that need SEVERAL debug sessions at once. A compound
/// naming ONE configuration needs exactly one session, which croft has run
/// since #250 — so refusing it cites a limitation that does not apply and
/// tells the user something false about their own launch.json.
///
/// `parse_compounds` rejects only an EMPTY member list, so a one-member
/// compound parses and reaches the launch site, where the `Ok(_)` arm reports
/// the #310 message without ever consulting `configurations.len()`. This is a
/// relocated-decision leftover: the member list is resolved, then the arm that
/// consumes it answers a question about session count without reading it.
#[test]
fn a_single_member_compound_launches_rather_than_citing_the_multi_session_limit() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(
tmp.path().join(".vscode/launch.json"),
r#"{ "configurations": [
{ "name": "Server", "type": "python", "request": "launch", "program": "s.py" },
{ "name": "Client", "type": "python", "request": "launch", "program": "c.py" }
],
"compounds": [
{ "name": "Just Server", "configurations": ["Server"] },
{ "name": "Both", "configurations": ["Server", "Client"] },
{ "name": "Tasked", "configurations": ["Server"], "preLaunchTask": "build" }
]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_debug_config_picker();
let idx = app
.list_picker
.as_ref()
.expect("picker open")
.rows
.iter()
.position(|r| r.label.starts_with("Just Server"))
.expect("the one-member compound is listed");
app.list_picker.as_mut().unwrap().selected = idx;
app.confirm_list_picker();
assert!(
!app.status.contains("#310"),
"a one-member compound needs ONE session, so the multi-session \
deferral does not apply to it: {}",
app.status
);
// #567: it selects the COMPOUND, not its member. Selecting the member
// made F5 relaunch the bare configuration, skipping anything the compound
// itself declares (its preLaunchTask).
assert_eq!(app.selected_debug_compound.as_deref(), Some("Just Server"));
assert_eq!(app.selected_debug_config, None);
// The selection is assigned BEFORE the launch, which has several
// early-return error paths — so the assertion above proves only that the
// launch BRANCH was reached. Assert the launch was not refused.
// The launch reached a real adapter, so what it does next depends on the
// machine: the GitHub runner has no `uv`, and "Debugger setup failed:
// running `uv venv`" is a true report about that box, not this fix
// regressing. Assert what the fix actually claims - that the refusal is
// not the #310 deferral - rather than that nothing went wrong at all,
// which made the test a statement about the environment.
if let Some(feedback) = app.run_debug.feedback.as_deref() {
assert!(
!feedback.contains("#310") && !feedback.contains("several debug sessions"),
"a one-member compound must not be refused for needing several \
sessions; any other environment-dependent failure is not this \
test's business: {feedback}"
);
}
// The guard that used to hold this line: a multi-member compound was
// DEFERRED and named #310. It launches now, which is what #310 built, so
// the guard becomes the positive one - the same picker row starts every
// member rather than one of them.
app.open_debug_config_picker();
let multi = app
.list_picker
.as_ref()
.unwrap()
.rows
.iter()
.position(|r| r.label.starts_with("Both"))
.expect("the two-member compound is listed");
app.list_picker.as_mut().unwrap().selected = multi;
app.confirm_list_picker();
// Asserting the ABSENCE of the old message proves nothing - any refusal
// omits it, and so does an empty status. Pin the OUTCOME: both members
// are running, in file order, with the first focused.
//
// Not a disjunction over "started no sessions". That arm is satisfied by
// the zero-session early return, so it passed without ever constraining
// the count - and the premise behind it ("no adapter is installed, so
// every member fails to start") is simply false here: the compound really
// does launch two sessions on this host.
// The REPORT must agree with the SET, whatever the host can start. CI has
// no Python adapter and starts zero; this Mac has debugpy and starts two.
// Pinning either number makes the test a statement about the runner, so
// pin the invariant that was actually broken: the count came from the
// number of members attempted rather than from the sessions that exist,
// and said "2 session(s), showing ?" over an empty set.
let live = app.debug_sessions.names();
if live.is_empty() {
assert!(
app.status.contains("started no sessions"),
"no adapter: the compound says so rather than claiming sessions: {}",
app.status
);
} else {
assert_eq!(
live,
vec!["Server", "Client"],
"with an adapter, both members run in launch.json order: {}",
app.status
);
assert_eq!(
app.debug_sessions.focused_name(),
Some("Server"),
"the FIRST member takes focus"
);
assert!(
app.status.contains(&format!("{} session(s)", live.len())),
"the count names the sessions that exist: {}",
app.status
);
assert!(
!app.status.contains("showing ?"),
"and the focused session is identified: {}",
app.status
);
}
assert!(
!app.status.contains("#310"),
"and no longer defers to the session limit: {}",
app.status
);
// #318: a compound's own `preLaunchTask` is now RUN rather than refused.
// This workspace declares no tasks at all, so the compound naming one is
// an error that says which task is missing — the same contract a config's
// own task gets, because the user cannot tell the two apart from outside.
//
// On a FRESH app: the launches above leave a live session, and
// `debug_error` does not clear one, so asserting `is_none()` on this app
// would be answered by the earlier launch rather than by this path.
let mut fresh = App::new(tmp.path().to_path_buf()).unwrap();
fresh.open_debug_config_picker();
let tasked = fresh
.list_picker
.as_ref()
.expect("picker open")
.rows
.iter()
.position(|r| r.label.starts_with("Tasked"))
.expect("the task-carrying compound is listed");
fresh.list_picker.as_mut().unwrap().selected = tasked;
fresh.confirm_list_picker();
assert!(
fresh.status.contains("\"build\" not found"),
"the error names the task the file asked for, so the user can declare \
it rather than guessing: {}",
fresh.status
);
assert!(
!fresh.status.contains("#318"),
"and it no longer cites the unbuilt-feature issue: croft honours this \
key now, so naming #318 would report a limitation it does not have: {}",
fresh.status
);
assert!(
fresh.pending_debug_launch.is_none(),
"nothing parked behind a task that does not exist"
);
assert!(
fresh.debug_sessions.is_empty(),
"and nothing launched — starting the member anyway would debug stale \
artifacts, which is what running the task exists to prevent"
);
}
/// #318: a compound's own `preLaunchTask` runs before its member starts, and
/// the launch waits for it — the same contract a configuration's own task has.
///
/// The distinguishing assertion is the PARK. A compound that simply launched
/// its member would leave `pending_debug_launch` empty and a session starting;
/// one that refused would report an error and do nothing. Parked-with-no-error
/// is the state that only "the task is running, the debugger is waiting for
/// it" produces.
#[test]
fn a_compounds_own_pre_launch_task_runs_before_its_member_starts() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(
tmp.path().join(".vscode/tasks.json"),
r#"{ "version": "2.0.0", "tasks": [
{ "label": "build", "type": "shell", "command": "true" }
]}"#,
)
.unwrap();
std::fs::write(
tmp.path().join(".vscode/launch.json"),
r#"{ "configurations": [
{ "name": "Server", "type": "python", "request": "launch", "program": "s.py" },
{ "name": "Client", "type": "python", "request": "launch", "program": "c.py" }
],
"compounds": [
{ "name": "Tasked", "configurations": ["Server"], "preLaunchTask": "build" },
{ "name": "Presented", "configurations": ["Server"],
"presentation": { "hidden": "true" } },
{ "name": "PresentedPair", "configurations": ["Server", "Client"],
"presentation": { "hidden": "true" } }
]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let select = |app: &mut App, label: &str| {
app.open_debug_config_picker();
let idx = app
.list_picker
.as_ref()
.expect("picker open")
.rows
.iter()
.position(|r| r.label.starts_with(label))
.unwrap_or_else(|| panic!("{label} is listed"));
app.list_picker.as_mut().unwrap().selected = idx;
app.confirm_list_picker();
};
select(&mut app, "Tasked");
assert!(
app.pending_debug_launch.is_some(),
"the launch waits behind the compound's task rather than starting \
alongside it: status was {:?}",
app.status
);
assert!(
!app.run_debug.feedback_is_error,
"and this is progress, not a refusal: {:?}",
app.run_debug.feedback
);
assert!(
app.status.contains("build") && app.status.contains("exits 0"),
"the status names the task and the condition the launch waits on: {}",
app.status
);
assert!(
app.debug_sessions.is_empty(),
"nothing has been debugged yet — that is the whole point of the wait"
);
// The guard that must stay GREEN: honouring one key must not be
// satisfiable by launching everything. Since #318 finished, `hidden`,
// `group` and `order` are all honoured, so the only shapes left to carry
// this guard are the MALFORMED ones. `{"hidden": "true"}` is the likely
// typo: a quoted bool croft cannot read, which must refuse rather than
// launch unhidden in silence.
let mut fresh = App::new(tmp.path().to_path_buf()).unwrap();
select(&mut fresh, "Presented");
assert!(
fresh.run_debug.feedback_is_error,
"presentation is still not honoured, so it still refuses: {:?}",
fresh.run_debug.feedback
);
// The message names the SUB-KEY, not `presentation` (#318). That is the
// point of the split: a compound may declare a working `group` beside a
// malformed `hidden`, so telling the user that "presentation" is
// unsupported would send them deleting a line that works.
assert!(
fresh.status.contains("presentation.hidden"),
"and names the key it cannot read: {}",
fresh.status
);
// The BARE parent would overstate it, for the same reason. The qualified
// path is what they can find in the file, so the check is that
// `presentation` never appears WITHOUT its sub-key.
assert!(
!fresh
.status
.replace("presentation.hidden", "")
.contains("presentation"),
"the parent is named only as part of the qualified path: {}",
fresh.status
);
assert!(
!fresh.status.contains("preLaunchTask"),
"without naming the one it now can — reporting a limitation croft no \
longer has is the false claim this whole path exists to avoid: {}",
fresh.status
);
assert!(
fresh.pending_debug_launch.is_none() && fresh.debug_sessions.is_empty(),
"and nothing ran"
);
// The same refusal on a MULTI-member compound must not tell the user to
// run one member directly. The guard covers both arities now, and naming
// only the first is advice to launch a SUBSET - the very outcome this arm
// refuses to produce itself. Both names, or the remedy is worse than the
// refusal.
let mut pair = App::new(tmp.path().to_path_buf()).unwrap();
select(&mut pair, "PresentedPair");
assert!(
pair.run_debug.feedback_is_error,
"a malformed key still refuses at two members: {:?}",
pair.run_debug.feedback
);
assert!(
pair.status.contains("Server") && pair.status.contains("Client"),
"and the remedy names EVERY member, not just the first: {}",
pair.status
);
assert!(pair.debug_sessions.is_empty(), "and still nothing ran");
}
/// #318, the half a parked-launch assertion cannot see: what happens when the
/// compound's task FINISHES.
///
/// A compound's member is resumed through the ordinary launch path, so a
/// member carrying its own `preLaunchTask` parks again rather than starting.
/// That chaining is what makes croft run both tasks, as VS Code does, and
/// nothing about the initial park proves it happens.
#[test]
fn a_finished_compound_task_starts_its_member_and_chains_the_members_own_task() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(
tmp.path().join(".vscode/tasks.json"),
r#"{ "version": "2.0.0", "tasks": [
{ "label": "compound-build", "type": "shell", "command": "true 1" },
{ "label": "member-build", "type": "shell", "command": "true 2" }
]}"#,
)
.unwrap();
std::fs::write(
tmp.path().join(".vscode/launch.json"),
r#"{ "configurations": [
{ "name": "Server", "type": "python", "request": "launch",
"program": "s.py", "preLaunchTask": "member-build" }
],
"compounds": [
{ "name": "Tasked", "configurations": ["Server"], "preLaunchTask": "compound-build" }
]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_debug_config_picker();
let idx = app
.list_picker
.as_ref()
.expect("picker open")
.rows
.iter()
.position(|r| r.label.starts_with("Tasked"))
.expect("the compound is listed");
app.list_picker.as_mut().unwrap().selected = idx;
app.confirm_list_picker();
let parked = app
.pending_debug_launch
.take()
.expect("the compound's task parked the launch");
assert!(
app.status.contains("compound-build"),
"staging: it is the COMPOUND's task that ran first: {}",
app.status
);
// The compound's task exits 0.
app.resume_pending_launch(Some(0), parked.step);
// The member does not go straight to the adapter: it declares a task of
// its own, so it parks in turn. Both tasks run, which is the behaviour
// being chained rather than merged buys.
let second = app
.pending_debug_launch
.as_ref()
.expect("the member's own preLaunchTask parks in turn rather than being skipped");
assert!(
app.status.contains("member-build"),
"and it is the MEMBER's task waiting now: {}",
app.status
);
assert!(
!app.run_debug.feedback_is_error,
"still progress, not a refusal: {:?}",
app.run_debug.feedback
);
assert!(
matches!(second.step, crate::app::PendingLaunchStep::Resolved(_)),
"the second park is the member's own launch, so the chain ends here \
rather than looping"
);
// A task that fails aborts instead of debugging what the build left.
let second = app.pending_debug_launch.take().expect("still parked");
app.resume_pending_launch(Some(1), second.step);
assert!(
app.run_debug.feedback_is_error && app.status.contains("exited 1"),
"a non-zero task aborts the launch and says so: {}",
app.status
);
assert!(app.debug_sessions.is_empty(), "and nothing was debugged");
}
/// #302: a dwell must not be ARMED while a structural suppression is already
/// in force. This is the one instance of the class that no entry-site disarm
/// can catch, and it is worth being explicit about why.
///
/// `entering_zen_mode_cancels_a_pending_collapse_rather_than_deferring_it`
/// covers arming BEFORE Zen: there is a transition, Zen entry sees it, and the
/// entry hook disarms. Here the dwell is armed DURING Zen — Cmd+B still works
/// inside Zen, and a focus move afterwards arms as usual — so the suppression
/// is never entered while the dwell is live. There is no transition, so there
/// is no boundary to hook, and every existing disarm site is structurally
/// blind to it.
///
/// The consequence is user-visible and delayed: the arm declines at fire time
/// via `!sidebar_auto_hide_allowed()` and stays armed BY DESIGN (transient
/// suppressions must retry). Zen is not transient. An hour later the user
/// leaves Zen and the next 8ms tick collapses the sidebar for a focus move
/// they made an hour earlier, silently spending any pin with it.
///
/// The fix is therefore not a sixth boundary: `maybe_auto_hide_sidebar` must
/// refuse to arm under a structural suppression at all, mirroring what
/// `toggle_side_bar` already does for the pin at the same four conditions.
#[test]
fn arming_inside_zen_mode_does_not_collapse_the_sidebar_when_zen_exits() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = false;
// Into Zen FIRST, so there is no pending dwell for Zen entry to cancel.
app.toggle_zen_mode();
assert!(app.zen_mode, "precondition: Zen is on");
assert!(
!app.sidebar_auto_hide_allowed(),
"precondition: Zen structurally suppresses the collapse"
);
// Cmd+B works inside Zen, and the user opens the sidebar to look at a file.
app.toggle_side_bar();
assert!(app.show_tree, "precondition: the sidebar is up inside Zen");
assert!(
!app.sidebar_pinned_open,
"precondition: toggle_side_bar already refuses to bank a pin under a \
structural suppression — this test is about the DWELL, which does not"
);
// Focus moves away, exactly as it would outside Zen. This is the arm that
// no entry site can see: the suppression was already in force.
let t0 = std::time::Instant::now();
app.focus_pane(Pane::Editor);
// The main loop, faithfully: ticks throughout Zen, well past the grace
// delay. None may collapse, and — the part two previous fixes got wrong —
// none may destroy the pending collapse either, because nothing would
// re-arm it afterwards.
for i in 0..50u32 {
assert!(
!app.tick_sidebar_auto_hide_at(
t0 + AUTO_HIDE_DWELL * 2 + std::time::Duration::from_millis(8 * i as u64)
),
"no collapse fires inside Zen: Zen owns the chrome (tick {i})"
);
}
assert!(
app.sidebar_dwell.armed(),
"and the dwell SURVIVES those ticks. Cancelling on a suppressed tick \
is indistinguishable from refusing to arm — production ticks every \
8ms, so the cancel lands 8ms after the arm, and nothing re-arms once \
a structural suppression lifts"
);
// The user-visible failure, spelled out. Zen exit RESTORES the pre-Zen
// snapshot, so the sidebar this test opened inside Zen is closed again on
// the way out — that part is by design and not what is under test. Reopen
// it, then check that no stale collapse from the in-Zen focus move is still
// pending to fire on the next tick.
app.toggle_zen_mode();
assert!(!app.zen_mode, "precondition: Zen is off again");
app.show_tree = true;
assert!(
app.sidebar_auto_hide_allowed(),
"precondition: a collapse is structurally possible again"
);
// The claim this test exists for: no STALE collapse on the frame Zen exits.
// The dwell is still armed, but each suppressed tick re-stamped it, so its
// deadline is measured from the last moment a collapse was impossible —
// not from the focus move made before Zen. The user gets the full grace
// period from a moment they can perceive: the chrome coming back.
assert!(
!app.tick_sidebar_auto_hide_at(t0 + AUTO_HIDE_DWELL * 2),
"and no stale collapse fires after Zen exits, for a focus move made \
while Zen was still on"
);
assert!(
app.show_tree,
"the sidebar is still up: the user asked for it and never asked otherwise"
);
// But the collapse is not LOST either — that was the round-one and
// round-two defect. Once the re-stamped grace period elapses it fires.
let after_zen = t0 + AUTO_HIDE_DWELL * 2 + std::time::Duration::from_millis(8 * 49);
assert!(
app.tick_sidebar_auto_hide_at(after_zen + AUTO_HIDE_DWELL * 2),
"and once the grace period from Zen exit elapses, it does fire: \
retained, not discarded"
);
}
/// #302 REGRESSION GUARD, round three. The two previous fixes each destroyed
/// the state the recovery needs, and the guard that was supposed to catch that
/// COULD NOT, because it never ticked during the suppression.
///
/// `main_loop` calls `tick_sidebar_auto_hide()` unconditionally on an 8ms
/// cadence (mod.rs, `event::poll(Duration::from_millis(8))`). So in production
/// a tick lands within 8ms of arming — and again, and again, for as long as the
/// suppression lasts. Any design that cancels the dwell on a suppressed tick
/// has cancelled it 8ms after it was armed, which is indistinguishable from
/// refusing to arm at all.
///
/// This test therefore TICKS DURING THE SUPPRESSED PERIOD, many times, exactly
/// as the main loop would. That single property is what separates it from the
/// vacuous guard it replaces: the previous version set the flag, cleared it,
/// and ticked once afterwards — a sequence production never produces.
#[test]
fn auto_hide_recovers_after_the_activity_bar_comes_back() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_auto_hide = true;
app.show_tree = true;
app.activity_bar_visible = false;
app.focus_pane(Pane::Tree);
assert!(
!app.sidebar_auto_hide_allowed(),
"precondition: a hidden activity bar structurally suppresses the collapse"
);
let t0 = std::time::Instant::now();
app.focus_pane(Pane::Editor);
// The main loop, faithfully: ticks every 8ms while the bar stays hidden,
// and — the part that makes this a real guard — PAST the grace delay.
//
// Ticking only within AUTO_HIDE_DWELL proves nothing: the tick returns at
// its `due` check before it ever reaches the structural branch, so a
// cancel-on-suppressed-tick defect is unreachable and the test passes
// against the very design it exists to reject. That was the third version
// of this guard and it had no teeth; teeth-proving it against the round-two
// mutation is what exposed that. Production ticks for as long as the
// suppression lasts, which is minutes or hours, so the ticks that matter
// are the ones AFTER the deadline has elapsed.
for i in 0..50u32 {
let t = t0 + AUTO_HIDE_DWELL * 2 + std::time::Duration::from_millis(8 * i as u64);
assert!(
!app.tick_sidebar_auto_hide_at(t),
"no collapse may fire while the bar is hidden (tick {i})"
);
}
assert!(
app.sidebar_dwell.armed(),
"and the dwell SURVIVES them: cancelling on a suppressed tick is what \
strands the feature, because nothing re-arms once the bar returns"
);
assert!(
app.show_tree,
"precondition: still open after 50 suppressed ticks"
);
// An hour later the user brings the activity bar back. Focus never moved —
// it is still the editor — so no gesture will arm anything, and production
// guards `if self.focus != Pane::Editor` before calling `focus_pane`.
app.activity_bar_visible = true;
assert!(
app.focus == Pane::Editor,
"precondition: focus never moved, so nothing re-arms by gesture"
);
assert!(
app.sidebar_auto_hide_allowed(),
"precondition: the suppression has lifted"
);
let last_tick = t0 + AUTO_HIDE_DWELL * 2 + std::time::Duration::from_millis(8 * 49);
assert!(
app.tick_sidebar_auto_hide_at(last_tick + AUTO_HIDE_DWELL * 2),
"auto-hide recovers once the bar returns: the pending collapse fires \
rather than the feature staying dead for the session"
);
assert!(!app.show_tree, "and the sidebar actually collapsed");
}
/// #257: Cmd+F in a rendered colour log must search what the user SEES.
///
/// The log view keeps the file windowed, so a log tab's `lines` is a stub
/// and the ordinary find path reads an empty buffer: the bar answers "No
/// results" over a file full of matches. `LogView::visible_text` was
/// written for exactly these consumers and had none.
#[test]
fn find_in_a_rendered_color_log_matches_the_visible_text() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("build.log");
let mut body = String::new();
for i in 0..200 {
body.push_str(&format!("\u{1b}[32mINFO\u{1b}[0m step {i} ok\n"));
}
body.push_str("\u{1b}[31mERROR\u{1b}[0m disk full\n");
std::fs::write(&p, &body).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.open(&p).unwrap();
assert!(
app.editor.log.is_some(),
"the fixture must open as a rendered log"
);
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
for ch in "disk".chars() {
app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
.unwrap();
}
let state = app
.editor_find
.as_ref()
.expect("Cmd+F opens the find bar over a log");
assert_eq!(
state.match_count, 1,
"the one ERROR line must be found through the stripped text"
);
assert_eq!(
app.editor.active_search_match.map(|(r, _, _)| r),
Some(200),
"the match is the last line of the file"
);
assert!(
app.editor.scroll > 0,
"the view must scroll to reveal the match, not sit at the top"
);
}
/// #257: Enter and Shift+Enter step through a log's matches. The log has no
/// caret to carry the position, so the walk is anchored on the active match
/// alone; without that anchor every Enter would re-find the same line.
#[test]
fn enter_steps_through_matches_in_a_rendered_log() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("run.log");
std::fs::write(
&p,
"\u{1b}[31mFAIL\u{1b}[0m one\nok\n\u{1b}[31mFAIL\u{1b}[0m two\nok\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.open(&p).unwrap();
assert!(app.editor.log.is_some());
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
for ch in "FAIL".chars() {
app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
.unwrap();
}
assert_eq!(
app.editor_find.as_ref().map(|s| s.match_count),
Some(2),
"both FAIL lines are counted through the stripped text"
);
assert_eq!(
app.editor.active_search_match.map(|(r, _, _)| r),
Some(0),
"typing lands on the first match"
);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.active_search_match.map(|(r, _, _)| r),
Some(2),
"Enter steps to the second match rather than re-finding the first"
);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.active_search_match.map(|(r, _, _)| r),
Some(0),
"past the last match, Enter wraps to the top"
);
app.handle_key(key(KeyCode::Enter, KeyModifiers::SHIFT))
.unwrap();
assert_eq!(
app.editor.active_search_match.map(|(r, _, _)| r),
Some(2),
"Shift+Enter walks back, wrapping to the last match"
);
}
/// #257 review finding: the find bar's `N+` belonged to the log tab that
/// earned it and leaked onto the next search. A text buffer is counted
/// exhaustively, so showing `N+` there claims a limit that does not exist.
#[test]
fn a_logs_budgeted_count_does_not_leak_onto_the_next_text_search() {
let tmp = tempfile::tempdir().unwrap();
let log = tmp.path().join("huge.log");
// Past FIND_SCAN_BYTES, so the count genuinely runs out of budget.
let line = "\u{1b}[31mERROR\u{1b}[0m ".to_string() + &"pad ".repeat(40) + "\n";
let body = line.repeat((crate::log_view::FIND_SCAN_BYTES / line.len()) + 2000);
std::fs::write(&log, &body).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.open(&log).unwrap();
assert!(app.editor.log.is_some(), "the fixture must open rendered");
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
for ch in "ERROR".chars() {
app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
.unwrap();
}
assert!(
app.editor_find
.as_ref()
.is_some_and(|s| s.count_truncated()),
"a log too large to search whole must report its count as partial"
);
// Now search an ordinary file, which IS counted exhaustively. The find
// bar deliberately stays OPEN across the tab switch: closing it builds a
// fresh EditorFind on the next Cmd+F, and this test then passes against
// the very bug it exists to catch (round-2 review finding).
let text = tmp.path().join("small.txt");
std::fs::write(&text, "ERROR one\nplain\nERROR two\n").unwrap();
app.editor.open(&text).unwrap();
assert!(app.editor.log.is_none(), "a plain file is a text tab");
assert!(
app.editor_find.is_some(),
"the find bar must still be the one the log search left behind"
);
// Retype the query into the SAME bar rather than opening a new one.
app.editor_find.as_mut().unwrap().query.clear();
for ch in "ERROR".chars() {
app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
.unwrap();
}
let state = app.editor_find.as_ref().expect("the find bar is open");
assert_eq!(state.match_count, 2);
assert!(
!state.count_truncated(),
"an exhaustive count must not inherit the log's N+"
);
}
/// #257 round-3 review finding: a step that runs out of budget must leave
/// the user where they are. Marking the count partial and then clearing the
/// active match left the bar reading "1+ matches" with nothing highlighted
/// and no way back to the match they were on.
#[test]
fn a_step_that_runs_out_of_reach_keeps_the_match_it_already_had() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("far.log");
// One match at the very top, then far more filler than a sweep may read,
// so stepping forward from it exhausts the budget without finding another.
let mut body = String::from("\u{1b}[31mERROR\u{1b}[0m first and only\n");
let filler = "quiet line with nothing of interest ".repeat(4);
for _ in 0..(crate::log_view::FIND_SCAN_BYTES / filler.len() + 3000) {
body.push_str(&filler);
body.push('\n');
}
std::fs::write(&p, &body).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.open(&p).unwrap();
assert!(app.editor.log.is_some());
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
for ch in "ERROR".chars() {
app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
.unwrap();
}
assert_eq!(
app.editor.active_search_match.map(|(r, _, _)| r),
Some(0),
"typing lands on the only match"
);
// Enter steps forward, runs out of budget, and finds nothing more.
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.active_search_match.map(|(r, _, _)| r),
Some(0),
"an out-of-reach step must leave the highlight where it was, not \
clear it and leave the user with a count and nothing to look at"
);
assert!(
app.editor_find
.as_ref()
.is_some_and(|s| s.count_truncated()),
"and the bar must say the search did not cover the whole file"
);
}
/// #257 round-4 review finding: a CHANGED query must not leave the previous
/// query's highlight painted. The early return that keeps a match across an
/// out-of-reach STEP was also firing on the retype path, where the old
/// position belongs to a query the user has already replaced.
#[test]
fn retyping_into_an_out_of_reach_query_clears_the_old_highlight() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("far.log");
let mut body = String::from("\u{1b}[31mERROR\u{1b}[0m first and only\n");
let filler = "quiet line with nothing of interest ".repeat(4);
for _ in 0..(crate::log_view::FIND_SCAN_BYTES / filler.len() + 3000) {
body.push_str(&filler);
body.push('\n');
}
std::fs::write(&p, &body).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.open(&p).unwrap();
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
for ch in "ERROR".chars() {
app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
.unwrap();
}
assert_eq!(
app.editor.active_search_match.map(|(r, _, _)| r),
Some(0),
"the match is found while the query still matches"
);
// Extend the query into something that matches nothing reachable.
for ch in "ZZQX".chars() {
app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
.unwrap();
}
assert_eq!(
app.editor.active_search_match, None,
"the previous query's highlight must not survive under a new query \
that found nothing: the bar would say no match while a match stayed \
painted"
);
}
/// #257: dragging over a rendered ANSI log selects it, and Cmd+C copies what
/// the reader SEES rather than the escape bytes behind it.
///
/// Driven through the real gestures and a real render, so the body rect the
/// mouse path reads is the one a frame actually painted: a test that set
/// `last_body` by hand would pass with the renderer never having agreed.
#[test]
fn dragging_over_a_rendered_log_selects_and_copies_the_visible_text() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("run.log");
std::fs::write(
&p,
"\u{1b}[32mINFO\u{1b}[0m starting up\n\u{1b}[31mERROR\u{1b}[0m disk full\nbye\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.open(&p).unwrap();
assert!(app.editor.log.is_some(), "the fixture opens rendered");
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let body = app.editor.log.as_ref().unwrap().last_body;
assert!(
body.width > 0 && body.height > 0,
"the render must have published a body rect for the mouse to hit"
);
// Press on the first body row, drag to the second, release.
use crossterm::event::{MouseButton, MouseEventKind};
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
body.x,
body.y,
));
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
body.x + 10,
body.y + 1,
));
app.handle_mouse(mouse(
MouseEventKind::Up(MouseButton::Left),
body.x + 10,
body.y + 1,
));
let log = app.editor.log.as_ref().unwrap();
assert!(log.has_selection(), "the drag must leave a selection");
assert!(!log.dragging, "and the release must end the drag");
let (text, clamped) = log.selection_text();
assert!(!clamped);
assert_eq!(
text, "INFO starting up\nERROR disk",
"the copy is the stripped text, not the escapes behind it"
);
// What is PAINTED must match what is copied, row for row. Nothing
// asserted this before: deleting the entire selection-painting block from
// the renderer left the suite green, so the visible half of the feature
// had no coverage at all.
let mut buf = ratatui::buffer::Buffer::empty(ratatui::layout::Rect {
x: 0,
y: 0,
width: 100,
height: 30,
});
term.draw(|frame| app.render(frame)).unwrap();
{
use ratatui::widgets::Widget;
let area = app.editor.last_area;
(&mut app.editor).render(area, &mut buf);
}
// Frame truth: the rect the render that filled THIS buffer published.
let body = app.editor.log.as_ref().unwrap().last_body;
let selected_bg = crate::theme::Theme::BLACK.selection();
let copied_per_row: Vec<usize> = text.split('\n').map(|l| l.chars().count()).collect();
for (r, expected) in copied_per_row.iter().enumerate() {
let y = body.y + r as u16;
let painted = (body.x..body.x + body.width)
.filter(|x| buf[(*x, y)].style().bg == Some(selected_bg))
.count();
assert_eq!(
painted, *expected,
"row {r}: {painted} cells painted as selected, {expected} characters copied"
);
}
// Cmd+C puts exactly that on the clipboard.
app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER))
.unwrap();
assert!(
app.status.starts_with("Copied"),
"the copy must report itself, got {:?}",
app.status
);
}
/// #257: dragging past the end of a SHORT line must paint what it copies.
///
/// The renderer painted to the endpoint it was handed while the copy read
/// `min(len)`, and `log_cell_at` clamped the line but not the column, so a
/// drag off the right of a short line painted to the pointer and copied to
/// the line's end. Clamping at the source means both readers see one value
/// instead of each clamping its own way.
#[test]
fn dragging_past_a_short_lines_end_paints_what_it_copies() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("short.log");
// A coloured line so the view renders, and a very short one to drag off.
std::fs::write(&p, "\u{1b}[31mabc\u{1b}[0m\nlonger second line here\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.open(&p).unwrap();
assert!(app.editor.log.is_some());
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let body = app.editor.log.as_ref().unwrap().last_body;
use crossterm::event::{MouseButton, MouseEventKind};
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
body.x,
body.y,
));
// Drag far past the end of a three-character line.
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
body.x + 60,
body.y,
));
app.handle_mouse(mouse(
MouseEventKind::Up(MouseButton::Left),
body.x + 60,
body.y,
));
let (text, _) = app.editor.log.as_ref().unwrap().selection_text();
assert_eq!(text, "abc", "the copy stops at the end of the line");
let mut buf = ratatui::buffer::Buffer::empty(ratatui::layout::Rect {
x: 0,
y: 0,
width: 100,
height: 30,
});
term.draw(|frame| app.render(frame)).unwrap();
{
use ratatui::widgets::Widget;
let area = app.editor.last_area;
(&mut app.editor).render(area, &mut buf);
}
// Frame truth: the rect to read is the one the render that filled THIS
// buffer published, not one captured from an earlier frame. Reading the
// stale rect pointed at the header row and reported nothing painted.
let body = app.editor.log.as_ref().unwrap().last_body;
let selected_bg = crate::theme::Theme::BLACK.selection();
let painted = (body.x..body.x + body.width)
.filter(|x| buf[(*x, body.y)].style().bg == Some(selected_bg))
.count();
assert_eq!(
painted,
text.chars().count(),
"the paint must stop where the copy does, not follow the pointer"
);
}
/// #404: a double-width character occupies two cells, so every span after
/// it must be painted, and every click after it hit-tested, by display
/// width rather than by character count.
///
/// The painter advanced `x` by `chars().count()`, so after a CJK pair the
/// next span landed two cells to the left of where the terminal had put
/// the pair, overpainting its second half, and `log_cell_at` matched the
/// drift by design. Fixed together so the two never disagree.
#[test]
fn double_width_characters_keep_log_columns_aligned() {
use crossterm::event::{MouseButton, MouseEventKind};
use ratatui::widgets::Widget;
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("wide.log");
// "\u{4e2d}\u{6587}" is two characters and four cells; then a space and
// a coloured X, which must land on cell 5 (character column 3).
std::fs::write(
&p,
"\u{1b}[31m\u{4e2d}\u{6587}\u{1b}[0m \u{1b}[32mX\u{1b}[0m\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.open(&p).unwrap();
assert!(app.editor.log.is_some());
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let body = app.editor.log.as_ref().unwrap().last_body;
// Click the X and release on it: a one-character selection.
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
body.x + 5,
body.y,
));
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
body.x + 6,
body.y,
));
app.handle_mouse(mouse(
MouseEventKind::Up(MouseButton::Left),
body.x + 6,
body.y,
));
let (text, _) = app.editor.log.as_ref().unwrap().selection_text();
assert_eq!(text, "X", "cell 5 is the X, two cells past the wide pair");
let mut buf = ratatui::buffer::Buffer::empty(ratatui::layout::Rect {
x: 0,
y: 0,
width: 100,
height: 30,
});
term.draw(|frame| app.render(frame)).unwrap();
{
let area = app.editor.last_area;
(&mut app.editor).render(area, &mut buf);
}
let body = app.editor.log.as_ref().unwrap().last_body;
let row: Vec<&str> = (body.x..body.x + 7)
.map(|x| buf[(x, body.y)].symbol())
.collect();
assert_eq!(
buf[(body.x + 2, body.y)].symbol(),
"\u{6587}",
"the second wide character keeps its cells: {row:?}"
);
assert_eq!(
buf[(body.x + 5, body.y)].symbol(),
"X",
"the span after the pair starts where the terminal put it: {row:?}"
);
let selected_bg = crate::theme::Theme::BLACK.selection();
let painted: Vec<u16> = (body.x..body.x + body.width)
.filter(|x| buf[(*x, body.y)].style().bg == Some(selected_bg))
.collect();
assert_eq!(
painted,
vec![body.x + 5],
"the selection band sits on the X's cell, not on character column 3"
);
}
/// #404 review: a wide character whose first half lands on the body's last
/// cell does not fit whole, and `set_stringn` drops it entirely. The
/// selection band must not colour that cell, or the annotator paints where
/// the painter deliberately put nothing, the same disagreement the cell map
/// exists to close, at the boundary.
#[test]
fn a_wide_character_clipped_at_the_right_edge_gets_no_selection_band() {
use ratatui::layout::Rect;
use ratatui::widgets::Widget;
let tmp = tempfile::tempdir().unwrap();
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 8,
};
// Learn the body width from a probe render, so the fixture puts the
// wide character exactly on the last cell whatever the chrome costs.
let probe = tmp.path().join("probe.log");
std::fs::write(&probe, "\u{1b}[31mx\u{1b}[0m\n").unwrap();
let mut e = crate::widgets::editor::Editor::new();
e.open(&probe).unwrap();
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e).render(area, &mut buf);
let width = e.log.as_ref().unwrap().last_body.width as usize;
assert!(width > 2);
let p = tmp.path().join("edge.log");
let text = format!("{}\u{4e2d}", "x".repeat(width - 1));
std::fs::write(&p, format!("\u{1b}[31m{text}\u{1b}[0m\n")).unwrap();
let mut e = crate::widgets::editor::Editor::new();
e.open(&p).unwrap();
let chars = text.chars().count();
e.log.as_mut().unwrap().selection = Some(((0, 0), (0, chars)));
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e).render(area, &mut buf);
let body = e.log.as_ref().unwrap().last_body;
let last = body.x + body.width - 1;
let selected_bg = crate::theme::Theme::BLACK.selection();
assert_eq!(
buf[(last, body.y)].symbol(),
" ",
"the painter drops a wide character that does not fit whole"
);
assert_ne!(
buf[(last, body.y)].style().bg,
Some(selected_bg),
"so the band must not colour the cell it left blank"
);
assert_eq!(
buf[(last - 1, body.y)].style().bg,
Some(selected_bg),
"while the character before it is selected as usual"
);
}
/// #257: a frame that paints no log body must publish no body rect.
///
/// `render_log` returned early for a zero-sized area WITHOUT clearing
/// `last_body`, so after a resize the mouse path could accept a click inside
/// a rectangle this frame had not painted. Frame truth cuts both ways: the
/// rect is a claim about what was drawn, and drawing nothing is a claim too.
#[test]
fn a_log_that_paints_nothing_publishes_no_body_rect() {
use ratatui::layout::Rect;
use ratatui::widgets::Widget;
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("run.log");
std::fs::write(&p, "\u{1b}[31mERROR\u{1b}[0m boom\nsecond\n").unwrap();
let mut e = crate::widgets::editor::Editor::new();
e.open(&p).unwrap();
// A real frame publishes a real rect.
let mut buf = ratatui::buffer::Buffer::empty(Rect {
x: 0,
y: 0,
width: 40,
height: 8,
});
(&mut e).render(
Rect {
x: 0,
y: 0,
width: 40,
height: 8,
},
&mut buf,
);
assert!(
e.log.as_ref().unwrap().last_body.height > 0,
"a painted frame publishes its body"
);
// A frame with no room paints nothing, so it must claim nothing.
let mut narrow = ratatui::buffer::Buffer::empty(Rect {
x: 0,
y: 0,
width: 40,
height: 8,
});
(&mut e).render(
Rect {
x: 0,
y: 0,
width: 0,
height: 0,
},
&mut narrow,
);
assert_eq!(
e.log.as_ref().unwrap().last_body,
Rect::default(),
"a frame that painted nothing must not leave a stale rect for the \
mouse path to hit-test against"
);
}
/// #257 follow-up: the find bar's title must FIT the bar.
///
/// The truncated-count arm shipped at 51 characters in a bar capped at 48
/// and painted as "...in the part that could be searc". Nothing rendered the
/// title, so nothing could catch it, and the replacement is protected only
/// by arithmetic no one re-runs. This renders every arm at the real width.
#[test]
fn every_find_bar_title_fits_the_bar_it_is_painted_in() {
use crate::widgets::editor_find::{EditorFind, render_editor_find};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 12,
};
let opts = crate::widgets::search::SearchOpts::default();
// Every arm of the title match, with the WHOLE title it must paint, and
// how to reach it. `match_index` matters as much as the count: the
// "N of M" arm is reached ONLY when it is Some, and `set_match_count`
// does not touch it, so the first version of this test never rendered
// that arm at all while claiming in its name to cover every one. It is
// also the arm whose width grows with TWO runtime numbers, which makes
// it the most able to overrun the bar.
//
// The expected string is the ENTIRE title, never a fragment of it. A
// fragment cannot detect an overrun: text added BEFORE the fragment
// pushes the tail off the end while leaving the fragment itself intact,
// so `contains` still passes. Measured rather than reasoned: against the
// fragment "9876543 of 9876543+", widening that arm to
// " Find - match {idx} of {total} found in this whole file " (59 cells
// painted into a 48-cell bar) left this test green. Only the full title
// makes the clip observable, because the clip removes its end.
//
// Written out rather than rebuilt from the code's own format strings on
// purpose: sharing the construction with the code under test would make
// any widening agree with itself and pass.
/// A title arm: the whole title it must paint, and how to reach it.
type TitleCase = (&'static str, Box<dyn Fn(&mut EditorFind)>);
let cases: Vec<TitleCase> = vec![
// The empty-query arm is the BARE title, and it is asserted whole
// for the same reason as the rest: every other arm also contains
// "Find", so a fragment could not tell this arm from a wrong one.
(" Find ", Box::new(|s: &mut EditorFind| s.query.clear())),
(
" Find — No results ",
Box::new(|s: &mut EditorFind| s.set_match_count(0, false)),
),
(
" Find: no match in the part searched ",
Box::new(|s: &mut EditorFind| s.set_match_count(0, true)),
),
(
" Find — 1234 matches ",
Box::new(|s: &mut EditorFind| s.set_match_count(1234, false)),
),
(
" Find — 1234+ matches ",
Box::new(|s: &mut EditorFind| s.set_match_count(1234, true)),
),
(
" Find — 7 of 1234 ",
Box::new(|s: &mut EditorFind| {
s.set_match_count(1234, false);
s.match_index = Some(7);
}),
),
(
" Find — 9876543 of 9876543+ ",
Box::new(|s: &mut EditorFind| {
// Both numbers as wide as they plausibly get on a log, since
// this arm's length grows with each independently.
s.set_match_count(9_876_543, true);
s.match_index = Some(9_876_543);
}),
),
];
for (expected, prepare) in cases {
let mut state = EditorFind::new(String::from("needle"), opts);
prepare(&mut state);
let mut buf = Buffer::empty(area);
render_editor_find(&mut state, area, &mut buf, crate::theme::Theme::BLACK);
let rect = state.last_rect;
assert!(rect.width > 0, "the bar must have been painted");
let row: String = (rect.x..rect.x + rect.width)
.map(|x| buf[(x, rect.y)].symbol().to_string())
.collect();
// THE BAR'S TITLE AREA, not the buffer. Two renderers paint this
// title and they clip differently: `Block` clips to its own title
// area (`rect.width - 2`), while the gradient re-stamp in
// `render_editor_find` uses `set_span`, whose clamp is the BUFFER's
// right edge. `Theme::BLACK.gradient()` is true, so the second one
// runs, and a title between 38 and 47 cells overruns the block
// silently: it writes over the bar's own top-right corner and out
// past the inner area, while a comparison anchored to the painted
// row still matches, because the overrun is exactly the text the
// comparison wanted. The width assertion is what makes that visible.
assert!(
expected.chars().count() <= (rect.width as usize).saturating_sub(2),
"the {}-cell title does not fit a {}-cell bar's title area",
expected.chars().count(),
rect.width
);
// Exactly, at the position the block paints it: one cell in from
// the left corner. `contains` would be weaker in both directions -
// it cannot see a clipped tail when the wanted text is a fragment,
// and for the bare " Find " arm every other title contains it too,
// so a completely wrong title would satisfy it.
let painted: String = row.chars().skip(1).take(expected.chars().count()).collect();
assert_eq!(
painted, expected,
"the title did not fit whole in a {}-cell bar, the row painted {row:?}",
rect.width
);
// And the bar is still a bar. The corner is the first thing an
// overrunning title destroys, so it is the cheapest witness that the
// title stayed inside the box it was painted in.
assert_eq!(
buf[(rect.x + rect.width - 1, rect.y)].symbol(),
"\u{256e}",
"the title overran the bar and ate its top-right corner: {row:?}"
);
}
}
/// #257 follow-up: the count and the highlight must agree at every step of
/// a search over a budgeted log.
///
/// Rounds 3, 4 and 5 of #393 each found one instance of a single class: the
/// bar's count and the painted highlight disagreeing. This walks the whole
/// gesture sequence and asserts the exact state after each one: type, step
/// forward into the out-of-reach branch (where round 3's defect lived),
/// step back, retype into a query that matches nothing, delete back.
///
/// NO SEPARATE INVARIANT HELPER, deliberately. An earlier version carried a
/// closure asserting `match_count == 0 => active_search_match.is_none()` at
/// each checkpoint, which reads as the general property behind the three
/// defects. It could not fail: `match_count == 0` holds at exactly one
/// checkpoint, and there the concrete assertion already fixes the highlight
/// to `None`, which is strictly stronger. Neutering the closure entirely
/// left the test green. Extending it over a prefix walk did not help either,
/// because the code has no per-length behaviour, so every state the walk
/// visits is behaviourally identical to one already enumerated.
///
/// A dead assertion whose name announces a property is worse than no
/// assertion: it makes a reader believe the class is covered. The concrete
/// assertions ARE the property, made checkable one state at a time.
///
/// HALF A PAIR. These pin `count == 0` with nothing painted. The other
/// direction, a count that survives while the highlight is thrown away, is
/// pinned by `a_step_that_runs_out_of_reach_keeps_the_match_it_already_had`.
///
/// WHICH CHECKPOINTS ARE NEW. Three of them re-assert what
/// `a_step_that_runs_out_of_reach_keeps_the_match_it_already_had` and
/// `retyping_into_an_out_of_reach_query_clears_the_old_highlight` already
/// cover; they are carried along because this test's subject is the
/// SEQUENCE, and a state is only reached by passing through them. The two
/// that no sibling covers are the backward step and the final backspace
/// into a query that matches again. A reader counting five independent
/// facts here would be counting wrong.
///
/// TWO REACHABLE MATCHES, not one. With a single match the Shift+Enter
/// checkpoint asserted nothing: `find_prev`'s leg 1 rejects the anchor's own
/// match, leg 2 walks back from EOF and runs out of budget before reaching
/// row 0, and `scroll_log_to_match` returns on `out_of_reach` WITHOUT
/// touching `active_search_match`. The assertion passed because the field
/// was never written. Measured: making `find_prev` return
/// `Found(row 0, col 999, len 5)` unconditionally left the test green. A
/// second match on row 1 puts a real backward step within budget, so the
/// checkpoint now fails if `find_prev`'s anchor filter or its column
/// arithmetic regresses.
#[test]
fn the_count_and_the_highlight_agree_at_every_step_of_a_log_search() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("budgeted.log");
// TWO matches at the head, both inside the budget, so a backward step
// has somewhere to land. Row 1 puts ERROR at character column 3, which
// makes a wrong column visible rather than coincidentally right.
let mut body = String::from("\u{1b}[31mERROR\u{1b}[0m first\n");
body.push_str("no \u{1b}[31mERROR\u{1b}[0m second\n");
let filler = "quiet line with nothing of interest ".repeat(4);
// Comfortably past the budget, matching the margin the sibling tests use
// (+3000 lines, ~11%). The earlier +200 was 1.4% over, and while the
// budget is a pure byte counter with no timing in it, a change to window
// accounting or to the stripped length of the colour header could flip
// the sweep from OutOfReach to Absent and quietly change what four
// assertions mean without any of them failing.
for _ in 0..(crate::log_view::FIND_SCAN_BYTES / filler.len() + 3000) {
body.push_str(&filler);
body.push('\n');
}
std::fs::write(&p, &body).unwrap();
assert!(
body.len() > crate::log_view::FIND_SCAN_BYTES,
"the fixture must outrun the sweep budget or the out-of-reach \
checkpoints test nothing"
);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.open(&p).unwrap();
assert!(app.editor.log.is_some(), "the fixture opens rendered");
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
for ch in "ERROR".chars() {
app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
.unwrap();
}
// The WHOLE tuple, not just the row. A wrong column or length paints the
// band in the wrong place, which is the defect class this test is for,
// and comparing only the row cannot see it.
assert_eq!(
app.editor.active_search_match,
Some((0, 0, 5)),
"typing lands on the first match, at its own column"
);
assert_eq!(
app.editor_find.as_ref().unwrap().match_count,
2,
"both head matches are counted, not merely some"
);
// Forward to the SECOND match, which is within budget, so this leg
// asserts a real step rather than a refusal.
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.active_search_match,
Some((1, 3, 5)),
"the next match is row 1 at column 3, past the \"no \" prefix"
);
// Forward again: nothing further is reachable, so this exercises the
// out-of-reach branch, which is where round 3's defect lived.
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.active_search_match,
Some((1, 3, 5)),
"a step that cannot reach further keeps the match it had"
);
assert!(
app.editor_find.as_ref().unwrap().count_truncated(),
"and the bar reports that the search did not cover the file"
);
// Backward from row 1 to row 0: within budget, so `find_prev`'s leg 1
// answers and its result is actually consumed. With one match this leg
// ran out of budget and `scroll_log_to_match` returned without writing
// anything, so the assertion passed on an untouched field.
app.handle_key(key(KeyCode::Enter, KeyModifiers::SHIFT))
.unwrap();
assert_eq!(
app.editor.active_search_match,
Some((0, 0, 5)),
"stepping back lands on the previous match, not on the current one"
);
// Only now retype into something unmatchable, so the transition from a
// painted match to none is itself a checkpoint.
for ch in "ZZQX".chars() {
app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
.unwrap();
}
assert_eq!(
app.editor_find.as_ref().unwrap().match_count,
0,
"the new query matches nothing"
);
assert_eq!(
app.editor.active_search_match, None,
"so nothing may stay painted"
);
// And back: the highlight must return rather than staying cleared.
for _ in 0..4 {
app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
.unwrap();
}
assert_eq!(
app.editor.active_search_match,
Some((0, 0, 5)),
"a query that matches again must paint its match, whole"
);
}
/// #414: a dropped `file://` URL naming a non-ASCII path must decode to that
/// path, not to one char per byte.
///
/// The decoder pushed each `%xx` byte, and each literal byte, `as char`,
/// which maps a byte to the Latin-1 code point of the same value, so every
/// multi-byte UTF-8 sequence came out as mojibake and the drop opened a
/// path that does not exist. The same defect class as #396, in the drop
/// path.
#[test]
fn a_dropped_file_url_with_a_non_ascii_path_decodes_to_utf8() {
use std::path::PathBuf;
assert_eq!(
super::normalise_dropped_token("file:///tmp/caf%C3%A9/%E4%B8%AD%E6%96%87.txt"),
Some(PathBuf::from("/tmp/caf\u{e9}/\u{4e2d}\u{6587}.txt")),
"percent-encoded UTF-8 reassembles into the characters it encodes"
);
assert_eq!(
super::normalise_dropped_token("file:///tmp/caf\u{e9}"),
Some(PathBuf::from("/tmp/caf\u{e9}")),
"a literal non-ASCII character in the URL survives too"
);
// The ASCII cases the decoder always handled are unchanged.
assert_eq!(
super::normalise_dropped_token("file:///tmp/a%20b"),
Some(PathBuf::from("/tmp/a b"))
);
assert_eq!(
super::normalise_dropped_token("'/tmp/x y'"),
Some(PathBuf::from("/tmp/x y"))
);
// `+` is not a space in a file URL (form encoding does not apply), and a
// `%` that is not an escape passes through literally, wherever it sits.
for (url, want) in [
("file:///tmp/a+b", "/tmp/a+b"),
("file:///tmp/a%zzb", "/tmp/a%zzb"),
("file:///tmp/a%2", "/tmp/a%2"),
("file:///tmp/a%", "/tmp/a%"),
] {
assert_eq!(
super::normalise_dropped_token(url),
Some(PathBuf::from(want)),
"{url}"
);
}
}
/// A `file://` URL whose escapes do not form valid UTF-8 names no path this
/// process can open. The decoder used to read each byte as Latin-1 and open
/// the wrong path; a lossy decode would instead open a path with U+FFFD in
/// it, which is just as wrong and passes every "is this a path" screen. The
/// function's contract is to drop what is not a plausible path, so it does.
#[test]
fn a_dropped_file_url_with_invalid_utf8_is_dropped() {
assert_eq!(super::normalise_dropped_token("file:///tmp/%FF"), None);
assert_eq!(
super::normalise_dropped_token("file:///tmp/%C3"),
None,
"a truncated multi-byte lead is not a path either"
);
}
/// #352: a workspace's `.vscode/extensions.json` recommendations appear in the
/// Extensions panel under FROM VS CODE with what croft has for each.
#[test]
fn workspace_extension_recommendations_show_under_from_vscode() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join(".vscode")).unwrap();
std::fs::write(
tmp.path().join(".vscode").join("extensions.json"),
r#"{ "recommendations": ["rust-lang.rust-analyzer", "nobody.nothing"] }"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.refresh_extensions();
let ids: Vec<String> = app
.extensions
.items()
.iter()
.filter(|i| i.vscode)
.map(|i| i.id.clone())
.collect();
assert_eq!(ids, ["rust-lang.rust-analyzer", "nobody.nothing"]);
// Toggling a built-in row is an answer, not an install: the status names
// the extension and what croft has for it, and nothing is disabled.
let visible = app.extensions.visible_indices();
let pos = visible
.iter()
.position(|&i| app.extensions.items()[i].id == "rust-lang.rust-analyzer")
.expect("the row is visible");
app.extensions.select(pos);
let before = app.disabled_extensions.clone();
app.toggle_selected_extension();
assert!(
app.status
.starts_with("rust-lang.rust-analyzer: built in: lsp-rust"),
"the status restates the row: {}",
app.status
);
assert_eq!(app.disabled_extensions, before, "nothing was toggled");
}
/// #344: a pane whose foreground process is a coding agent is badged, its
/// status is read off the screen once it goes quiet, and the `Waiting`
/// transition fires exactly once per prompt. The fake agent is a shell that
/// prints a permission question and then sits; the sample names it `claude`
/// the way the label sampler would.
#[test]
fn an_agent_pane_is_badged_and_a_prompt_fires_waiting_once() {
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 'Edited src/main.rs\\nDo you want to proceed? (y/n)\\n'; sleep 30",
),
],
tmp.path(),
)
.unwrap();
let shell_pid = app.terminals[0]
.shell_pid()
.expect("a running pane has a pid");
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the fake agent to paint its prompt",
|| app.terminals[0].visible_text().contains("proceed"),
);
let zero = std::time::Duration::ZERO;
// First sample: seated straight into a prompt.
let samples = vec![(shell_pid, String::from("claude"))];
assert!(app.apply_agent_samples(&samples, zero), "the lane changed");
let lane = app.terminals[0].agent().cloned().expect("badged");
assert_eq!(lane.name, "claude");
assert_eq!(lane.status, crate::agents::AgentStatus::Waiting);
assert!(app.drain_agent_events(), "a waiting agent is announced");
assert!(
app.status.contains("claude") && app.status.contains("waiting"),
"{}",
app.status
);
assert_eq!(app.agent_counts(), (1, 1));
// The same prompt on the next sample: no second Waiting.
app.status.clear();
assert!(!app.apply_agent_samples(&samples, zero), "nothing changed");
assert!(!app.drain_agent_events(), "the prompt fires once");
assert!(app.status.is_empty());
// The pill wears the badge and the chip counts it.
let backend = ratatui::backend::TestBackend::new(120, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
app.split_terminal().unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let buf = term.backend().buffer().clone();
let text: String = (0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n");
assert!(
text.contains("\u{25c6} claude \u{25d0}"),
"the pill wears the badge:\n{text}"
);
assert!(
text.contains("1 agent \u{b7} 1 waiting"),
"the chip counts it:\n{text}"
);
assert!(app.status_agents_rect.width > 0, "and is clickable");
// Clicking the chip from the editor with the panel collapsed reveals
// the pane, not just focuses it.
app.show_terminal = false;
app.focus_pane(Pane::Editor);
term.draw(|frame| app.render(frame)).unwrap();
let chip = app.status_agents_rect;
assert!(
chip.width > 0,
"the chip is painted while the panel is hidden"
);
app.handle_mouse(mouse(
crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
chip.x,
chip.y,
));
assert!(app.show_terminal, "the click reveals the panel");
assert!(matches!(app.focus, Pane::Terminal), "and focuses the pane");
// The agent leaving the foreground unseats it: the shell reclaiming the
// pane is one way, and a pane that produced no sample at all (the agent
// took the shell with it, or the pid was missed) is the other.
let gone = vec![(shell_pid, String::from("zsh"))];
assert!(app.apply_agent_samples(&gone, zero));
assert!(app.terminals[0].agent().is_none());
assert_eq!(app.agent_counts(), (0, 0));
assert!(app.apply_agent_samples(&samples, zero), "re-seated");
assert!(app.apply_agent_samples(&[], zero), "no sample unseats");
assert!(app.terminals[0].agent().is_none());
assert!(
matches!(
app.agent_events.back(),
Some(crate::agents::AgentEvent::Gone { .. })
),
"and says so: {:?}",
app.agent_events
);
// A pane that has not output yet is quiet since it spawned, not since
// 1970, so a just-launched agent reads as working.
let fresh = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from("sleep 30")],
tmp.path(),
)
.unwrap();
assert!(
fresh.quiet_for() < std::time::Duration::from_secs(5),
"quiet for {:?}",
fresh.quiet_for()
);
}
/// #394: a log past the head budget opens on a partial index, the header
/// says so, and the main loop's `poll_log_index` grows it to the total and
/// re-runs an open find's count once the pass is done.
#[test]
fn a_large_log_opens_before_its_index_is_complete_and_the_loop_finishes_it() {
let tmp = tempfile::tempdir().unwrap();
use ratatui::widgets::Widget as _;
let p = tmp.path().join("huge.log");
let mut body = Vec::new();
body.extend_from_slice(b"\x1b[32mINFO\x1b[0m head\n");
let mut lines = 1usize;
while (body.len() as u64) < crate::log_view::HEAD_INDEX_BYTES + 1024 * 1024 {
body.extend_from_slice(format!("line{lines} some padding text\n").as_bytes());
lines += 1;
}
body.extend_from_slice(b"\x1b[31mERROR\x1b[0m disk full\n");
let total = lines + 1;
std::fs::write(&p, &body).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.open(&p).unwrap();
let log = app.editor.log.as_ref().expect("opens as a rendered log");
assert!(log.indexing(), "the tail is still being indexed after open");
assert!(log.len() < total, "the count is a lower bound for now");
let area = Rect::new(0, 0, 80, 12);
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut *app.editor).render(area, &mut buf);
// The header sits on the row above the body the frame published; the
// editor's own border occupies row 0.
let body = app.editor.log.as_ref().unwrap().last_body;
let header: String = (body.x..body.x + body.width)
.map(|x| buf[(x, body.y - 1)].symbol().to_string())
.collect();
assert!(
header.contains("so far, indexing"),
"the header must not present a moving count as a total: {header:?}"
);
// A find typed while the pass runs: the ERROR line is past the index.
app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
.unwrap();
for ch in "disk".chars() {
app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
.unwrap();
}
let state = app.editor_find.as_ref().unwrap();
assert!(
state.count_truncated(),
"a count taken against a partial index is flagged partial"
);
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"the background log index",
|| {
app.poll_log_index();
!app.editor.log.as_ref().unwrap().indexing()
},
);
assert_eq!(app.editor.log.as_ref().unwrap().len(), total);
(&mut *app.editor).render(area, &mut buf);
// The header sits on the row above the body the frame published; the
// editor's own border occupies row 0.
let body = app.editor.log.as_ref().unwrap().last_body;
let header: String = (body.x..body.x + body.width)
.map(|x| buf[(x, body.y - 1)].symbol().to_string())
.collect();
assert!(
header.contains(&format!("{total} lines ")) && !header.contains("indexing"),
"the finished header carries the total: {header:?}"
);
assert!(
!app.poll_log_index(),
"a finished index asks for no more repaints"
);
}
/// #374: Fix with Navigator from PROBLEMS. With no navigator seated the
/// action lands on the diagnostic and says the navigator is not active
/// rather than doing nothing; the caret-side entry points resolve the
/// diagnostic under the caret with its server as the source; the palette
/// carries the command; and the Quick Fix picker offers the navigator row
/// after the server's own actions.
#[test]
fn fix_with_navigator_lands_on_the_diagnostic_and_refuses_without_a_seat() {
use crate::lsp::manager::DiagnosticSeverity;
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("a.rs");
std::fs::write(&file, "use std::io;\nfn main() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
let mut by_server = std::collections::HashMap::new();
by_server.insert(
String::from("rust-analyzer"),
vec![crate::lsp::manager::Diagnostic {
start_line: 0,
start_char: 4,
end_line: 0,
end_char: 11,
severity: DiagnosticSeverity::Warning,
message: String::from("unused import: `std::io`"),
}],
);
app.lsp_diagnostics.insert(file.clone(), by_server);
assert!(app.drain_lsp_diagnostics());
assert!(app.rebuild_problems());
let (path, item) = {
let groups = app.problems.groups();
(groups[0].path.clone(), groups[0].items[0].clone())
};
assert_eq!(item.source, "rust-analyzer");
// Move the caret away, then fix: with no navigator the action refuses
// up front and has no side effect, so the caret stays where it was
// rather than jumping to a diagnostic nothing is going to fix.
app.editor.cursor_row = 1;
app.fix_problem_with_navigator(path.clone(), item.clone(), Vec::new());
assert!(
app.status.to_lowercase().contains("not active"),
"{}",
app.status
);
assert_eq!(app.editor.path.as_deref(), Some(file.as_path()));
assert_eq!(app.editor.cursor_row, 1, "a refusal moves nothing");
assert!(
app.problems.fixing.is_none(),
"no turn was sent, so no spinner"
);
app.editor.cursor_row = 0;
// The caret-side candidate is the same diagnostic, with its server.
let (cpath, citem) = app
.navigator_fix_candidate()
.expect("the caret sits on a diagnostic");
assert_eq!(cpath, file);
assert_eq!(citem.message, item.message);
assert_eq!(citem.source, "rust-analyzer");
assert!(citem.col_utf16);
app.editor.cursor_row = 1;
assert!(
app.navigator_fix_candidate().is_none(),
"no diagnostic on the second line"
);
app.editor.cursor_row = 0;
// The Quick Fix picker: server actions first, the navigator row last.
app.open_code_action_picker(vec![crate::lsp::manager::CodeActionItem {
title: String::from("Remove unused import"),
server: String::from("rust-analyzer"),
edits: Vec::new(),
command: None,
needs_resolve: false,
resolve_action: None,
is_preferred: false,
}]);
let picker = app.list_picker.as_ref().expect("the picker opened");
let labels: Vec<String> = picker.rows.iter().map(|r| r.label.clone()).collect();
assert_eq!(labels, vec!["Remove unused import", "Fix with Navigator"]);
assert_eq!(picker.rows[1].id, "navigator");
// Confirming the navigator row must route to the navigator, never to
// the server's first action: the picker's shared numeric-id decode
// parses "navigator" to 0 (#374 review, the blocker).
if let Some(picker) = app.list_picker.as_mut() {
picker.select_next();
assert_eq!(picker.selected_row().unwrap().id, "navigator");
}
app.status.clear();
app.confirm_list_picker();
assert!(
app.status.to_lowercase().contains("not active"),
"the navigator row reached the navigator path: {}",
app.status
);
assert_eq!(
app.editor.lines.join("\n"),
"use std::io;\nfn main() {}",
"and no server action touched the buffer"
);
// The control: the server row still applies the server action.
app.open_code_action_picker(vec![crate::lsp::manager::CodeActionItem {
title: String::from("Remove unused import"),
server: String::from("rust-analyzer"),
edits: Vec::new(),
command: None,
needs_resolve: false,
resolve_action: None,
is_preferred: false,
}]);
app.status.clear();
app.confirm_list_picker();
assert!(
!app.status.to_lowercase().contains("not active"),
"row 0 is the server's, not the navigator's: {}",
app.status
);
// Deactivating the seat clears the marker (#374 review): with the
// navigator gone no TurnDone can arrive, so the unseat path is the
// only thing standing between the row and an eternal spinner.
app.problems.fixing = Some((file.clone(), 0));
app.problems_fix_started = Some(std::time::Instant::now());
app.last_pair_check = None;
app.maybe_seat_navigator();
assert!(
app.problems.fixing.is_none(),
"the deactivation teardown clears the fix marker"
);
assert_eq!(app.problems_fix_spinner_phase(), 0);
// The palette carries the command; the menu entry has no chord.
assert!(
crate::widgets::command_palette::ALL_COMMANDS
.contains(&crate::widgets::command_palette::Command::FixProblemWithNavigator)
);
assert_eq!(
crate::widgets::command_palette::Command::FixProblemWithNavigator.id(),
"problems_fix_navigator"
);
assert_eq!(
shortcut_for(&MenuAction::FixProblemWithNavigator {
path: path.clone(),
item: item.clone()
}),
None
);
// The spinner stops with the turn, however it ended (#374): the same
// clear runs on TurnDone, on the seat dying, and on unseat.
app.problems.fixing = Some((path, item.line));
app.problems_fix_started = Some(std::time::Instant::now());
assert!(app.problems_fix_spinner_phase() < 100);
app.clear_problem_fix();
assert!(app.problems.fixing.is_none());
assert_eq!(
app.problems_fix_spinner_phase(),
0,
"idle never wakes the renderer"
);
}
/// #370: a `.http` file runs the request under the caret. The variables
/// substitute from `.http.env.json` on the WIRE only: the status line,
/// history entry, and response tab all carry the raw `{{name}}` form, so
/// the token never leaves the env file. A JSON response opens pretty-printed
/// as `.jsonc`; a PNG response opens through the image path.
#[test]
fn an_http_file_runs_requests_and_keeps_secrets_out_of_history_and_the_tab() {
use std::io::{Read as _, Write as _};
let tmp = tempfile::tempdir().unwrap();
// The cache-dir override is a process-wide global shared with the relay
// family: hold their lock and restore via RAII, exactly as
// `with_relay_home` does, so a panic cannot leak the redirect into
// later tests (#428 review).
struct RestoreCacheDir;
impl Drop for RestoreCacheDir {
fn drop(&mut self) {
*CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = None;
}
}
let _cache_lock = relay_test_lock().lock().unwrap();
let _restore = RestoreCacheDir;
*CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = Some(tmp.path().join("cache"));
// A 1x1 PNG via the image crate, so the decode on open genuinely works.
let png_bytes = {
let img: image::RgbaImage = image::ImageBuffer::from_pixel(1, 1, image::Rgba([0, 0, 0, 0]));
let mut buf: Vec<u8> = Vec::new();
image::DynamicImage::ImageRgba8(img)
.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
.unwrap();
buf
};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let seen2 = seen.clone();
let png_served = png_bytes.clone();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut s) = stream else { break };
let mut buf = vec![0u8; 8192];
let n = s.read(&mut buf).unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..n]).to_string();
let (body, ct): (Vec<u8>, &str) = if req.starts_with("GET /users") {
(
b"{\"users\":[{\"id\":1,\"name\":\"ada\"}]}".to_vec(),
"application/json",
)
} else {
(png_served.clone(), "image/png")
};
seen2.lock().unwrap().push(req);
let head = format!(
"HTTP/1.1 200 OK\r\ncontent-type: {ct}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
body.len()
);
let _ = s.write_all(head.as_bytes());
let _ = s.write_all(&body);
let _ = s.shutdown(std::net::Shutdown::Both);
}
});
let http = tmp.path().join("api.http");
std::fs::write(
&http,
"GET {{host}}/users\nAuthorization: Bearer {{token}}\n\n###\nGET {{host}}/logo.png\n",
)
.unwrap();
std::fs::write(
tmp.path().join(crate::http_file::ENV_FILE),
format!("{{\"host\": \"http://127.0.0.1:{port}\", \"token\": \"super-secret-token\"}}"),
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&http).unwrap();
app.editor.cursor_row = 1;
app.send_http_request_under_caret();
assert!(
app.status.starts_with("Sending GET {{host}}/users"),
"the status carries the RAW line: {}",
app.status
);
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"the HTTP response",
|| {
app.drain_http_responses();
app.http_run.is_none()
},
);
let opened = app.editor.path.clone().expect("a response tab opened");
assert_eq!(opened.extension().and_then(|e| e.to_str()), Some("jsonc"));
let doc = app.editor.lines.join("\n");
assert!(
doc.contains("// GET {{host}}/users \u{2192} HTTP/1.1 200 OK"),
"{doc}"
);
assert!(doc.contains("\"users\": ["), "pretty-printed: {doc}");
assert!(
!doc.contains("super-secret-token"),
"the token never reaches the tab"
);
assert!(
seen.lock().unwrap()[0].contains("Bearer super-secret-token"),
"but the wire DID carry the substituted value"
);
let hits = app.command_history.search(
"http GET",
crate::command_history::HistoryScope::All,
"",
"",
);
assert_eq!(
hits[0].cmd, "http GET {{host}}/users",
"history keeps the raw line"
);
assert_eq!(hits[0].exit, Some(200));
assert!(!hits[0].cmd.contains("super-secret-token"));
// The PNG block renders through the image path.
app.editor.open_pinned(&http).unwrap();
app.editor.cursor_row = 4;
app.send_http_request_under_caret();
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"the PNG response",
|| {
app.drain_http_responses();
app.http_run.is_none()
},
);
assert!(
app.editor.image.is_some(),
"a PNG response opens as an image, not bytes in a text tab: {:?}",
app.editor.path
);
// A second send while one is in flight is refused and clobbers
// nothing; a worker that died reports itself on the next drain.
let (dummy_tx, dummy_rx) = std::sync::mpsc::channel();
app.http_run = Some(dummy_rx);
app.editor.open_pinned(&http).unwrap();
app.editor.cursor_row = 0;
app.send_http_request_under_caret();
assert_eq!(app.status, "An HTTP request is already in flight");
drop(dummy_tx);
assert!(app.drain_http_responses());
assert!(app.status.contains("worker died"), "{}", app.status);
assert!(app.http_run.is_none());
// A transport failure must NOT leak a substituted secret into the
// status line: ureq's error Display opens with the resolved URL, so
// only its kind may be shown (#428 review). The port is bound then
// dropped, so the connection is refused at once.
let dead_port = {
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
l.local_addr().unwrap().port()
};
std::fs::write(
tmp.path().join(crate::http_file::ENV_FILE),
format!(
"{{\"host\": \"http://127.0.0.1:{dead_port}\", \"token\": \"super-secret-token\"}}"
),
)
.unwrap();
let secret_url = tmp.path().join("leak.http");
std::fs::write(&secret_url, "GET {{host}}/x?api_key={{token}}\n").unwrap();
app.editor.open_pinned(&secret_url).unwrap();
app.editor.cursor_row = 0;
app.send_http_request_under_caret();
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"the refused connection",
|| {
app.drain_http_responses();
app.http_run.is_none()
},
);
assert!(
app.status.contains("failed"),
"a transport failure is reported: {}",
app.status
);
assert!(
!app.status.contains("super-secret-token"),
"the substituted URL never reaches the status line: {}",
app.status
);
let hits =
app.command_history
.search("api_key", crate::command_history::HistoryScope::All, "", "");
assert_eq!(hits[0].exit, None, "a failed run records no status code");
assert!(!hits[0].cmd.contains("super-secret-token"));
app.editor.open_pinned(&http).unwrap();
// A hole with no value refuses to send rather than leaking the hole.
app.editor.open_pinned(&http).unwrap();
std::fs::remove_file(tmp.path().join(crate::http_file::ENV_FILE)).unwrap();
app.editor.cursor_row = 0;
app.send_http_request_under_caret();
assert!(
app.status.contains("no value for {{host}}, {{token}}"),
"{}",
app.status
);
assert!(app.http_run.is_none(), "nothing was sent");
}
/// #356: a recorded frame carries the VISIBLE screen, not the scrollback.
///
/// `grid_lines` starts at `topmost_line()`, which is negative scrollback —
/// up to 5000 rows. Writing all of it after a clear scrolls the live screen
/// straight off the top, so the cast shows the tail of the history rather
/// than what the user was looking at, at roughly 400 KB per frame. A test
/// that only counts event kinds cannot see either half of that.
#[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,
};
// `resize`, not a `CSI 8 ; rows ; cols t` feed: the emulator leaves that
// sequence unhandled, so the grid kept the 80x24 it was spawned with while
// `last_inner` said 40x6, and the recorded frame carried 24 rows under a
// header announcing 6. Every assertion below still passed, because they
// read the same `grid_lines` the recorder does: a fixture can be wrong
// about itself while everything asserted on it holds.
//
// 20 rows, and the number answers two failures at once rather than
// trading one for the other.
//
// `line-199` sits one row above the bottom at EVERY height, because the
// flood ends on a newline. What the height sets is the eviction budget:
// how many rows the pane's live shell may print before the frame is
// recorded. `resize` writes through to the pty master, so that shell
// takes a SIGWINCH the old escape-sequence feed never sent, and it is a
// login shell running the developer's own rc - a wrapped prompt and a
// banner are ordinary. At 6 the budget was five rows, which is inside
// that range; at 12 it was eleven, which is nearer than it needs to be.
//
// The other constraint is only that the height DIFFER from the 24 a pane
// is spawned at, or the header assertion below cannot fail: restore the
// unhandled escape sequence at 24 and every assertion here passes. 20
// satisfies both - 19 rows of budget, and the control still fires.
//
// A third way the height matters, worth writing down because it is not
// obvious: the scrollback guard rejects a last-N-rows recorder by
// arithmetic on this number, not structurally. At `resize(40, 64)` a
// recorder writing the last 64 rows would satisfy every assertion here,
// because 64 would then BE the screen. The row-order assertion below is
// the one check that does not depend on the height.
app.terminals[0].resize(40, 20);
// Far more output than the screen holds, so most of it is scrollback.
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");
// The geometry a player is handed, taken from the FILE rather than from
// `grid_lines`. The recorder takes the header from the pane's rect and
// the frame body from the grid, and nothing tied the two together: a
// fixture whose rect and grid disagreed wrote a 24-row frame under a
// header announcing 6, and every assertion here still passed because they
// all read the grid. A player sizes its window from this header, so the
// frame that follows has to fit it.
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();
// The claim is the VISIBLE screen, so the bound is the screen's own
// height, taken from the pane rather than guessed: `grid_lines` returns
// the scrollback first, and the visible rows are what remains after its
// negative `top`. The bound of 64 this replaces admitted the regression
// it existed to reject - a recorder that wrote the last 64 rows carries
// 40 rows of history AND `line-199`, so every assertion here passed on
// it (verified by making `record_active_screen` do exactly that).
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"
);
// And a check that does not go through `grid_lines` at all, so a wrong
// slice cannot agree with a wrong expectation: any frame wider than the
// screen reaches back into the flood, and `line-100` is far outside a
// screen-sized window at the recent end of 200 lines.
assert!(
!frame.contains("line-100"),
"the frame reaches back into scrollback: {frame:?}"
);
// Order and adjacency, in one literal that does not go through
// `grid_lines`. Everything above constrains the frame's ENDS and its row
// count, so a recorder that emitted the visible rows reversed, or
// shuffled, satisfies all of it.
assert!(
frame.contains("line-198\r\nline-199"),
"the frame must carry the screen's rows in order: {frame:?}"
);
// And it is the RECENT end of the output, not the oldest.
// `line-199` alone. The `|| contains("line-19")` this replaces was both
// redundant and weakening: "line-199" already contains "line-19", so the
// disjunct could only ever ADD acceptance - of a frame showing an old
// scrollback slice around line-19 through line-24, which is precisely the
// regression the assertion exists to reject. An OR whose second arm is a
// substring of its first can only make a check weaker.
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"
);
}
/// The recorded frame's rows wrap at the width the header declares (#397).
///
/// The header takes its geometry from the pane's `last_inner` and the body
/// comes from the grid, and the sibling test above ties them together in one
/// dimension only: it compares `header["height"]` against a row count derived
/// from the frame, but `header["width"]` against the literal 40 the fixture
/// itself set. A grid wrapped at any other column satisfies that. It is not a
/// hypothetical shape either: that fixture shipped an 80-column grid under a
/// 40-column header and every assertion in it passed.
///
/// A line longer than the screen is the discriminator. It can only wrap at
/// the grid's REAL width, so a frame whose rows run past the header's width
/// fails here, and the digits make the wrap column readable from the text
/// rather than inferred from a length.
#[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,
};
// `resize`, so the GRID is 40 columns too. Setting `last_inner` alone
// leaves the grid at the 80 it was spawned with, which is exactly the
// disagreement this test exists to reject.
app.terminals[0].resize(40, 20);
// Digits repeating every SEVEN columns, so the wrap point is READ off the
// text. The period matters twice over. A uniform fill would look
// correctly wrapped at every width; and a period of ten, which this
// replaces, divides 40, so `long[..40]` and `long[40..80]` were the SAME
// string and the adjacency needle below was also satisfied at grid widths
// 50 and 60. Seven is coprime with 40, so the two halves differ and
// adjacency pins the column by itself.
let long: String = (0..100u8).map(|i| char::from(b'0' + (i % 7))).collect();
// A LEADING CRLF, in the SAME feed as the payload. The pane runs a real
// shell whose prompt races these bytes (#397), and a prompt landing first
// would push the payload off column 0, at which point the line wraps
// somewhere else and this test reports "the long line must wrap at column
// 40" against a grid that really is 40 - the same misdiagnosis its own
// first draft produced for a different reason. `feed_bytes_for_test`
// holds the term lock for the whole buffer, so the reader thread cannot
// interleave INSIDE this call; a separate leading feed would leave the
// window between the two calls open.
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");
// The recorder writes a clear-and-home BEFORE the rows, so the first
// segment of a naive split carries seven escape characters on top of its
// row. Measuring that as a row's width is how the first version of this
// test read 47 columns off a grid that really was 40.
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"
);
// The wrap, pinned as two WHOLE rows rather than as a substring. The
// substring form this replaces did not deliver the uniqueness its comment
// claimed: `contains` only needs the first half to END some row and the
// second to BEGIN the next, so with a period-P fill it matches at every
// width w in 40..=60 with w congruent to 40 mod P. At the period of 10
// this started with that was widths 50 and 60; at 7 it is 47 and 54, and
// 47 is the very number this test's own first draft misread off a
// 40-column grid. Changing the period could never fix it.
//
// Row EQUALITY can only hold at width 40: at 47 the row is `long[..47]`,
// which is not `long[..40]`. So adjacency now rejects every other width on
// its own, and the bound below is a genuinely independent second check
// rather than the only one doing the work.
let rows: Vec<&str> = body.split("\r\n").collect();
// Precondition, so a missing payload cannot be reported as a bad wrap.
// `record_active_screen` splits scrollback off, so shell startup output
// pushing the payload above `topmost_line()` would fail the adjacency
// check below while naming the column, which is the exact misdiagnosis
// this test's first draft produced for a different reason.
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:?}"
);
// And no row may exceed it. This is the half that catches the 80-column
// grid: there the line wraps at 80, so the widest row is twice what a
// player sizes its window to.
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"
);
}
/// #356's playback criterion with `agg`, the GIF converter: a recording
/// with colour, a resize and a wrapped line converts without complaint.
/// Set `CROFT_TEST_AGG` to an agg binary (`cargo install --git
/// https://github.com/asciinema/agg`).
#[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");
}
/// A geometry change reaches the cast BEFORE the frame drawn at it (#397).
///
/// `record_active_screen` emits the resize first so a player has the new
/// geometry before the frame that was wrapped for it; the other order renders
/// one frame at the old width. Nothing pinned that order. In every other
/// fixture `recorded_size` already equals the pane's size at record time, so
/// the branch never runs at all, and the one other test that produces an `r`
/// event calls `record_resize` directly, which bypasses the ordering logic
/// rather than exercising it.
///
/// `last_inner` alone moves here, without a `resize`: it is what the branch
/// reads, and the claim under test is the ORDER of two events, not the
/// content of the frame between them.
#[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);
// Toggling on seeds `recorded_size` from the pane, so this first frame
// must NOT carry a resize: a test that saw one here would be reading the
// seeding, not the ordering.
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();
// Swap the two statements in `record_active_screen` and this reads
// `["o", "o", "r"]`; drop the branch and it reads `["o", "o"]`. The
// sequence is asserted whole rather than as "an r exists somewhere",
// which both of those would satisfy under a looser check.
assert_eq!(
kinds,
vec!["o", "r", "o"],
"the cast must carry the new geometry before the frame drawn at it, got {kinds:?}"
);
}
/// A collapsed pane records no geometry, and does not poison the next one.
///
/// `record_active_screen`'s guard is `size != self.recorded_size && size.0 > 0
/// && size.1 > 0`, and the two size conjuncts had never run: every fixture in
/// the suite holds a non-zero rect. They carry two claims. A pane whose
/// `last_inner` has collapsed must not write a degenerate `r` announcing a
/// zero-column window, and it must not overwrite `recorded_size` with that
/// zero, which would make the NEXT record emit a resize back to a geometry
/// the player already had.
///
/// Drop EITHER size conjunct and the sequence gains two `r` events instead
/// of none: `size.0 > 0` from the width fold, `size.1 > 0` from the height
/// fold. The first version of this doc named only the width half, which is
/// the shape an earlier round was pulled up for: the doc is what the next
/// editor reads before the assert message.
#[test]
fn a_collapsed_pane_records_no_resize_and_leaves_the_last_one_standing() {
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();
// Collapsed: the rect a pane gets when its split is folded to nothing.
// `last_inner` only, deliberately: production also calls `resize`, which
// floors the GRID at two columns, and the guard under test reads
// `last_inner` rather than the grid.
app.terminals[0].last_inner.width = 0;
app.record_active_screen();
// And back to the geometry the recording was opened at. If the collapsed
// record had written its zero into `recorded_size`, THIS record would
// announce a resize to 40x20, which the player already has.
app.terminals[0].last_inner.width = 40;
app.record_active_screen();
// The HEIGHT conjunct, which the first version of this test left as dead
// as it found it: with only `size.0 > 0` deleted the collapsed record
// still has a zero width and the sequence does not move, so that mutation
// was invisible. A zero-height fold exercises the other half.
app.terminals[0].last_inner.height = 0;
app.record_active_screen();
app.terminals[0].last_inner.height = 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 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", "o", "o", "o", "o"],
"five frames and NO resize: a collapsed pane has no geometry worth \
announcing, and must not make the pane after it look like a change. \
Dropping either conjunct of the guard adds two `r` events, the width \
half from the first fold and the height half from the second, \
got {kinds:?}"
);
}
/// A fold mid-recording narrows the frame, and says nothing about it (#397).
///
/// The sibling above moves `last_inner` alone, because the guard it tests
/// reads `last_inner`. Production folds differently: `render` assigns
/// `last_inner = inner` and then calls `resize(inner.width, inner.height)`,
/// so a real fold leaves `last_inner.width` at 0 while the GRID floors at two
/// columns. The zero then suppresses the resize event, and the cast carries a
/// 2-column frame under a 40-column header with nothing announcing it.
///
/// The first version of this test asserted `widest <= declared` and could not
/// fail. Both numbers are arithmetic: no row can exceed the grid, and the
/// grid is only ever 40 or the floor of 2, so 2 <= 40 held whatever the fold
/// did. Deleting both fold lines left every assertion green, which is a test
/// named for a gesture it never exercised. It now asserts what the fold
/// actually moves.
#[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();
// Exactly what `render` does on a fold: `last_inner` takes the zero, and
// `resize` floors the grid at two columns. Setting `last_inner.width = 2`
// instead, as the first version did, is a pairing production never
// produces, and it makes the recorder emit an `r` the real gesture
// suppresses, so the fixture avoided the case it was written for.
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();
// No header parse here: the "frames fit the header" claim belongs to
// `a_recorded_frames_rows_wrap_at_the_width_its_header_declares`, which
// pins it with a 100-character payload. Asserting it HERE was arithmetic,
// since `after` is pinned to 2 two lines below and no row can exceed the
// grid, so it survived the fold being deleted. That is the same defect
// this test was rewritten to remove, kept one assertion further down.
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");
// The claim the fold moves. Remove the fold and `after` EQUALS `before`
// (whatever that is: the pane's real shell may print a prompt wider than
// the payload), so this is the assertion the previous version was
// missing. No literal here, because the fixture does not control it.
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"
);
// And the suppression is part of the claim rather than a side effect the
// filter above discarded: `last_inner.width` of 0 fails the guard's
// `size.0 > 0`, so the narrowing reaches the player with no `r` in front
// of it. Set `last_inner.width = 2` and an `r` appears here.
assert!(
events.iter().all(|(kind, _)| kind == "o"),
"a fold announces no geometry, got {:?}",
events.iter().map(|(k, _)| k).collect::<Vec<_>>()
);
}
/// A pane that GROWS mid-recording announces the new width first (#397).
///
/// The fold above narrows, which a player renders as a small image in a large
/// window and cannot corrupt anything. Widening is the direction that can:
/// the frame really is wider than the header the recording opened at, and
/// correctness rests entirely on the `r` event arriving before the frame
/// drawn at it. Nothing in the suite recorded a pane that grows.
#[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);
// Longer than the header's 40 and shorter than the new 80, so the row
// that lands is one the OLD geometry could not have held.
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();
// A third frame with NOTHING moved, which pins the recorder REMEMBERING
// the widening. Delete `self.recorded_size = size` from
// `record_active_screen` and this reads ["o","r","o","r","o"]: the stale
// size makes every later frame re-announce a geometry the player has.
// Nothing in the suite caught that assignment's removal.
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}"
);
// Unconditional, and on BOTH dimensions. The first version read
// `events[1][3]`, which an asciicast resize never has (it is
// `[time, "r", "COLSxROWS"]`, three elements), so the primary extraction
// always yielded None and an `or_else` did the work behind an `if let`.
// The day that fallback was tidied away the assertion would have stopped
// running with nothing failing, and the rows dimension was read by
// nothing at all: `record_resize(size.1, size.0)` survived the suite.
assert_eq!(
events[1][2].as_str(),
Some("80x20"),
"the `r` must name the pane's new geometry, got {:?}",
events[1]
);
}
/// #366: review boxes survive a render, which rebuilds the navigator's.
///
/// `render` reassigns `editor.comment_boxes` from `navigator_notes` every
/// frame, so review threads written straight into that field were wiped
/// before the user saw one — while the status line still reported having
/// loaded them. The boxes therefore live in their own field and are merged
/// in, and this asserts the merge rather than the assignment.
#[test]
fn review_boxes_survive_the_render_that_rebuilds_navigator_notes() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("a.rs");
std::fs::write(&file, "one\ntwo\nthree\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&file).unwrap();
app.review_boxes = Some((
file.clone(),
vec![crate::review_threads::Thread {
id: 77,
author: String::from("ada"),
body: String::from("this moved"),
path: String::from("a.rs"),
anchor: crate::review_threads::Anchor::Outdated(1),
resolved: false,
}],
));
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert!(
app.editor.comment_boxes.iter().any(|b| b.id == 77),
"the render wiped the review box: {:?}",
app.editor
.comment_boxes
.iter()
.map(|b| b.id)
.collect::<Vec<_>>()
);
// A second frame must not duplicate it — the merge appends each time,
// so it has to append to a freshly rebuilt list rather than accumulate.
term.draw(|f| app.render(f)).unwrap();
assert_eq!(
app.editor
.comment_boxes
.iter()
.filter(|b| b.id == 77)
.count(),
1,
"the box was duplicated across frames"
);
}
/// #366: another file's review comments do not follow the user to this one.
///
/// The boxes are merged into `editor.comment_boxes` on every frame. Keyed
/// only by "whatever was loaded last", `a.rs`'s objections would hang off
/// `b.rs`'s line numbers, against unrelated code — the same harm
/// `threads_are_filtered_to_the_file_being_viewed` prevents on the filter
/// axis, re-entering through the lifetime axis. So the field carries the
/// path it was loaded for and the merge checks it.
#[test]
fn review_boxes_do_not_follow_the_user_to_another_file() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.rs");
let b = tmp.path().join("b.rs");
std::fs::write(&a, "one\ntwo\nthree\n").unwrap();
std::fs::write(&b, "alpha\nbeta\ngamma\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&a).unwrap();
app.review_boxes = Some((
a.clone(),
vec![crate::review_threads::Thread {
id: 77,
author: String::from("ada"),
body: String::from("objection"),
path: String::from("a.rs"),
anchor: crate::review_threads::Anchor::At(1),
resolved: false,
}],
));
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert!(
app.editor.comment_boxes.iter().any(|b| b.id == 77),
"the box should be on the file it was loaded for"
);
// Switch files: the boxes belong to a.rs and must not appear here.
app.editor.open(&b).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert!(
!app.editor.comment_boxes.iter().any(|bx| bx.id == 77),
"a.rs's review comments followed the user to b.rs: {:?}",
app.editor
.comment_boxes
.iter()
.map(|bx| (bx.id, bx.line))
.collect::<Vec<_>>()
);
}
/// #366: box geometry tracks the live buffer, not the buffer at load time.
///
/// `box_line` clamps so a box past the end stays visible. Computed once at
/// load, that clamp is stale the instant the user edits: delete most of the
/// file and the boxes keep rows that no longer exist, which is exactly the
/// invisibility clamping exists to prevent. So the field keeps `Thread`s and
/// the geometry is derived per frame.
#[test]
fn review_box_geometry_follows_the_buffer_when_it_shrinks() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("a.rs");
std::fs::write(&file, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&file).unwrap();
app.review_boxes = Some((
file.clone(),
vec![crate::review_threads::Thread {
id: 88,
author: String::from("ada"),
body: String::from("late"),
path: String::from("a.rs"),
anchor: crate::review_threads::Anchor::At(9),
resolved: false,
}],
));
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let before = app
.editor
.comment_boxes
.iter()
.find(|b| b.id == 88)
.map(|b| b.line);
assert_eq!(before, Some(9), "the box should sit on its own line first");
// The user deletes most of the file; line 9 no longer exists.
app.editor.lines.truncate(3);
term.draw(|f| app.render(f)).unwrap();
let after = app
.editor
.comment_boxes
.iter()
.find(|b| b.id == 88)
.map(|b| b.line);
assert_eq!(
after,
Some(2),
"the box kept a row past the end of the shrunken buffer"
);
}
/// #366: Ignore actually dismisses a review box.
///
/// Every box renders a live `\u{2715} Ignore` footer, and the hit-test is
/// driven off `comment_boxes` indices with no notion of a box's origin. If
/// `ignore_comment_box` only knows about navigator notes, it reports
/// "Comment ignored" and the box returns on the next frame — a dismiss that
/// claims success and visibly does nothing.
#[test]
fn ignoring_a_review_box_actually_dismisses_it() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("a.rs");
std::fs::write(&file, "one\ntwo\nthree\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&file).unwrap();
app.review_boxes = Some((
file.clone(),
vec![crate::review_threads::Thread {
id: 99,
author: String::from("ada"),
body: String::from("dismiss me"),
path: String::from("a.rs"),
anchor: crate::review_threads::Anchor::At(0),
resolved: false,
}],
));
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert!(app.editor.comment_boxes.iter().any(|b| b.id == 99));
app.ignore_comment_box(99);
term.draw(|f| app.render(f)).unwrap();
assert!(
!app.editor.comment_boxes.iter().any(|b| b.id == 99),
"the ignored review box came back on the next frame"
);
}
/// #366: F4 reaches review boxes, not only navigator notes.
///
/// The boxes render on a shared surface with a shared hit-test, so a
/// keyboard walk that reads `navigator_notes` alone leaves them visible but
/// unreachable — and reports "No navigator comments in this file" while
/// several are on screen.
#[test]
fn the_comment_walk_reaches_review_boxes() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("a.rs");
std::fs::write(&file, "one\ntwo\nthree\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&file).unwrap();
app.review_boxes = Some((
file.clone(),
vec![crate::review_threads::Thread {
id: 55,
author: String::from("ada"),
body: String::from("reachable?"),
path: String::from("a.rs"),
anchor: crate::review_threads::Anchor::At(2),
resolved: false,
}],
));
// Deliberately NO render first: `comment_boxes` is a render output, so
// a walk that read it would depend on a frame having been drawn and
// would find nothing on an F4 pressed before the first one.
app.editor.cursor_row = 0;
assert_eq!(
app.next_comment_from_caret().map(|(id, _)| id),
Some(55),
"F4 skipped the review box entirely"
);
}
/// #366: a navigator note and a review comment on ONE line keep a stable
/// order, and the review box carries its own text.
///
/// The merge appends review boxes after the navigator's, which is the order
/// the render comment promises. Asserting on ids alone would pass under a
/// merge that mangled every other field, so this pins the whole tuple:
/// a swap of the two sources, a wrong line, or a body taken from the wrong
/// thread all fail here.
#[test]
fn a_navigator_note_and_a_review_comment_on_one_line_keep_a_stable_order() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("a.rs");
std::fs::write(&file, "one\ntwo\nthree\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_file_at_launch(&file);
app.navigator_notes
.insert("a.rs".into(), vec![(1, 1, "the navigator's note".into())]);
app.review_boxes = Some((
file.clone(),
vec![crate::review_threads::Thread {
id: 4_000_000_001,
author: String::from("ada"),
body: String::from("the reviewer's objection"),
path: String::from("a.rs"),
// Same row as the navigator's note.
anchor: crate::review_threads::Anchor::At(1),
resolved: false,
}],
));
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let got: Vec<(u64, usize, String)> = app
.editor
.comment_boxes
.iter()
.map(|b| (b.id, b.line, b.body.clone()))
.collect();
assert_eq!(
got,
vec![
(1, 1, String::from("the navigator's note")),
(4_000_000_001, 1, String::from("the reviewer's objection")),
],
"the navigator's note must come first and each box keep its own text"
);
}
/// #366: review boxes follow the open file through a rename.
///
/// Both guards compare the stored path against `editor.path`, so a rename
/// that repoints the tab without repointing the field makes the boxes
/// vanish from the buffer the user is still editing.
#[test]
fn review_boxes_follow_the_open_file_through_a_rename() {
let tmp = tempfile::tempdir().unwrap();
let old = tmp.path().join("a.rs");
let new = tmp.path().join("renamed.rs");
std::fs::write(&old, "one\ntwo\nthree\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&old).unwrap();
app.review_boxes = Some((
old.clone(),
vec![crate::review_threads::Thread {
id: 66,
author: String::from("ada"),
body: String::from("still mine"),
path: String::from("a.rs"),
anchor: crate::review_threads::Anchor::At(1),
resolved: false,
}],
));
// Driven through the real rename prompt rather than by calling the
// helpers directly: hand-calling them tests the helper's logic while
// leaving the WIRING untested, so deleting the call from the rename
// handler would keep passing.
app.prompt = Some(super::Prompt {
label: String::from("Rename a.rs"),
buffer: String::from("renamed.rs"),
kind: super::PromptKind::Rename(old.clone()),
target_dir: tmp.path().to_path_buf(),
error: None,
});
app.commit_prompt();
assert!(
app.prompt.is_none(),
"the rename prompt should have committed"
);
assert_eq!(
app.editor.path.as_deref(),
Some(new.as_path()),
"the tab should have followed the rename"
);
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert!(
app.editor.comment_boxes.iter().any(|b| b.id == 66),
"the rename orphaned the review boxes: {:?}",
app.editor
.comment_boxes
.iter()
.map(|b| b.id)
.collect::<Vec<_>>()
);
}
/// #356: a recording produces a file that is asciicast v2 all the way
/// through, header and every event.
///
/// Asserted by PARSING the file rather than by matching strings: the format
/// exists to be read by `asciinema play` and `agg`, and a cast that looks
/// right but does not parse fails at the moment someone tries to share it.
/// A terminal stream is full of quotes and escape bytes, so this is the
/// failure mode that actually happens.
#[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,
};
// The PTY grid is sized from the pane's INNER rect, so the header must
// be too — `Borders::ALL` takes a cell on each side. Recording the outer
// size declares a terminal two columns wider than the content was
// wrapped for, and the player re-wraps every long line at the wrong
// column.
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);
// Output carrying the characters that break a hand-rolled encoder.
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);
// Found by LISTING rather than by rebuilding the name. A test that
// recomputes the path asserts against its own copy of the naming rule,
// so it would keep passing if production's rule changed — the same
// stand-in problem as asserting against a helper you wrote yourself.
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:?}"
);
}
/// A file with two functions, `fn b` the LAST thing in it (no trailing
/// newline), opened with the caret inside `fn b` and the symbol tab opened
/// from the palette.
fn app_with_symbol_tab_on_b(tmp: &tempfile::TempDir) -> (App, std::path::PathBuf) {
let file = tmp.path().join("two.rs");
std::fs::write(&file, "fn a() {\n 1\n}\nfn b() {\n 2\n}").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.editor.cursor_row = 4;
app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
(app, file)
}
fn painted(app: &mut App) -> String {
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let mut all = String::new();
for y in 0..30 {
for x in 0..100 {
all.push_str(term.backend().buffer()[(x, y)].symbol());
}
all.push('\n');
}
all
}
/// #369: a file and its symbol tab count edits apart, but one of them
/// speaks for the file to the language server: the active tab. Judged
/// each against the one record, they took turns resending the whole text
/// on every tick.
#[test]
fn one_tab_speaks_for_a_file_to_the_language_server() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("two.rs");
std::fs::write(&file, "fn a() {\n 1\n}\nfn b() {\n 2\n}").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.editor.cursor_row = 1;
app.editor.cursor_col = 5;
for _ in 0..3 {
app.editor.insert_char('1');
}
app.editor.cursor_row = 4;
app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
app.sync_symbol_views();
assert!(app.editor.symbol_view.is_some(), "the symbol tab is active");
let path = app.editor.path.clone().unwrap();
assert_ne!(
app.editor.editors[0].edit_seq, app.editor.edit_seq,
"the tabs' counters differ"
);
let mut seen = Vec::new();
for _ in 0..3 {
app.sync_lsp();
seen.push(app.lsp_last_seen.get(&path).copied());
}
let active = Some(app.editor.edit_seq);
assert_eq!(seen, vec![active, active, active], "no tick resends");
}
/// An LSP edit applied to the file's tab while its symbol tab is active
/// survives the next keystroke in the symbol tab: both tabs changed, and
/// the keystroke's tab used to be copied over the rename.
#[test]
fn a_rename_landing_before_a_keystroke_in_a_symbol_tab_is_kept() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
app.focus = Pane::Editor;
let edits = vec![(
file.clone(),
vec![crate::widgets::editor::TextSpanEdit {
start: (0, 3),
end: (0, 4),
new_text: String::from("renamed"),
utf16: false,
}],
)];
app.apply_rename_edits(&edits).unwrap();
app.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Char('x'),
crossterm::event::KeyModifiers::NONE,
))
.unwrap();
app.sync_symbol_views();
let file_tab = app
.editor
.editors
.iter()
.find(|t| t.symbol_view.is_none() && t.path.as_deref() == Some(file.as_path()))
.expect("the file's own tab");
assert!(
file_tab.lines[0].contains("renamed"),
"{:?}",
file_tab.lines
);
assert!(
file_tab.lines.iter().any(|l| l.contains('x')),
"{:?}",
file_tab.lines
);
}
#[test]
fn peek_references_with_nothing_to_ask_does_not_arm_on_a_stale_request() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.editor.path.is_none());
app.references_request_id = Some(7);
app.peek_references_at_cursor();
assert!(!app.references_want_peek);
assert_eq!(app.references_request_id, None);
}
/// A file of three functions with a symbol tab on the middle one, `b`
/// (lines 3 to 5), active, and vim on.
fn vim_symbol_tab_on_b(tmp: &tempfile::TempDir) -> App {
let file = tmp.path().join("three.rs");
std::fs::write(
&file,
"fn a() {\n 1\n}\nfn b() {\n 2\n}\nfn c() {\n 3\n}",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.editor.cursor_row = 4;
app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
app.sync_symbol_views();
let view = app.editor.symbol_view.as_ref().expect("a symbol tab on b");
assert_eq!((view.first, view.last), (3, 5));
app.focus = Pane::Editor;
app.vim.enabled = true;
app
}
/// #369: vim operators in a symbol tab stay inside its symbol. Upward
/// (`dgg`, `d5k`, `db` at its first column) they used to reach the hidden
/// lines above it, downward (`dG`, `dw` at its end) the ones below; inside
/// it they still delete what they cover.
#[test]
fn vim_operators_in_a_symbol_tab_stay_inside_its_symbol() {
let a = ["fn a() {", " 1", "}"];
let c = ["fn c() {", " 3", "}"];
let whole = [&a[..], &["fn b() {", " 2", "}"], &c[..]].concat();
// (keys, caret, the buffer after)
let cases: [(&str, (usize, usize), Vec<&str>); 5] = [
("dgg", (4, 0), [&a[..], &["}"], &c[..]].concat()),
("d5k", (4, 0), [&a[..], &["}"], &c[..]].concat()),
("db", (3, 0), whole.clone()),
("dG", (4, 0), [&a[..], &["fn b() {"], &c[..]].concat()),
(
"dw",
(5, 0),
[&a[..], &["fn b() {", " 2", ""], &c[..]].concat(),
),
];
for (keys, (row, col), after) in cases {
let tmp = tempfile::tempdir().unwrap();
let mut app = vim_symbol_tab_on_b(&tmp);
app.editor.cursor_row = row;
app.editor.cursor_col = col;
vim_feed_str(&mut app, keys);
assert_eq!(app.editor.lines, after, "{keys}");
}
}
/// #369: a count on a line operator stops at the symbol's last line, and
/// the status reports the lines it covered.
#[test]
fn a_vim_line_count_in_a_symbol_tab_stops_at_its_last_line() {
let tmp = tempfile::tempdir().unwrap();
let mut app = vim_symbol_tab_on_b(&tmp);
app.editor.cursor_row = 4;
app.editor.cursor_col = 0;
vim_feed_str(&mut app, "5yy");
assert_eq!(app.status, "Yanked 2 line(s)");
}
/// #369: two symbols that start on one line get a tab each, opening either
/// again focuses its own tab, and each follows its own symbol: renaming the
/// inner one leaves the outer tab's title alone.
#[test]
fn symbols_starting_on_one_line_get_a_tab_each() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("one.rs");
std::fs::write(&file, "impl S { fn m() {} }\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.open_symbol_tab_for("S".into(), 0, 0);
app.editor.select(0);
app.open_symbol_tab_for("m".into(), 0, 0);
let names = |app: &App| -> Vec<String> {
let mut names: Vec<String> = app
.editor
.editors
.iter()
.filter_map(|e| e.symbol_view.as_ref().map(|v| v.name.clone()))
.collect();
names.sort();
names
};
assert_eq!(names(&app), vec!["S", "m"]);
app.editor.select(0);
app.open_symbol_tab_for("S".into(), 0, 0);
assert_eq!(names(&app).len(), 2, "reopening S focused its tab");
assert_eq!(
app.editor.symbol_view.as_ref().map(|v| v.name.as_str()),
Some("S")
);
// Rename m to n from the file's tab.
app.editor.select(0);
let col = app.editor.lines[0].find("m()").unwrap();
app.editor.cursor_row = 0;
app.editor.cursor_col = col;
app.editor.delete_forward();
app.editor.insert_char('n');
app.sync_symbol_views();
assert_eq!(names(&app), vec!["S", "n"]);
}
/// #369: pickers spell some symbols differently (the LSP outline's
/// `impl Foo` is tree-sitter's `Foo`); asking for the same symbol under
/// either name focuses the one tab.
#[test]
fn one_symbol_under_two_spellings_gets_one_tab() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("foo.rs");
std::fs::write(&file, "impl Foo {\n fn a() {}\n}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.open_symbol_tab_for("Foo".into(), 0, 2);
app.editor.select(0);
app.open_symbol_tab_for("impl Foo".into(), 0, 2);
let tabs = app
.editor
.editors
.iter()
.filter(|e| e.symbol_view.is_some())
.count();
assert_eq!(tabs, 1);
}
/// #369: a symbol tab's minimap draws only its symbol, and a click on it
/// lands on the symbol's lines, not the file's.
#[test]
fn a_symbol_tab_minimap_draws_and_maps_only_its_symbol() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("mm.rs");
std::fs::write(&file, "fn a() {\n 1\n}\n fn b() {\n 2\n }").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
let (bg, fg) = ((0, 0, 0), (255, 255, 255));
// Row 0, column 0: `f` of `fn a` in the file's tab.
let lit = |buf: &[u8]| buf[0] != 0;
assert!(lit(&app.editor.minimap_rgba(4, 3, 3, bg, fg)));
app.editor.cursor_row = 4;
app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
assert_eq!(app.editor.minimap_span(), (3, 6));
// ` fn b`: column 0 is indentation.
assert!(!lit(&app.editor.minimap_rgba(4, 3, 3, bg, fg)));
app.minimap_img_rect = Rect::new(0, 0, 2, 3);
app.cell_pixel = Some((1, 1));
app.minimap_content_h = 3;
app.minimap_scroll_to_row(0);
assert_eq!(
app.editor.cursor_row, 3,
"the top of the strip is b's first line"
);
}
/// #369: a documented symbol starts on its doc comment in the LSP outline
/// and on its item in the tree-sitter one; opened from both it gets one tab.
#[test]
fn a_documented_symbol_opened_from_both_outlines_gets_one_tab() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("doc.rs");
std::fs::write(&file, "/// doc\nfn foo() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.open_symbol_tab_for("foo".into(), 1, 1);
app.editor.select(0);
app.open_symbol_tab_for("foo".into(), 0, 1);
let tabs = app
.editor
.editors
.iter()
.filter(|e| e.symbol_view.is_some())
.count();
assert_eq!(tabs, 1);
assert!(
app.editor.symbol_view.is_some(),
"the existing tab is focused"
);
}
/// #369: two same-named symbols of one kind and depth (a `fn new` in each
/// of two impls) are told apart by the line their item starts on.
#[test]
fn same_named_symbols_on_different_lines_get_a_tab_each() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("news.rs");
std::fs::write(
&file,
"impl A {\n fn new() {}\n}\nimpl B {\n fn new() {}\n}\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.open_symbol_tab_for("new".into(), 1, 1);
app.editor.select(0);
app.open_symbol_tab_for("new".into(), 4, 4);
let tabs = app
.editor
.editors
.iter()
.filter(|e| e.symbol_view.is_some())
.count();
assert_eq!(tabs, 2);
}
/// #369: switching between two symbol tabs of the same length repaints the
/// minimap (their other layout fields agree), and its viewport and
/// selection count from the symbol's first line.
#[test]
fn switching_between_same_length_symbol_tabs_repaints_the_minimap() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("two.rs");
std::fs::write(&file, "fn a() {\n 1\n}\nfn b() {\n 2\n}").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.cell_pixel = Some((8, 16));
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
app.editor.open_pinned(&file).unwrap();
app.open_symbol_tab_for("a".into(), 0, 2);
app.editor.select(0);
app.open_symbol_tab_for("b".into(), 3, 5);
let tab = |app: &App, name: &str| {
app.editor
.editors
.iter()
.position(|e| e.symbol_view.as_ref().is_some_and(|v| v.name == name))
.unwrap()
};
let (a, b) = (tab(&app, "a"), tab(&app, "b"));
let strip = Rect::new(100, 1, 6, 20);
app.editor.select(a);
app.update_minimap_overlay(strip);
assert_eq!(app.minimap_base.as_ref().map(|m| m.sig.5), Some((0, 3)));
app.editor.select(b);
app.update_minimap_overlay(strip);
assert_eq!(app.minimap_base.as_ref().map(|m| m.sig.5), Some((3, 6)));
app.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: (3, 0),
head: (4, 2),
});
app.update_minimap_overlay(strip);
let layout = app.overlays.minimap.layout().expect("laid out");
assert_eq!((layout.top, layout.selection), (0, Some((0, 1))));
}
/// #369: a symbol tab is a tab of its own that shows only its symbol.
///
/// Opened beside the file's tab, titled by the symbol, holding the whole
/// file (so LSP, save and line numbers stay in file coordinates) while it
/// paints only the symbol's lines. `fn b` is the last symbol in the file:
/// its range must stop at the buffer's end, not a separator byte past it.
#[test]
fn a_symbol_tab_opens_beside_its_file_showing_only_the_symbol() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
assert_eq!(app.editor.editors.len(), 2, "a NEW tab, not a replaced one");
assert_eq!(app.editor.active_index(), 1, "placed after its file's tab");
let tab = &app.editor.editors[1];
assert_eq!(tab.path.as_deref(), Some(file.as_path()));
let view = tab.symbol_view.as_ref().expect("the tab is a symbol tab");
assert_eq!((view.name.as_str(), view.first, view.last), ("b", 3, 5));
let text = tab.lines.join("\n");
assert_eq!(
&text[view.range.start..view.range.end],
"fn b() {\n 2\n}",
"the range slices exactly the symbol, up to the buffer's end"
);
assert_eq!(tab.cursor_row, 4, "the caret stays where it was");
// Scrolled to the top, the clip, not the scroll, keeps `fn a` out.
app.editor.scroll = 0;
let screen = painted(&mut app);
assert!(
screen.contains("b \u{b7} two.rs"),
"titled by its symbol:\n{screen}"
);
assert!(
screen.contains("fn b() {"),
"the symbol is shown:\n{screen}"
);
assert!(
!screen.contains("fn a() {"),
"nothing outside the symbol is painted:\n{screen}"
);
// Opening it again focuses the existing tab rather than stacking one.
app.editor.select(0);
app.editor.cursor_row = 5;
app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
assert_eq!(app.editor.editors.len(), 2);
assert_eq!(app.editor.active_index(), 1);
}
/// #369: the caret and every edit stay inside the symbol.
///
/// Motions stop at its edges, and the edits that would join its first or
/// last line to a line outside it (Backspace at its start, Delete at its
/// end, moving a line across its edge) do nothing, rather than pulling text
/// the tab cannot show into or out of it.
#[test]
fn a_symbol_tab_keeps_the_caret_and_edits_inside_its_symbol() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, _) = app_with_symbol_tab_on_b(&tmp);
let before = app.editor.lines.clone();
app.editor.cursor_row = 3;
app.editor.cursor_col = 0;
app.handle_key(key(KeyCode::Up, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.cursor_row, 3,
"Up stops at the symbol's first line"
);
app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.lines, before,
"Backspace at its start joins nothing"
);
app.handle_key(key(KeyCode::Up, KeyModifiers::ALT)).unwrap();
assert_eq!(
app.editor.lines, before,
"its first line cannot move above it"
);
app.editor.cursor_row = 5;
app.editor.cursor_col = 0;
app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
.unwrap();
assert_eq!(
(app.editor.cursor_row, app.editor.cursor_col),
(5, 1),
"the caret parks at the symbol's end"
);
app.handle_key(key(KeyCode::Delete, KeyModifiers::NONE))
.unwrap();
app.editor.cursor_row = 5;
app.handle_key(key(KeyCode::Down, KeyModifiers::ALT))
.unwrap();
assert_eq!(
app.editor.lines, before,
"Delete and Alt+Down stop at its end"
);
// An ordinary edit inside still works.
app.editor.cursor_row = 4;
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('0'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines[4], " 20");
}
/// #369: a symbol tab and its file's tab are one document.
///
/// Typing in either shows up in the other, an edit above the symbol moves
/// the clip with it, saving either clears both dirty dots, and a symbol
/// that is deleted closes its tab with a note saying why.
#[test]
fn a_symbol_tab_mirrors_its_file_and_follows_the_symbol() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
// Typing in the symbol tab reaches the file's tab.
app.editor.cursor_row = 4;
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
.unwrap();
// The key itself mirrors the edit, so nothing is left for the tick.
assert!(!app.sync_symbol_views());
assert_eq!(app.editor.editors[0].lines[4], " 27");
assert!(
app.editor.editors[0].dirty,
"the file's tab has the unsaved edit"
);
// Lines added above the symbol in the file's tab move the clip down.
app.editor.select(0);
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
app.sync_symbol_views();
let tab = &app.editor.editors[1];
assert_eq!(tab.lines, app.editor.editors[0].lines);
let view = tab.symbol_view.as_ref().unwrap();
assert_eq!(
(view.first, view.last),
(4, 6),
"the clip moved with its symbol"
);
// Saving one clears both.
app.editor.editors[0].save_to_disk().unwrap();
app.sync_symbol_views();
assert!(
!app.editor.editors[1].dirty,
"the saved text is the symbol tab's text too"
);
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
"\nfn a() {\n 1\n}\nfn b() {\n 27\n}"
);
// Renaming the symbol retitles the tab.
app.editor.select(1);
app.editor.cursor_row = 4;
app.editor.cursor_col = 4;
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
app.sync_symbol_views();
assert_eq!(
app.editor.editors[1].symbol_view.as_ref().unwrap().name,
"bx"
);
// Deleting it closes the tab.
app.editor.select(0);
let kept: Vec<String> = app.editor.lines[..4].to_vec();
app.editor.replace_all_lines(kept);
app.sync_symbol_views();
assert_eq!(app.editor.editors.len(), 1, "the symbol tab closed");
assert!(app.editor.editors[0].symbol_view.is_none());
assert!(
app.status.contains("bx") && app.status.contains("gone"),
"the user is told which tab closed and why: {}",
app.status
);
}
/// #369: Alt+Enter in the workspace-symbol picker opens the symbol tab even
/// when the server names the file through a symlink.
///
/// The jump lands on the tab already open under the real path, so the
/// landed check has to compare the two spellings by their canonical form.
#[cfg(unix)]
#[test]
fn alt_enter_on_a_symlinked_symbol_still_opens_its_tab() {
let tmp = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(tmp.path()).unwrap();
let file = root.join("two.rs");
std::fs::write(&file, "fn a() {\n 1\n}\nfn b() {\n 2\n}").unwrap();
let link = root.join("link.rs");
std::os::unix::fs::symlink(&file, &link).unwrap();
let mut app = App::new(root.clone()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.open_workspace_symbols("b");
app.ws_symbols_request_id = Some(1);
app.apply_workspace_symbols(1, vec![ws_item("b", &link, 3)], false);
app.handle_key(key(KeyCode::Enter, KeyModifiers::ALT))
.unwrap();
let view = app
.editor
.symbol_view
.as_ref()
.expect("the symbol tab opened");
assert_eq!(view.name, "b");
}
/// #369: duplicating the symbol's last line keeps the copy inside it.
///
/// The copy lands below the closing brace, so the clip has to grow by the
/// one line rather than leave the new line outside the tab.
#[test]
fn duplicating_a_symbols_last_line_keeps_the_copy_inside_the_tab() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("two.rs");
std::fs::write(&file, "fn a() {\n 1\n}\nfn b() {\n 2\n}").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.editor.cursor_row = 1;
app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
app.sync_symbol_views();
let view = app.editor.symbol_view.as_ref().expect("symbol tab on a");
assert_eq!((view.first, view.last), (0, 2));
app.editor.cursor_row = 2;
app.editor.cursor_col = 0;
app.editor.duplicate_lines_down();
app.sync_symbol_views();
assert_eq!(
app.editor.lines[..5],
["fn a() {", " 1", "}", "}", "fn b() {"]
);
let view = app.editor.symbol_view.as_ref().expect("still a symbol tab");
assert_eq!((view.first, view.last), (0, 3), "the clip grew by the copy");
assert_eq!(app.editor.cursor_row, 3, "the caret sits on the copy");
}
/// #369: saving the file's tab leaves no disk conflict on its symbol tab.
///
/// The symbol tab holds the same text that was just written, so the next
/// external-change check must see it as in sync with disk instead of
/// offering to reload over the saved edit.
#[test]
fn saving_the_files_tab_leaves_no_conflict_on_its_symbol_tab() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, _) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
app.editor.cursor_row = 4;
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
.unwrap();
assert!(app.editor.editors[1].dirty);
app.editor.editors[0].save_to_disk().unwrap();
app.sync_symbol_views();
assert!(
!app.reload_open_file_after_external_change(),
"the symbol tab already holds the saved text"
);
assert!(app.input_prompt.is_none(), "no reload prompt");
assert_eq!(app.editor.editors[1].lines[4], " 27");
}
/// #369: Cmd+S in the symbol tab writes the file and leaves both tabs clean,
/// with no conflict for the file's tab, which holds the same text.
#[test]
fn cmd_s_in_a_symbol_tab_saves_the_file_and_cleans_both_tabs() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
app.editor.cursor_row = 4;
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
.unwrap();
assert!(app.editor.editors[0].dirty, "the file's tab has the edit");
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
"fn a() {\n 1\n}\nfn b() {\n 27\n}"
);
assert!(!app.editor.editors[1].dirty, "the symbol tab is saved");
assert!(!app.editor.editors[0].dirty, "so is the file's tab");
assert!(
!app.reload_open_file_after_external_change(),
"the file's tab already holds the saved text"
);
assert!(app.input_prompt.is_none(), "no reload prompt");
}
/// #369: auto save writes a file with a symbol tab once. Both tabs hold the
/// edit and are due together; writing the second would read the first
/// write as an external change and raise a conflict prompt.
#[test]
fn auto_save_writes_a_file_with_a_symbol_tab_once_and_cleans_both() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.auto_save = true;
app.sync_symbol_views();
app.editor.cursor_row = 4;
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
.unwrap();
app.sync_symbol_views();
let past = std::time::Instant::now() - std::time::Duration::from_secs(5);
for e in app.editor.editors.iter_mut() {
assert!(e.dirty, "fixture: both tabs hold the edit");
e.last_edit_at = Some(past);
}
assert!(app.tick_auto_save());
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
"fn a() {\n 1\n}\nfn b() {\n 27\n}"
);
for e in &app.editor.editors {
assert!(!e.dirty && !e.disk_conflict, "both tabs are saved");
}
assert!(app.input_prompt.is_none(), "no conflict prompt");
assert!(!app.reload_open_file_after_external_change());
}
/// #369: both tabs of a file with a symbol tab meet a disk conflict
/// together, and the prompt names the file once.
#[test]
fn auto_save_reports_a_symbol_tabs_file_conflict_once() {
use crate::widgets::input_prompt::InputPurpose;
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.auto_save = true;
app.sync_symbol_views();
app.editor.cursor_row = 4;
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
.unwrap();
app.sync_symbol_views();
std::fs::write(
&file,
"fn a() {\n 1\n}\nfn b() {\n changed elsewhere\n}",
)
.unwrap();
let past = std::time::Instant::now() - std::time::Duration::from_secs(5);
for e in app.editor.editors.iter_mut() {
e.last_edit_at = Some(past);
}
assert!(app.tick_auto_save());
assert!(
app.editor.editors.iter().all(|e| e.disk_conflict),
"both tabs latch the conflict"
);
match app.input_prompt.as_ref().map(|p| &p.purpose) {
Some(InputPurpose::ReloadConflict { paths }) => assert_eq!(paths, &vec![file]),
_ => panic!("a conflict prompt"),
}
}
/// #369: an encoding refusal on a file with a symbol tab names the file
/// once, not once per tab.
#[test]
fn auto_save_names_a_symbol_tabs_file_once_when_its_encoding_refuses() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, _file) = app_with_symbol_tab_on_b(&tmp);
app.auto_save = true;
app.sync_symbol_views();
let past = std::time::Instant::now() - std::time::Duration::from_secs(5);
for e in app.editor.editors.iter_mut() {
e.encoding = encoding_rs::WINDOWS_1252;
e.lines[4] = String::from(" \u{65e5}\u{672c}");
e.dirty = true;
e.last_edit_at = Some(past);
}
assert!(app.tick_auto_save());
assert!(app.editor.editors.iter().all(|e| e.encoding_loss));
assert_eq!(app.status.matches("two.rs").count(), 1, "{}", app.status);
}
/// #369: a format-on-save write lands after `save` returned, so it settles
/// the file's other tab itself rather than leaving it dirty.
#[test]
fn a_deferred_format_on_save_write_cleans_the_symbol_tabs_sibling() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
app.editor.cursor_row = 4;
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
.unwrap();
app.sync_symbol_views();
app.save_after_format = Some(file.clone());
app.complete_pending_save();
assert!(std::fs::read_to_string(&file).unwrap().contains("27"));
assert!(!app.editor.editors[1].dirty, "the symbol tab is saved");
assert!(!app.editor.editors[0].dirty, "so is the file's tab");
assert!(!app.reload_open_file_after_external_change());
}
/// #369: a format-on-save reply that lands after the user moved to another
/// file writes the requested file's tab and still settles its symbol tab.
#[test]
fn a_late_format_on_save_write_cleans_the_symbol_tabs_sibling_from_another_file() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
app.editor.cursor_row = 4;
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
.unwrap();
app.sync_symbol_views();
let other = tmp.path().join("other.rs");
std::fs::write(&other, "fn c() {}").unwrap();
app.editor.open_pinned(&other).unwrap();
assert_eq!(app.editor.path.as_deref(), Some(other.as_path()));
app.save_after_format = Some(file.clone());
app.complete_pending_save();
assert!(std::fs::read_to_string(&file).unwrap().contains("27"));
let tabs: Vec<_> = app
.editor
.editors
.iter()
.filter(|e| e.path.as_deref() == Some(file.as_path()))
.collect();
assert_eq!(tabs.len(), 2, "fixture: the file and its symbol tab");
assert!(tabs.iter().all(|e| !e.dirty), "both tabs are saved");
}
/// #369: the focus-change sweep, which waits for no delay, also writes a
/// file with a symbol tab once and cleans both when focus leaves the editor.
#[test]
fn a_focus_change_save_writes_a_file_with_a_symbol_tab_once() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
app.editor.cursor_row = 4;
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('7'), KeyModifiers::NONE))
.unwrap();
app.sync_symbol_views();
assert!(app.editor.editors.iter().all(|e| e.dirty), "fixture");
// Focus left the editor, so both tabs are due at once.
app.focus = Pane::Tree;
assert!(app.sweep_auto_save(false));
assert!(std::fs::read_to_string(&file).unwrap().contains("27"));
for e in &app.editor.editors {
assert!(!e.dirty && !e.disk_conflict, "both tabs are saved");
}
assert!(app.input_prompt.is_none(), "no conflict prompt");
}
/// #369: every way in opens the same symbol tab.
///
/// `Cmd+K Shift+V` takes the symbol at the caret, and an OUTLINE row's right-click
/// menu opens the row's symbol even when the caret sits elsewhere.
#[test]
fn the_chord_and_the_outline_menu_open_a_symbol_tab() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("two.rs");
std::fs::write(&file, "fn a() {\n 1\n}\nfn b() {\n 2\n}").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.editor.cursor_row = 1;
// Plain Cmd+K V is Live Run's.
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('v'), KeyModifiers::NONE)));
assert!(
app.editor.symbol_view.is_none(),
"Cmd+K V is not the symbol tab"
);
// Shift arrives lowercase with SHIFT under CSI-u.
let mut csi_u = App::new(tmp.path().to_path_buf()).unwrap();
csi_u.editor.open_pinned(&file).unwrap();
csi_u.editor.cursor_row = 1;
assert!(csi_u.handle_cmd_k_chord(key(KeyCode::Char('v'), KeyModifiers::SHIFT)));
assert!(csi_u.editor.symbol_view.is_some(), "Shift+v opens it too");
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('V'), KeyModifiers::SHIFT)));
let view = app
.editor
.symbol_view
.as_ref()
.expect("Cmd+K Shift+V opened a symbol tab");
assert_eq!((view.name.as_str(), view.first, view.last), ("a", 0, 2));
app.editor.select(0);
app.dispatch_menu_action(
MenuAction::OpenSymbolTab {
path: file.clone(),
name: "b".into(),
first: 3,
last: 5,
},
tmp.path().to_path_buf(),
);
let view = app
.editor
.symbol_view
.as_ref()
.expect("the menu opened a symbol tab");
assert_eq!((view.name.as_str(), view.first, view.last), ("b", 3, 5));
assert_eq!(app.editor.editors.len(), 3);
}
/// #369: right-clicking an OUTLINE row offers its symbol as a tab.
///
/// The row, not the caret, picks the symbol: the caret sits in `a` while
/// the click lands on `b`'s row.
#[test]
fn an_outline_row_right_click_opens_that_symbol_as_a_tab() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("two.rs");
std::fs::write(&file, "fn a() {\n 1\n}\nfn b() {\n 2\n}").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
if !app.explorer_views.is_visible(ExplorerView::Outline) {
app.toggle_explorer_view(ExplorerView::Outline);
}
app.outline.collapsed = false;
let symbols = app.compute_syntax_outline(&file);
app.outline.set_symbols(file.clone(), symbols);
painted(&mut app);
let area = app.outline.last_area;
let row = (area.y..area.y + area.height)
.find(|&y| {
app.outline
.row_at(y)
.is_some_and(|i| app.outline.symbols()[i].name == "b")
})
.expect("b has an OUTLINE row");
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Right),
area.x + 2,
row,
));
let menu = app.context_menu.as_mut().expect("the row has a menu");
let idx = menu
.items
.iter()
.position(|e| menu_label(e) == "Open Symbol in Its Own Tab")
.expect("the menu offers the symbol tab");
menu.selected = idx;
app.handle_menu_key(key(KeyCode::Enter, KeyModifiers::NONE));
let view = app
.editor
.symbol_view
.as_ref()
.expect("a symbol tab opened");
assert_eq!((view.name.as_str(), view.first, view.last), ("b", 3, 5));
}
/// #369: a restart restores the file, not a duplicate of it.
///
/// The symbol tab mirrors its file's tab, so session capture drops it while
/// that tab is open, and keeps it (as a plain tab, with its unsaved text)
/// when it is the file's only tab.
#[test]
fn session_capture_keeps_a_symbol_tab_only_when_it_is_the_files_last_tab() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
let state = app.capture_session_state();
assert_eq!(state.tabs.len(), 1, "the file's tab alone");
assert_eq!(state.active_tab, 0, "focus falls to the file's tab");
app.editor.close_tab(0);
app.editor.lines[4] = " 9".into();
app.editor.dirty = true;
let state = app.capture_session_state();
assert_eq!(state.tabs.len(), 1);
assert_eq!(state.tabs[0].path.as_ref(), Some(&file));
assert!(
state.tabs[0]
.unsaved_text
.as_deref()
.unwrap()
.contains(" 9")
);
}
/// #369: scrolling a symbol tab stops once its last line reaches the pane's
/// bottom; a short symbol never leaves a lone line above blank rows.
#[test]
fn a_symbol_tab_never_scrolls_its_tail_off_a_pane_it_fits() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, _file) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
app.editor.cursor_row = 5;
app.editor.cursor_col = 0;
app.editor.scroll = 5;
painted(&mut app);
assert_eq!(
app.editor.scroll, 3,
"fn b's three lines fill the pane top down"
);
}
/// #369: multi-cursor commands in a symbol tab stay inside the symbol:
/// Change All Occurrences matches only there, Add Cursor Above stops at its
/// first line, and a caret that lands outside is dropped rather than
/// stacked on the edge.
#[test]
fn multi_cursor_commands_stay_in_the_symbol() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, _file) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
app.editor.cursor_row = 3;
app.editor.cursor_col = 0;
assert_eq!(
app.editor.select_all_occurrences_of_word_at_cursor(),
1,
"fn a's `fn` is outside"
);
assert!(app.editor.carets.is_empty());
app.editor.selection = None;
app.editor.add_cursor_above();
assert!(app.editor.carets.is_empty(), "no caret above the symbol");
for row in [0, 1] {
app.editor
.carets
.push(crate::widgets::editor::EditorSelection::new(row, 0));
}
app.editor.clamp_to_symbol_view();
assert!(app.editor.carets.is_empty(), "outside carets are dropped");
// Two copies of one inside caret, and one on the primary, leave one.
let (row, col) = (app.editor.cursor_row, app.editor.cursor_col);
for (r, c) in [(4, 0), (4, 0), (row, col)] {
app.editor
.carets
.push(crate::widgets::editor::EditorSelection::new(r, c));
}
app.editor.clamp_to_symbol_view();
assert_eq!(app.editor.carets.len(), 1, "duplicates are removed");
app.editor.carets.clear();
// Add Selection to Next Match finds no `fn` outside the symbol.
app.editor.cursor_row = 3;
app.editor.cursor_col = 0;
assert_eq!(app.editor.select_next_occurrence(), 1, "selects the word");
assert_eq!(
app.editor.select_next_occurrence(),
1,
"fn a's `fn` is outside"
);
assert!(app.editor.carets.is_empty());
}
/// #369: Add Cursor Below in a symbol tab stops at the symbol's last line,
/// with the rest of the file below it.
#[test]
fn add_cursor_below_stops_at_the_symbols_end() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("two.rs");
std::fs::write(&file, "fn a() {\n 1\n}\nfn b() {\n 2\n}").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.editor.cursor_row = 1;
app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
app.sync_symbol_views();
assert_eq!(app.editor.symbol_clip(), Some((0, 3)));
app.editor.cursor_row = 2;
app.editor.cursor_col = 0;
app.editor.add_cursor_below();
assert!(app.editor.carets.is_empty(), "fn b is not the tab's");
}
/// #369: a collaborator's edit is not the symbol tab's own. A line they
/// open at the start of the symbol's first line stays above the symbol.
#[test]
fn a_collaborators_edit_on_a_symbols_edge_is_not_the_tabs_own() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, _file) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
for ed in app.editor.editors.iter_mut() {
ed.apply_span_edits(&[crate::widgets::editor::TextSpanEdit {
start: (3, 0),
end: (3, 0),
new_text: String::from("\n"),
utf16: false,
}]);
// The local caret sits just past the new line, where a caret that
// had typed it would be.
ed.cursor_row = 4;
ed.cursor_col = 0;
ed.collab_doc_gen = 1;
ed.collab_synced_seq = ed.edit_seq;
}
app.sync_symbol_views();
let view = app.editor.editors[1].symbol_view.as_ref().unwrap();
assert_eq!(
(view.first, view.last),
(4, 6),
"the new line is above fn b"
);
}
/// #369: an edit on a symbol's edge lands on the side its caret is on.
///
/// Enter at the end of the symbol, typed in its own tab, opens a line the
/// tab keeps showing, so the caret stays on it; Enter at the start of the
/// symbol's first line, typed in the file's tab, opens a line above it that
/// the clip leaves out.
#[test]
fn a_line_opened_on_a_symbols_edge_goes_where_the_caret_is() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, _) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
app.editor.cursor_row = 5;
app.editor.cursor_col = 1;
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('z'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines[6], "z", "the caret stayed on the new line");
assert_eq!(app.editor.cursor_row, 6);
let view = app.editor.editors[1].symbol_view.as_ref().unwrap();
assert_eq!((view.first, view.last), (3, 6), "the symbol grew");
app.editor.select(0);
app.editor.cursor_row = 3;
app.editor.cursor_col = 0;
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
let view = app.editor.editors[1].symbol_view.as_ref().unwrap();
assert_eq!(
(view.first, view.last),
(4, 7),
"the opened line is above the symbol"
);
}
/// #369: a mirrored tab undoes as far as the tab that was typed in.
///
/// A typing burst is one undo step where it was typed, so it is one step in
/// the file's tab too, and a selection away from the edit survives it.
#[test]
fn a_mirrored_typing_burst_is_one_undo_step_and_keeps_a_distant_selection() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, _) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
let before = app.editor.lines.clone();
let mut sel = crate::widgets::editor::EditorSelection::new(0, 0);
sel.head = (0, 4);
app.editor.editors[0].selection = Some(sel);
app.editor.cursor_row = 4;
app.editor.cursor_col = 5;
for c in ['a', 'b', 'c'] {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
assert_eq!(app.editor.editors[0].lines[4], " 2abc");
assert_eq!(
app.editor.editors[0].selection,
Some(sel),
"a selection clear of the edit is kept"
);
assert!(app.editor.editors[0].undo());
assert!(app.editor.editors[1].undo());
assert_eq!(app.editor.editors[1].lines, before);
assert_eq!(
app.editor.editors[0].lines, before,
"one undo takes back the whole burst in the file's tab too"
);
}
/// #369: Join Lines, a counted line delete, find and Replace All stay
/// inside the symbol.
#[test]
fn line_joins_counted_deletes_and_find_stay_in_the_symbol() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("two.rs");
std::fs::write(&file, "fn a() {\n 1\n}\nfn b() {\n 2\n}").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.editor.cursor_row = 1;
app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
assert_eq!(app.editor.symbol_clip(), Some((0, 3)));
let before = app.editor.lines.clone();
app.editor.cursor_row = 2;
app.editor.join_lines();
assert_eq!(app.editor.lines, before, "the last line joins nothing");
// Find wraps within the symbol: from `fn a`'s `}`, the next `}` is
// that same one, not `fn b`'s.
let opts = crate::widgets::search::SearchOpts::default();
let m = app.editor_find_step(true, "}", opts, 2, 0, true).unwrap();
assert_eq!(m.row, 2);
let mut find = crate::widgets::editor_find::EditorFind::new("fn".into(), opts);
find.replace_visible = true;
find.replace = "FN".into();
app.editor_find = Some(find);
app.editor_find_replace_all();
assert_eq!(app.editor.lines[0], "FN a() {");
assert_eq!(app.editor.lines[3], "fn b() {", "outside the symbol");
app.editor.cursor_row = 1;
app.editor.delete_lines(10);
assert_eq!(
app.editor.lines,
["FN a() {", "fn b() {", " 2", "}"],
"the count stops at the symbol's end"
);
}
/// #369: two symbol tabs of one file with no file tab restore as ONE tab.
#[test]
fn session_capture_keeps_one_tab_for_orphaned_symbol_tabs_of_a_file() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.editor.close_tab(0);
app.open_symbol_tab_for("a".into(), 0, 2);
assert_eq!(app.editor.editors.len(), 2);
let state = app.capture_session_state();
assert_eq!(state.tabs.len(), 1);
assert_eq!(state.tabs[0].path.as_ref(), Some(&file));
}
/// #369: deleting a symbol tab's whole symbol closes the tab while a tab of
/// the whole file still holds the text.
#[test]
fn a_symbol_tab_whose_symbol_is_gone_closes() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, _file) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
assert_eq!(app.editor.editors.len(), 2);
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
.unwrap();
app.sync_symbol_views();
assert_eq!(app.editor.editors.len(), 1, "{}", app.status);
assert!(app.status.contains("that symbol is gone"), "{}", app.status);
assert!(app.editor.symbol_view.is_none());
}
/// #369: a symbol tab left as the only tab of its file keeps its unsaved
/// edits when its symbol is deleted: it becomes a tab of the whole file
/// instead of closing and taking them with it.
#[test]
fn an_orphaned_symbol_tab_with_unsaved_edits_survives_its_symbol() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
// An edit outside the symbol, made in the file tab and mirrored in.
app.editor.select(0);
app.editor.cursor_row = 1;
app.editor.cursor_col = 5;
app.handle_key(key(KeyCode::Char('9'), KeyModifiers::NONE))
.unwrap();
app.sync_symbol_views();
app.editor.close_tab(0);
assert!(
app.editor.symbol_view.is_some(),
"only the symbol tab is left"
);
assert!(app.editor.dirty);
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
.unwrap();
app.sync_symbol_views();
assert_eq!(app.editor.editors.len(), 1, "the tab stays: {}", app.status);
assert!(
app.editor.symbol_view.is_none(),
"it shows the whole file now"
);
assert_eq!(app.editor.path.as_deref(), Some(file.as_path()));
assert_eq!(
app.editor.lines[1], " 19",
"the out-of-clip edit survives"
);
assert!(app.editor.dirty);
assert!(app.status.contains("whole file"), "{}", app.status);
}
/// #369: a tab that turned into a whole-file tab keeps the keys typed
/// right after, in the same burst, while another symbol tab of its file is
/// still open to mirror against.
#[test]
fn a_kept_orphan_keeps_the_next_keys_beside_a_sibling_symbol_tab() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
app.editor.select(0);
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
app.sync_symbol_views();
let whole = |app: &App| {
app.editor
.editors
.iter()
.position(|e| e.symbol_view.is_none())
};
app.editor.close_tab(whole(&app).expect("the file tab"));
assert_eq!(app.editor.editors.len(), 2, "two symbol tabs are left");
let b = app
.editor
.editors
.iter()
.position(|e| e.symbol_view.as_ref().is_some_and(|v| v.name == "b"))
.expect("the b tab");
app.editor.select(b);
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
let kept = whole(&app).expect("the b tab became a file tab");
assert_eq!(
app.editor.editors[kept].path.as_deref(),
Some(file.as_path())
);
assert!(
app.editor.editors[kept].lines.iter().any(|l| l == "x"),
"{:?}",
app.editor.editors[kept].lines
);
}
/// #369: one symbol's tabs in two groups, with no file tab left in either:
/// deleting the symbol keeps one of them as the file's tab, and the other,
/// whose edits that tab now holds, closes and folds its group away.
#[test]
fn one_symbols_tabs_in_two_groups_keep_a_single_file_tab() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
app.split_editor();
app.editor.cursor_row = 4;
app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
app.sync_symbol_views();
let file_tab = |tabs: &crate::widgets::editor::EditorTabs| {
tabs.editors
.iter()
.position(|e| e.symbol_view.is_none())
.expect("the file tab")
};
let i = file_tab(&app.editor);
app.editor.close_tab(i);
let other = &mut app.editor_layout.inactive_groups_mut()[0];
let i = file_tab(other);
other.close_tab(i);
assert_eq!(app.editor.editors.len(), 1);
assert_eq!(app.editor_layout.inactive_groups()[0].editors.len(), 1);
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
.unwrap();
assert!(
app.editor_layout.inactive_groups().is_empty(),
"the other copy closed and its group folded away"
);
assert_eq!(app.editor.editors.len(), 1);
let kept = &app.editor.editors[0];
assert!(kept.symbol_view.is_none() && kept.dirty);
assert_eq!(kept.path.as_deref(), Some(file.as_path()));
assert!(app.status.contains("whole file"), "{}", app.status);
}
/// Opens `impl S` and `fn m` as symbol tabs, closes the file tab, deletes
/// m's line from the impl tab one Backspace at a time (m goes on the last
/// one), then presses undo once in the impl tab or in the m tab (by then
/// the file's tab); hands back the line undo left.
fn undo_once_after_m_goes(in_kept: bool) -> String {
fn tab(app: &App, name: &str) -> Option<usize> {
app.editor
.editors
.iter()
.position(|e| e.symbol_view.as_ref().is_some_and(|v| v.name == name))
}
let m_line = " fn m() {}";
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("s.rs");
std::fs::write(&file, format!("impl S {{\n{m_line}\n}}\n")).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
for row in [1, 0] {
app.editor.select(0);
app.editor.cursor_row = row;
app.editor.cursor_col = 0;
app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
app.sync_symbol_views();
}
let i = app
.editor
.editors
.iter()
.position(|e| e.symbol_view.is_none())
.expect("the file tab");
app.editor.close_tab(i);
let imp = tab(&app, "S").expect("the impl tab");
app.editor.select(imp);
app.editor.cursor_row = 1;
app.editor.cursor_col = m_line.chars().count();
app.focus_pane(Pane::Editor);
for _ in 0..m_line.chars().count() {
app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
.unwrap();
}
assert!(tab(&app, "m").is_none(), "m is gone");
let kept = app
.editor
.editors
.iter()
.position(|e| e.symbol_view.is_none())
.expect("the m tab became the file tab");
assert_eq!(
app.editor.editors[kept].lines[1], "",
"the kept tab mirrors the emptied line"
);
let at = if in_kept {
kept
} else {
tab(&app, "S").expect("the impl tab")
};
app.editor.select(at);
app.handle_key(key(KeyCode::Char('z'), KeyModifiers::SUPER))
.unwrap();
app.editor.lines[1].clone()
}
/// #369: a method's symbol tab kept as the file's tab while the impl tab's
/// Backspaces delete the method keeps taking one undo step per Backspace,
/// so one undo there walks back as far as it does in the impl tab. m goes
/// on the last Backspace, in the pass that last mirrored it: the kept tab
/// must stay a mirror member (its `mirror_seq` kept), or its undo is
/// overwritten by the impl tab's text.
#[test]
fn a_kept_orphan_undoes_the_backspaces_that_deleted_its_symbol_like_its_sibling() {
let in_impl = undo_once_after_m_goes(false);
assert_ne!(
in_impl, "",
"undo in the impl tab restores part of the line"
);
assert_eq!(undo_once_after_m_goes(true), in_impl);
}
/// #369: a clean symbol tab whose symbol goes closes even with no file
/// tab open: it holds nothing the disk does not.
#[test]
fn a_clean_orphaned_symbol_tab_closes_when_its_symbol_goes() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.sync_symbol_views();
app.editor.close_tab(0);
assert!(app.editor.symbol_view.is_some() && !app.editor.dirty);
std::fs::write(&file, "fn a() {\n 1\n}\n").unwrap();
app.editor.reload_if_clean().unwrap().unwrap();
app.sync_symbol_views();
assert!(
app.editor.editors.iter().all(|e| e.path.is_none()),
"{}",
app.status
);
assert!(app.status.contains("that symbol is gone"), "{}", app.status);
}
/// #369: going to a file lands on the tab that shows ALL of it.
///
/// A symbol tab has the file's path, and the tab lookups behind opening,
/// previewing and selecting a file would otherwise pick it and show a jump
/// target that sits outside its clip as the clip's nearest edge.
#[test]
fn opening_a_file_never_lands_in_its_symbol_tab() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, file) = app_with_symbol_tab_on_b(&tmp);
app.editor.close_tab(0);
assert!(
app.editor.editors[0].symbol_view.is_some(),
"only the symbol tab is left"
);
app.open_at_utf16(&file, 0, 0).unwrap();
assert!(
app.editor.symbol_view.is_none(),
"the jump opened a tab of the whole file"
);
assert_eq!(app.editor.cursor_row, 0, "and landed where it was sent");
assert_eq!(
app.editor.editors.len(),
2,
"the symbol tab stays open beside it"
);
}
/// #363: a fleet run does not block the event loop, and its results arrive
/// through the channel like every other background answer.
///
/// The blocking version is the tempting one — `run_on_hosts` returns a
/// `Vec`, so calling it inline reads naturally — and it freezes the editor
/// for up to `FLEET_TIMEOUT` while the network answers. The user could not
/// scroll, type, or cancel. This asserts the split: the command returns at
/// once, and a later drain reports.
#[test]
fn a_fleet_run_reports_through_the_channel_rather_than_blocking() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Nothing in flight: a drain finds nothing and says so, rather than
// blocking or inventing an empty result.
assert!(!app.drain_fleet_results(), "no run, nothing to report");
// Feed a result as the worker thread would.
let results = vec![
crate::fleet::HostResult {
host: String::from("a"),
output: String::from("5.15.0"),
exit: Some(0),
elapsed: std::time::Duration::ZERO,
},
crate::fleet::HostResult {
host: String::from("b"),
output: String::from("5.15.0"),
exit: Some(0),
elapsed: std::time::Duration::ZERO,
},
crate::fleet::HostResult {
host: String::from("odd"),
output: String::from("6.1.0"),
exit: Some(0),
elapsed: std::time::Duration::ZERO,
},
crate::fleet::HostResult {
host: String::from("down"),
output: String::from("timed out"),
exit: None,
elapsed: std::time::Duration::ZERO,
},
];
app.fleet_running = true;
app.fleet_tx.send(results).unwrap();
assert!(app.drain_fleet_results(), "a delivered result must report");
assert!(!app.fleet_running, "the run is no longer in flight");
assert!(
app.status.contains("2 identical") && app.status.contains("1 differ"),
"the summary must reach the user: {}",
app.status
);
assert!(app.status.contains("1 failed"), "status: {}", app.status);
// And the channel is empty again, so a second drain is a no-op rather
// than replaying the same run.
assert!(!app.drain_fleet_results(), "results are consumed once");
}
/// #371: the scrubber's keys move through history, and anything else keeps
/// its normal meaning.
///
/// The consumed/not-consumed split is the point. A scrubber that swallowed
/// every key would be a mode, and the user would lose their editor to a
/// gesture they meant as a glance.
#[test]
fn the_scrubber_consumes_its_own_keys_and_no_others() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let fake = |h: &str, sum: &str| crate::git::GraphCommit {
hash: String::from(h),
short_hash: String::from(&h[..7]),
parents: Vec::new(),
refs: Vec::new(),
summary: String::from(sum),
author: String::from("t"),
age_secs: 0,
};
app.scrubber = Some(crate::scrubber::Scrubber::new(vec![
fake("aaaaaaa1", "newest"),
fake("bbbbbbb2", "older"),
]));
// Left steps back and lands on HEAD, not past it.
assert!(app.handle_scrubber_key(KeyCode::Left));
assert_eq!(
app.scrubber.as_ref().unwrap().position(),
crate::scrubber::Position::At(0)
);
assert!(app.status.contains("aaaaaaa"), "status: {}", app.status);
assert!(
app.status.contains("newest"),
"the summary helps: {}",
app.status
);
// Home returns to the working tree from anywhere.
assert!(app.handle_scrubber_key(KeyCode::Left));
assert!(app.handle_scrubber_key(KeyCode::Home));
assert_eq!(
app.scrubber.as_ref().unwrap().position(),
crate::scrubber::Position::Working
);
// A key the scrubber does not use is NOT consumed, so it still means
// whatever it meant before.
assert!(
!app.handle_scrubber_key(KeyCode::Char('x')),
"an unrelated key must pass through"
);
assert!(app.scrubber.is_some(), "and must not close the scrubber");
// Esc closes, and the live buffer is simply what is there — the
// scrubber never replaced it, so closing cannot lose unsaved work.
assert!(app.handle_scrubber_key(KeyCode::Esc));
assert!(app.scrubber.is_none());
// With no scrubber open, its keys are not consumed either.
assert!(!app.handle_scrubber_key(KeyCode::Left));
}
/// #345: the Explorer's unreviewed dots track the ledger, on every path
/// that changes it.
///
/// The predicate and the painting are tested in `file_tree`; this is the
/// wiring between them, which is where a decoration feature actually breaks.
/// A dot that lags the ledger is worse than no dot at all, because "no dot"
/// is precisely what a reviewed file looks like — so a stale one tells the
/// user they have reviewed something they have not.
///
/// **The drain is driven for real, not stood in for.** An earlier version of
/// this test called `attribute_writes_to_working_agents` and then
/// `sync_agent_lane_decorations` by hand, which tests the helper and not the
/// wiring: deleting the drain's own sync left every assertion passing. Since
/// the drain is the path that fires on every agent write, that was the one
/// call site the feature cannot afford to have untested.
#[test]
fn the_explorer_dots_follow_the_agent_ledger() {
let tmp = tempfile::tempdir().unwrap();
let touched = tmp.path().join("touched.rs");
std::fs::write(&touched, "fn a() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(
app.tree.agent_touched.is_empty(),
"staging: nothing decorated before an agent writes"
);
app.terminals[0].set_agent(Some(crate::agents::AgentLane {
name: String::from("claude"),
status: crate::agents::AgentStatus::Working,
}));
// Let the watcher establish itself first, as the other fs-watch tests
// do: a write racing the initial registration is simply not delivered,
// which would make this test flaky rather than wrong.
for _ in 0..20 {
let _ = app.drain_fs_events();
std::thread::sleep(std::time::Duration::from_millis(10));
}
// Through the real drain: write the file, let the watcher deliver it,
// and call the function the event loop calls. No explicit sync here —
// that is the property under test.
std::fs::write(&touched, "fn a() { todo!() }\n").unwrap();
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the watcher event to reach the tree",
|| {
app.drain_fs_events();
app.tree.agent_touched.contains(&touched)
},
);
assert!(
app.tree.agent_touched.contains(&touched),
"the drain must light the row it attributed, without a nudge \
(ledger has {} unreviewed)",
app.agent_ledger.unreviewed_files()
);
assert!(app.tree.is_agent_touched(&touched));
// The chip counts the set the tree draws. Asserted HERE, where both
// sides are 1: after the lane is cleared below they are both 0, and an
// equality that only ever compares 0 to 0 cannot fail.
assert_eq!(
app.agent_ledger.unreviewed_files(),
app.tree.agent_touched.len(),
"the badge and the dots must be the same number"
);
// Reviewing goes through the public entry point, which syncs itself.
assert!(app.mark_agent_file_reviewed("claude", &touched));
assert!(
!app.tree.agent_touched.contains(&touched),
"marking reviewed must clear the dot without a further nudge"
);
// Mark-the-whole-lane reviewed is the other syncing entry point.
let mut changed = std::collections::BTreeSet::new();
changed.insert(touched.clone());
std::fs::write(&touched, "fn a() { 1 }\n").unwrap();
assert!(app.attribute_writes_to_working_agents(&changed));
app.sync_agent_lane_decorations();
assert!(
app.tree.agent_touched.contains(&touched),
"staging: lit again"
);
app.mark_agent_lane_reviewed("claude");
assert!(
app.tree.agent_touched.is_empty(),
"marking the lane reviewed must clear every dot"
);
}
/// #345: a write reported through a symlinked root is still attributed.
///
/// Found by driving the real fs-watch drain rather than calling the
/// attribution helper directly. The watcher reports a file's REALPATH while
/// a root is stored as the user spelled it, so a workspace reached through a
/// symlink — `/var` on macOS, which is `/private/var`, and any symlinked
/// checkout on Linux — matched no root and every agent write was dropped.
/// The queue stayed empty and nothing failed, which is why a test that
/// substituted for the drain could not see it.
#[test]
#[cfg(unix)]
fn a_write_under_a_symlinked_root_is_still_the_agents() {
let tmp = tempfile::tempdir().unwrap();
let real = tmp.path().join("real");
std::fs::create_dir(&real).unwrap();
let link = tmp.path().join("link");
std::os::unix::fs::symlink(&real, &link).unwrap();
// The workspace is opened through the LINK; the file is written and
// reported through the real path, as a watcher would.
let via_link = link.join("f.rs");
std::fs::write(&via_link, "fn a() {}\n").unwrap();
let mut app = App::new(link.clone()).unwrap();
app.terminals[0].set_agent(Some(crate::agents::AgentLane {
name: String::from("claude"),
status: crate::agents::AgentStatus::Working,
}));
let mut changed = std::collections::BTreeSet::new();
changed.insert(real.join("f.rs"));
assert!(
app.attribute_writes_to_working_agents(&changed),
"a realpath write under a symlinked root must still be attributed"
);
// And it is keyed the way the ROOT is spelled, so the Explorer's rows —
// which come from the tree, not the watcher — find it.
app.sync_agent_lane_decorations();
assert!(
app.tree.agent_touched.contains(&via_link),
"the ledger keyed the row under the realpath, so no tree row matches \
it: {:?}",
app.tree.agent_touched
);
// And a DELETION clears it. `canonicalize` stats the final component, so
// resolving the whole path fails on a file that is gone — which would
// make the ledger's forget-path arm unreachable and strand the row on a
// file that no longer exists, with no later write able to clear it. That
// is strictly worse than the original bug, which dropped writes and
// deletions alike and so at least stayed self-consistent.
std::fs::remove_file(&via_link).unwrap();
assert!(
app.attribute_writes_to_working_agents(&changed),
"a deletion reported by realpath must reach the ledger too"
);
app.sync_agent_lane_decorations();
assert!(
app.tree.agent_touched.is_empty(),
"the row outlived the file it described: {:?}",
app.tree.agent_touched
);
// The parent going too, which makes the walk climb more than one level.
// A tail-reattachment bug hides here rather than in the single-level
// case: the key the delete resolves to must still be the key the write
// created, or `forget_path` finds nothing to forget.
let sub = link.join("sub");
std::fs::create_dir(&sub).unwrap();
let nested = sub.join("g.rs");
std::fs::write(&nested, "fn g() {}\n").unwrap();
let mut deep = std::collections::BTreeSet::new();
deep.insert(real.join("sub/g.rs"));
assert!(app.attribute_writes_to_working_agents(&deep));
app.sync_agent_lane_decorations();
assert!(
app.tree.agent_touched.contains(&nested),
"staging: the nested file is queued"
);
std::fs::remove_dir_all(&sub).unwrap();
assert!(
app.attribute_writes_to_working_agents(&deep),
"a deletion whose PARENT is gone must still resolve"
);
app.sync_agent_lane_decorations();
assert!(
app.tree.agent_touched.is_empty(),
"the row outlived its whole directory: {:?}",
app.tree.agent_touched
);
}
/// #345: removing a workspace folder takes its review queue with it.
///
/// The rows leave the tree on their own, so no stale dot renders — but the
/// status chip counts the same set, and a count that outlives the folder it
/// describes sends the user hunting for rows that are not there.
#[test]
fn removing_a_folder_drops_its_rows_from_the_review_queue() {
let primary = tempfile::tempdir().unwrap();
let secondary = tempfile::tempdir().unwrap();
let in_second = secondary.path().join("s.rs");
std::fs::write(&in_second, "fn s() {}\n").unwrap();
let mut app = App::new(primary.path().to_path_buf()).unwrap();
app.roots.add(secondary.path().to_path_buf());
app.terminals[0].set_agent(Some(crate::agents::AgentLane {
name: String::from("claude"),
status: crate::agents::AgentStatus::Working,
}));
let mut changed = std::collections::BTreeSet::new();
changed.insert(in_second.clone());
assert!(app.attribute_writes_to_working_agents(&changed));
app.sync_agent_lane_decorations();
assert_eq!(
app.tree.agent_touched.len(),
1,
"staging: the secondary root's file is queued"
);
app.remove_workspace_folder(secondary.path().to_path_buf());
assert!(
app.tree.agent_touched.is_empty(),
"the removed folder's rows outlived it: {:?}",
app.tree.agent_touched
);
assert_eq!(app.agent_ledger.unreviewed_files(), 0);
}
/// #345: a re-root leaves no dots from the workspace the user left.
///
/// The paths in the set are ABSOLUTE, and Make Root's documented use is
/// re-rooting into a CHILD — where the new tree's paths are exactly the ones
/// still in the set. Left behind, every stale dot re-renders on the new tree
/// describing a lane that is gone, which is the precise staleness this
/// decoration exists to avoid.
#[test]
fn a_re_root_drops_the_previous_workspaces_review_queue() {
let tmp = tempfile::tempdir().unwrap();
let child = tmp.path().join("child");
std::fs::create_dir(&child).unwrap();
let inside = child.join("in_child.rs");
std::fs::write(&inside, "fn a() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0].set_agent(Some(crate::agents::AgentLane {
name: String::from("claude"),
status: crate::agents::AgentStatus::Working,
}));
let mut changed = std::collections::BTreeSet::new();
changed.insert(inside.clone());
assert!(app.attribute_writes_to_working_agents(&changed));
app.sync_agent_lane_decorations();
assert!(
app.tree.agent_touched.contains(&inside),
"staging: the file is decorated before the re-root"
);
// Re-root INTO the child: the file's absolute path is unchanged and it
// is still on screen, so a surviving set would re-decorate it.
app.change_workspace_root(child.clone());
assert!(
app.tree.agent_touched.is_empty(),
"the Explorer kept the old workspace's dots: {:?}",
app.tree.agent_touched
);
assert_eq!(
app.agent_ledger.unreviewed_files(),
0,
"the ledger kept the old workspace's queue"
);
assert!(!app.tree.is_agent_touched(&inside));
}
/// #345: the agent lane attributes workspace writes to whichever agents
/// were WORKING when they landed, keeps a review baseline per file, and
/// never blames an agent for the user's own saves.
#[test]
fn the_agent_lane_ledger_attributes_writes_and_tracks_review_baselines() {
let tmp = tempfile::tempdir().unwrap();
let touched = tmp.path().join("touched.rs");
std::fs::write(&touched, "fn a() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// With no agent working, a write belongs to the user: no lane at all.
let mut changed = std::collections::BTreeSet::new();
changed.insert(touched.clone());
assert!(!app.attribute_writes_to_working_agents(&changed));
assert!(app.agent_ledger.agents().is_empty());
// Seat a WORKING agent in the pane, then replay the same write.
app.terminals[0].set_agent(Some(crate::agents::AgentLane {
name: String::from("claude"),
status: crate::agents::AgentStatus::Working,
}));
assert_eq!(app.working_agents(), vec![String::from("claude")]);
assert!(app.attribute_writes_to_working_agents(&changed));
assert_eq!(app.agent_ledger.unreviewed_count("claude"), 1);
assert!(app.agent_ledger.is_unreviewed(&touched));
// A SECONDARY workspace root's files are attributed too: a multi-root
// session must not have an empty queue for every folder but the first.
let second = tempfile::tempdir().unwrap();
let in_second = second.path().join("lib.rs");
std::fs::write(&in_second, "fn b() {}\n").unwrap();
app.roots.add(second.path().to_path_buf());
let mut second_set = std::collections::BTreeSet::new();
second_set.insert(in_second.clone());
assert!(
app.attribute_writes_to_working_agents(&second_set),
"a write under a secondary root is still the agent's"
);
assert!(app.agent_ledger.is_unreviewed(&in_second));
app.mark_agent_file_reviewed("claude", &in_second);
// A file OUTSIDE the workspace is not this workspace's review queue.
let outside = tempfile::tempdir().unwrap();
let stray = outside.path().join("elsewhere.rs");
std::fs::write(&stray, "x\n").unwrap();
let mut outside_set = std::collections::BTreeSet::new();
outside_set.insert(stray.clone());
assert!(!app.attribute_writes_to_working_agents(&outside_set));
assert!(!app.agent_ledger.is_unreviewed(&stray));
// Reviewing baselines the content on disk NOW, so a later edit by the
// user does not resurrect the row but a later agent write does.
assert!(app.mark_agent_file_reviewed("claude", &touched));
assert_eq!(app.agent_ledger.unreviewed_count("claude"), 0);
std::fs::write(&touched, "fn a() { todo!() }\n").unwrap();
assert!(app.attribute_writes_to_working_agents(&changed));
assert_eq!(
app.agent_ledger.unreviewed_count("claude"),
1,
"a fresh agent write re-queues the file"
);
// A file DELETED after its agent goes idle still leaves the queue: the
// row would otherwise point at a file that is not there forever, since
// a deleted file generates no later write to clear it.
let later = tmp.path().join("later.rs");
std::fs::write(&later, "fn c() {}\n").unwrap();
let mut later_set = std::collections::BTreeSet::new();
later_set.insert(later.clone());
assert!(app.attribute_writes_to_working_agents(&later_set));
assert!(app.agent_ledger.is_unreviewed(&later));
app.terminals[0].set_agent(Some(crate::agents::AgentLane {
name: String::from("claude"),
status: crate::agents::AgentStatus::Idle,
}));
std::fs::remove_file(&later).unwrap();
assert!(
app.attribute_writes_to_working_agents(&later_set),
"a deletion is processed with no agent working"
);
assert!(
!app.agent_ledger.is_unreviewed(&later),
"the row leaves rather than stranding"
);
app.terminals[0].set_agent(Some(crate::agents::AgentLane {
name: String::from("claude"),
status: crate::agents::AgentStatus::Working,
}));
// A QUIET agent stops being attributed: only Working counts.
app.terminals[0].set_agent(Some(crate::agents::AgentLane {
name: String::from("claude"),
status: crate::agents::AgentStatus::Idle,
}));
assert!(app.working_agents().is_empty());
std::fs::write(&touched, "fn a() { 1 }\n").unwrap();
assert!(!app.attribute_writes_to_working_agents(&changed));
// Mark-all clears the lane and says how much it cleared.
assert_eq!(app.mark_agent_lane_reviewed("claude"), 1);
assert!(
app.status.contains("1 file marked reviewed"),
"{}",
app.status
);
assert_eq!(app.agent_ledger.total_unreviewed(), 0);
assert_eq!(app.mark_agent_lane_reviewed("claude"), 0);
assert!(app.status.contains("nothing waiting"), "{}", app.status);
// The lane summary names each agent, its count, and any shared row.
app.terminals[0].set_agent(Some(crate::agents::AgentLane {
name: String::from("claude"),
status: crate::agents::AgentStatus::Working,
}));
std::fs::write(&touched, "fn a() { 2 }\n").unwrap();
assert!(app.attribute_writes_to_working_agents(&changed));
app.run_command(crate::widgets::command_palette::Command::ShowAgentLane);
assert!(
app.status.contains("claude: 1 to review") && app.status.contains("touched.rs"),
"{}",
app.status
);
// "Mark this file reviewed" acts on the ACTIVE file, in every lane
// holding it, and refuses when there is nothing waiting.
app.editor.open_pinned(&touched).unwrap();
app.run_command(crate::widgets::command_palette::Command::MarkAgentFileReviewed);
assert!(
app.status.contains("marked reviewed in 1 agent lane"),
"{}",
app.status
);
assert_eq!(app.agent_ledger.total_unreviewed(), 0);
app.run_command(crate::widgets::command_palette::Command::MarkAgentFileReviewed);
assert!(
app.status.contains("No agent change waiting"),
"{}",
app.status
);
// The palette commands are registered.
for (cmd, id) in [
(
crate::widgets::command_palette::Command::MarkAgentLaneReviewed,
"agents_mark_reviewed",
),
(
crate::widgets::command_palette::Command::ShowAgentLane,
"agents_show_lane",
),
(
crate::widgets::command_palette::Command::MarkAgentFileReviewed,
"agents_mark_file_reviewed",
),
] {
assert!(crate::widgets::command_palette::ALL_COMMANDS.contains(&cmd));
assert_eq!(cmd.id(), id);
}
}
/// #345: the watcher's three ledger-facing behaviours, driven through the
/// real drain rather than asserted about by reading it.
///
/// A rescan means events were DROPPED, so the queue is a lower bound and
/// the ledger must record that durably; a removed directory is not a file
/// and must not enter a file-only ledger; and a removed FILE must still be
/// reported, so the row can leave the queue.
#[test]
fn the_watcher_reports_rescans_and_keeps_directories_out_of_the_ledger() {
use notify::Event as NotifyEvent;
use notify::event::{EventKind, ModifyKind, RemoveKind};
use notify_debouncer_full::DebouncedEvent;
use std::sync::mpsc;
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("touched.rs");
std::fs::write(&file, "fn a() {}\n").unwrap();
let doomed_dir = tmp.path().join("subdir");
std::fs::create_dir(&doomed_dir).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0].set_agent(Some(crate::agents::AgentLane {
name: String::from("claude"),
status: crate::agents::AgentStatus::Working,
}));
let (tx, rx) = mpsc::channel();
app.fs_watch.set_test_events(rx);
// A removed directory, a removed file, and an ordinary write.
let mut dir_gone = NotifyEvent::new(EventKind::Remove(RemoveKind::Folder));
dir_gone = dir_gone.add_path(doomed_dir.clone());
let mut written = NotifyEvent::new(EventKind::Modify(ModifyKind::Any));
written = written.add_path(file.clone());
let now = std::time::Instant::now();
tx.send(Ok(vec![
DebouncedEvent::new(dir_gone, now),
DebouncedEvent::new(written, now),
]))
.unwrap();
app.drain_fs_events();
assert!(
app.agent_ledger.is_unreviewed(&file),
"the written file is attributed to the working agent"
);
assert!(
!app.agent_ledger.is_unreviewed(&doomed_dir),
"a removed DIRECTORY must not enter a file-only ledger"
);
assert!(
!app.agent_ledger.may_be_incomplete(),
"no rescan yet, so the queue is not a lower bound"
);
// A removed FILE that IS in a lane leaves it the moment the removal is
// seen: a deleted file generates no later write, so a guard that
// excluded its event would strand the row in the queue forever.
let doomed = tmp.path().join("doomed.rs");
std::fs::write(&doomed, "fn gone() {}\n").unwrap();
let mut doomed_set = std::collections::BTreeSet::new();
doomed_set.insert(doomed.clone());
assert!(app.attribute_writes_to_working_agents(&doomed_set));
assert!(app.agent_ledger.is_unreviewed(&doomed));
std::fs::remove_file(&doomed).unwrap();
let (tx3, rx3) = mpsc::channel();
app.fs_watch.set_test_events(rx3);
// `Any` is what kqueue, the Windows watcher and the poll fallback emit
// for every removal, so this is the shape three of five backends send.
let removed = NotifyEvent::new(EventKind::Remove(RemoveKind::Any)).add_path(doomed.clone());
tx3.send(Ok(vec![DebouncedEvent::new(
removed,
std::time::Instant::now(),
)]))
.unwrap();
app.drain_fs_events();
assert!(
!app.agent_ledger.is_unreviewed(&doomed),
"the removed file's row leaves the queue rather than stranding"
);
// Now a rescan: the watcher overflowed and dropped events.
let (tx2, rx2) = mpsc::channel();
app.fs_watch.set_test_events(rx2);
let rescan = NotifyEvent::new(EventKind::Modify(ModifyKind::Any))
.add_path(file.clone())
.set_flag(notify::event::Flag::Rescan);
tx2.send(Ok(vec![DebouncedEvent::new(
rescan,
std::time::Instant::now(),
)]))
.unwrap();
app.drain_fs_events();
assert!(
app.agent_ledger.may_be_incomplete(),
"a rescan makes every count a lower bound, durably"
);
// And the doubt survives an unrelated status change, which is the
// point of holding it in the ledger rather than the status line.
app.status = String::from("something else entirely");
assert!(app.agent_ledger.may_be_incomplete());
}
/// #373: "Debug This Test" breaks where the test last failed, without the
/// user setting a breakpoint — and takes that breakpoint back out when the
/// session ends, so it never outlives the run that asked for it.
#[test]
fn debugging_a_test_breaks_at_its_last_failure_and_cleans_up_after() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
let src = tmp.path().join("src/lib.rs");
std::fs::write(&src, "fn a() {}\nfn b() {}\nassert!(false);\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// The runner's output for a failing test, as it reaches the channel.
crate::output::clear(crate::output::CHANNEL_TESTS);
for line in [
"---- tests::adds stdout ----",
"thread 'tests::adds' panicked at src/lib.rs:3:5:",
"assertion failed: false",
] {
crate::output::push(
crate::output::CHANNEL_TESTS,
crate::output::OutputLevel::Info,
line,
);
}
let site = app
.failure_site_of("tests::adds")
.expect("the panic line names a place in the user's own code");
assert_eq!(site.line, 3);
assert_eq!(site.resolve(tmp.path()), Some((src.clone(), 3)));
// Arming sets the breakpoint and says where.
assert!(app.editor.breakpoints.is_empty());
app.arm_failure_breakpoint("tests::adds", tmp.path());
assert_eq!(
app.editor.breakpoints.get(&src).map(|l| l.contains(&3)),
Some(true),
"the assertion's line carries a breakpoint the user never set"
);
// The note rides on whichever launch message the user actually sees:
// setting it as the status here would be overwritten moments later.
assert!(
app.with_failure_note(String::from("Building"))
.contains("breaking at lib.rs:3 where it last failed"),
"{}",
app.with_failure_note(String::from("Building"))
);
// Disarming takes back exactly that one, leaving no empty entry, and
// drops the note with it.
app.disarm_failure_breakpoint();
assert_eq!(app.with_failure_note(String::from("Building")), "Building");
assert!(
app.editor.breakpoints.is_empty(),
"the temporary breakpoint does not outlive its session"
);
// A breakpoint the USER set at the same line is theirs: arming must not
// adopt it, and disarming must not delete their work.
app.editor
.breakpoints
.entry(src.clone())
.or_default()
.insert(3);
app.arm_failure_breakpoint("tests::adds", tmp.path());
app.disarm_failure_breakpoint();
assert_eq!(
app.editor.breakpoints.get(&src).map(|l| l.contains(&3)),
Some(true),
"the user's own breakpoint survives a debug session that shared its line"
);
app.editor.breakpoints.clear();
// A failure in a dependency names nothing actionable, so nothing is set.
crate::output::clear(crate::output::CHANNEL_TESTS);
for line in [
"---- tests::deps stdout ----",
"thread 'tests::deps' panicked at /Users/me/.cargo/registry/src/x-1.0/lib.rs:9:1:",
] {
crate::output::push(
crate::output::CHANNEL_TESTS,
crate::output::OutputLevel::Info,
line,
);
}
assert!(app.failure_site_of("tests::deps").is_none());
app.arm_failure_breakpoint("tests::deps", tmp.path());
assert!(
app.editor.breakpoints.is_empty(),
"a location inside a dependency is not offered as a breakpoint"
);
// The palette carries the command that reaches all of this.
assert!(
crate::widgets::command_palette::ALL_COMMANDS
.contains(&crate::widgets::command_palette::Command::DebugTestAtCursor)
);
}
/// #373: the site must be found in AUTHENTIC runner output, summary and
/// all. libtest reprints every failing test's name in a trailing
/// `failures:` block, so a scan anchored on "the last line mentioning the
/// name" lands after every stdout block and finds nothing — the feature
/// silently does nothing for the ecosystem it was written for. This is
/// the regression test for that.
#[test]
fn the_failure_site_survives_a_whole_cargo_test_run() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
std::fs::write(tmp.path().join("src/lib.rs"), "a\nb\nc\n").unwrap();
std::fs::write(tmp.path().join("src/other.rs"), "x\ny\nz\n").unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
crate::output::clear(crate::output::CHANNEL_TESTS);
for line in [
" Compiling demo v0.1.0",
" Finished test profile [unoptimized + debuginfo]",
" Running unittests src/lib.rs",
"",
"running 2 tests",
"test tests::adds_two ... FAILED",
"test tests::adds ... FAILED",
"",
"failures:",
"",
"---- tests::adds_two stdout ----",
"thread 'tests::adds_two' panicked at src/other.rs:2:5:",
"assertion `left == right` failed",
"",
"---- tests::adds stdout ----",
"thread 'tests::adds' panicked at src/lib.rs:3:5:",
"assertion failed: false",
"note: run with `RUST_BACKTRACE=1` to display a backtrace",
"",
"failures:",
" tests::adds",
" tests::adds_two",
"",
"test result: FAILED. 0 passed; 2 failed; 0 ignored; 0 measured",
] {
crate::output::push(
crate::output::CHANNEL_TESTS,
crate::output::OutputLevel::Info,
line,
);
}
// The trailing summary must not swallow the block, and each test must
// get ITS OWN assertion — not the other's.
let adds = app
.failure_site_of("tests::adds")
.expect("the site survives the summary that follows every block");
assert_eq!(
(adds.file.to_string_lossy().into_owned(), adds.line),
(String::from("src/lib.rs"), 3)
);
let two = app
.failure_site_of("tests::adds_two")
.expect("and so does the other test's");
assert_eq!(
(two.file.to_string_lossy().into_owned(), two.line),
(String::from("src/other.rs"), 2),
"a name that is a PREFIX of another must not borrow its block"
);
// And a test that did not fail has no block at all.
assert!(app.failure_site_of("tests::passes").is_none());
}
/// #430: a task must not be typed into a pane whose shell has walked away
/// from the task's directory.
///
/// Both defects lived in `run_project_task`'s copy of a guard that #392
/// fixed only on the runnable-fence side: `starts_with` accepted any
/// DESCENDANT, so a shell that had `cd`'d into a subdirectory was reused
/// and the task ran there. The two callers now share `pane_is_idle_at`,
/// so a correction cannot land on one and miss the other.
#[test]
fn a_task_pane_whose_shell_left_the_directory_is_not_reused() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("Makefile"), "build:\n\ttrue\n").unwrap();
std::fs::create_dir_all(tmp.path().join("sub")).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let chord = key(
KeyCode::Char('B'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
);
app.handle_key(chord).unwrap();
// Wait for the pane's shell to reach its prompt, as the reuse path
// requires an idle pane.
let root = tmp.path().canonicalize().unwrap();
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"the task pane's shell",
|| {
let t = &app.terminals[app.active_terminal];
t.foreground_is_shell() && t.kernel_shell_cwd() == Some(root.clone())
},
);
let idx = app.active_terminal;
let label = app.terminals[idx].label().to_string();
// The control: standing in the task's own directory, the pane IS this
// task's pane.
assert!(
pane_is_idle_at(&app.terminals[idx], &label, &root),
"precondition: an idle pane at the task's own directory is reusable"
);
// Now walk the shell into a subdirectory, as a user reading a log or
// poking at a subcrate would.
app.terminals[idx].write_input(b"cd sub\r");
let sub = root.join("sub");
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"the shell to enter the subdirectory",
|| app.terminals[idx].kernel_shell_cwd() == Some(sub.clone()),
);
assert!(
!pane_is_idle_at(&app.terminals[idx], &label, &root),
"a shell that has left the task's directory is not the task's pane: \
`starts_with` accepted any descendant and ran the task in `sub`"
);
// And the whole path agrees: rerunning opens a fresh pane at the right
// directory rather than typing into the one that walked away.
let before = app.terminals.len();
app.handle_key(chord).unwrap();
assert_eq!(
app.terminals.len(),
before + 1,
"the task gets a pane standing where it will actually run"
);
}
/// #430: "moved away" and "unknowable" are different, and only the first
/// is a reason to refuse.
///
/// Tested through the pure `cwd_matches` rather than through a live pane,
/// so BOTH arms execute on every platform. The previous version of this
/// test wrapped its headline assertion in `if kernel_shell_cwd().is_none()`
/// — false on macOS and Linux, so the assertion never ran anywhere the
/// suite runs, and reverting the fix would have left it green.
#[test]
fn an_unknowable_cwd_still_allows_reuse_but_a_wrong_one_does_not() {
let root = Path::new("/w/a");
// Read and equal: this command's pane.
assert!(cwd_matches(Some(Path::new("/w/a")), root, true));
// Read and different: the shell wandered off. A DESCENDANT is the
// #430 defect specifically — `starts_with` accepted it.
assert!(!cwd_matches(Some(Path::new("/w/a/sub")), root, true));
assert!(!cwd_matches(Some(Path::new("/w/b")), root, true));
// Unreadable where the platform CAN read one: the failure the guard
// exists for, so it stays closed.
assert!(!cwd_matches(None, root, true));
// Unreadable because the platform can never read one (Android): a
// closed guard would stack a new pane on every single run.
assert!(cwd_matches(None, root, false));
// And a platform that cannot observe still refuses a cwd it somehow
// did read and that differs — the capability is not a blanket pass.
assert!(!cwd_matches(Some(Path::new("/w/a/sub")), root, false));
// The label half of the predicate, on a real pane.
let tmp = tempfile::tempdir().unwrap();
let real_root = tmp.path().canonicalize().unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(!pane_is_idle_at(
&app.terminals[0],
"Task: nonexistent",
&real_root
));
}
// ---------------------------------------------------------------------------
// #313: collapsing terminal panes.
// ---------------------------------------------------------------------------
/// Split to `n` panes and render once at a size wide enough for every pane to
/// carry its full header strip.
fn app_with_terminal_panes(
n: usize,
) -> (
tempfile::TempDir,
App,
ratatui::Terminal<ratatui::backend::TestBackend>,
) {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for _ in 1..n {
app.split_terminal().unwrap();
}
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
(tmp, app, term)
}
#[test]
fn collapsed_panes_keep_one_column_and_the_rest_divide_what_is_left() {
// The apportioning is the whole of the layout risk, so it is measured
// against real solved widths rather than eyeballed off a constraint list.
let solve = |flags: &[bool], width: u16| -> Vec<u16> {
Layout::default()
.direction(Direction::Horizontal)
.constraints(terminal_pane_constraints(flags))
.split(Rect {
x: 0,
y: 0,
width,
height: 10,
})
.iter()
.map(|r| r.width)
.collect()
};
// Nothing collapsed: the even split croft had before the feature existed.
assert_eq!(solve(&[false; 4], 100), vec![25, 25, 25, 25]);
// Two collapsed: one column each, and the two still open divide the 98
// that leaves. This is the assertion `Ratio(1, k)` fails - it would ask
// for 50 columns apiece out of the FULL 100 while the strips also want
// theirs, and the solver settles the overflow by shaving the panes.
let widths = solve(&[false, true, true, false], 100);
assert_eq!(
widths,
vec![49, 1, 1, 49],
"collapsed panes cost one column"
);
assert_eq!(widths.iter().sum::<u16>(), 100, "the row is fully spent");
// The gain is the point: 25 columns each becomes 49.
assert!(
widths[0] > solve(&[false; 4], 100)[0],
"collapsing must actually hand width to the panes still open"
);
}
#[test]
fn the_minus_button_still_closes_and_the_chevron_collapses() {
// The ruling on #313: `-` keeps meaning close, and collapse is its own
// button. These are one test because the whole risk is the two being
// confused - a build where `-` folded instead of closing would pass any
// test that only exercised one of them.
let (_tmp, mut app, _term) = app_with_terminal_panes(3);
let fold = app.terminal_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.terminal_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 clicking_a_collapsed_strip_gives_the_pane_its_width_back() {
let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
app.toggle_terminal_collapse(2);
term.draw(|f| app.render(f)).unwrap();
let strip = app.terminal_strip_rects[2];
assert_eq!(strip.width, 1, "a collapsed pane is one column wide");
assert!(strip.height > 1, "the strip runs the height of the panel");
// Anywhere down the strip, not only the chevron: one column is a small
// enough target without also demanding the right row.
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
strip.x,
strip.y + strip.height / 2,
));
assert!(!app.terminals[2].collapsed, "the strip is the way back out");
}
#[test]
fn a_strip_on_the_sidebar_seam_still_unfolds_its_pane() {
// #468: the default terminal is the LEFTMOST pane, and its strip sits on
// the editor column's left edge, which is exactly the column the sidebar
// seam claims for a resize drag. That hit-test runs before the strip's,
// so a click on the left pane's strip started a drag and the pane could
// never be brought back; a pane opened to the right sat clear of the seam
// and unfolded fine. Both sidebar positions are covered because the seam
// moves with the side bar: on the right it is the column past the editor,
// and its two-column grab zone reaches the LAST pane's strip instead.
for &pos in &[SideBarPosition::Left, SideBarPosition::Right] {
let (_tmp, mut app, mut term) = app_with_terminal_panes(2);
app.side_bar_position = pos;
let idx = match pos {
SideBarPosition::Left => 0,
SideBarPosition::Right => 1,
};
app.toggle_terminal_collapse(idx);
term.draw(|f| app.render(f)).unwrap();
let strip = app.terminal_strip_rects[idx];
assert_eq!(strip.width, 1, "{pos:?}: pane {idx} is folded to a strip");
let seam = app
.sidebar_splitter_x
.expect("the side bar is shown, so its seam exists");
// The whole point: the strip must lie inside the seam's grab zone
// (the seam column and the one left of it), or this proves nothing.
assert!(
strip.x == seam || strip.x + 1 == seam,
"{pos:?}: precondition - strip x={} must meet the seam at x={seam}",
strip.x
);
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
strip.x,
strip.y + strip.height / 2,
));
assert!(
!app.terminals[idx].collapsed,
"{pos:?}: the strip on the seam is still the way back out"
);
assert_eq!(
app.splitter_drag, None,
"{pos:?}: a click on a strip is not a sidebar resize"
);
}
}
#[test]
fn a_collapsed_pane_is_never_reflowed_into_its_strip() {
// `resize` clamps to two columns, so rendering a collapsed pane would not
// crash - it would quietly rewrap the running shell to a two-column grid
// and destroy everything on its screen. Skipping the render is what keeps
// the pane's geometry, and this is the assertion that says so.
let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
let before = app.terminals[1].grid_cols();
assert!(
before > 2,
"the pane must start at a real width to prove this"
);
app.toggle_terminal_collapse(1);
term.draw(|f| app.render(f)).unwrap();
assert_eq!(
app.terminals[1].grid_cols(),
before,
"a collapsed pane's shell keeps the geometry it had"
);
assert_eq!(
app.terminals[1].last_area,
Rect::default(),
"and its grid hit rect is cleared, so a strip click cannot land in it"
);
}
#[test]
fn the_last_expanded_pane_refuses_to_collapse() {
let (_tmp, mut app, _term) = app_with_terminal_panes(2);
app.toggle_terminal_collapse(0);
assert!(app.terminals[0].collapsed);
app.toggle_terminal_collapse(1);
assert!(
!app.terminals[1].collapsed,
"folding every pane away would leave a row of strips with nothing in it"
);
assert!(
app.status.contains("last expanded"),
"and it says so rather than swallowing the click: {:?}",
app.status
);
}
#[test]
fn closing_the_only_expanded_pane_never_leaves_a_row_of_strips() {
// The refusal above guards one route into an all-collapsed row; closing
// is the other, and it arrives from the opposite direction.
let (_tmp, mut app, _term) = app_with_terminal_panes(2);
app.toggle_terminal_collapse(0);
assert!(app.close_terminal_at(1), "close the pane that was expanded");
assert_eq!(app.terminals.len(), 1);
assert!(
!app.terminals[0].collapsed,
"the survivor must be given its width back"
);
}
#[test]
fn reopening_a_closed_pane_brings_it_back_expanded() {
let (_tmp, mut app, _term) = app_with_terminal_panes(3);
app.toggle_terminal_collapse(2);
assert!(app.close_terminal_at(2));
app.undo_close_terminal();
// The count first. Without it a reopen that did nothing at all leaves two
// uncollapsed panes and satisfies the flag check while proving the pane
// never came back: the predicate is fine, the set it ranges over is wrong.
assert_eq!(app.terminals.len(), 3, "the pane must actually be back");
assert!(
!app.terminals.iter().any(|t| t.collapsed),
"a reopen that put a strip on screen would read as having failed"
);
}
#[test]
fn cmd_k_brackets_fold_the_active_pane_and_restore_every_folded_one() {
let (_tmp, mut app, _term) = app_with_terminal_panes(4);
app.active_terminal = 3;
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('['), KeyModifiers::NONE)));
app.active_terminal = 2;
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('['), KeyModifiers::NONE)));
assert_eq!(
app.terminals.iter().filter(|t| t.collapsed).count(),
2,
"each Cmd+K [ folds the pane that is active"
);
assert!(app.handle_cmd_k_chord(key(KeyCode::Char(']'), KeyModifiers::NONE)));
assert!(
!app.terminals.iter().any(|t| t.collapsed),
"Cmd+K ] is the issue's one gesture back to equal-sized panes"
);
assert!(app.status.contains("Restored 2"), "{:?}", app.status);
}
#[test]
fn cmd_k_e_still_reveals_in_the_explorer() {
// The design proposal had picked Cmd+K E for restore-all. It is croft's
// reveal-in-Explorer, and an `e` arm added below the existing one would
// never have been reached - a chord that silently does nothing. This
// pins the collision so the mistake cannot be made a second time.
let (_tmp, mut app, _term) = app_with_terminal_panes(2);
app.toggle_terminal_collapse(1);
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('e'), KeyModifiers::NONE)));
// BOTH halves, in this test. "Did not collapse" alone passes against a
// build where `e` reaches nothing at all, while the test's NAME goes on
// claiming it revealed. With no file open the reveal arm says so, and
// that is the presence half over the same state.
assert_eq!(
app.status, "Reveal in Explorer View: no active file",
"Cmd+K E must still reach reveal-in-Explorer"
);
assert!(
app.terminals[1].collapsed,
"and must not have been quietly taken over by collapse"
);
}
#[test]
fn folding_the_focused_pane_moves_focus_somewhere_visible() {
// A one-column strip shows no cursor, so keystrokes would land where the
// user cannot see them arrive.
let (_tmp, mut app, _term) = app_with_terminal_panes(3);
app.active_terminal = 1;
app.toggle_terminal_collapse(1);
assert!(app.terminals[1].collapsed);
// The SPECIFIC pane, not merely "not the folded one": naming it is what
// tells a deliberate hand-off from focus landing somewhere by accident.
// Pane 1's neighbours are equidistant, so this pins the left tie-break.
assert_eq!(app.active_terminal, 0, "ties go to the pane on the left");
assert!(
!app.terminals[app.active_terminal].collapsed,
"and that pane is actually on screen"
);
}
#[test]
fn folding_a_pane_hands_focus_to_its_neighbour_not_to_the_front_of_the_row() {
// The case above cannot tell "nearest" from "first": pane 1 of three is
// one step from both its neighbours, so the two rules agree there. Four
// panes with the LAST one folded separates them - nearest says 2, first
// says 0 - which is the whole of the difference between handing focus to
// a neighbour and throwing the user back across the panel.
let (_tmp, mut app, _term) = app_with_terminal_panes(4);
app.active_terminal = 3;
app.toggle_terminal_collapse(3);
assert!(app.terminals[3].collapsed);
assert_eq!(
app.active_terminal, 2,
"focus goes to the neighbour, not to the first expanded pane"
);
}
/// A post-draw overlay whose rect does not fit the screen is not emitted
/// (#513). The flush block writes with absolute CUP straight to stdout,
/// so an out-of-range origin cannot panic and ratatui cannot repair it --
/// the payload has to be refused before it is written.
#[test]
fn an_overlay_past_the_screen_edge_is_refused_before_it_is_written() {
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();
// Inside the screen: emittable.
assert!(
app.overlay_fits_on_screen(0, 0, 80, 24),
"a payload filling the screen exactly must be allowed"
);
assert!(app.overlay_fits_on_screen(10, 5, 20, 10), "well inside");
// Past either edge: refused. These are the shapes a stale rect makes --
// the pre-maximize column of a pane that is now narrower, or a row
// index from a taller layout.
assert!(
!app.overlay_fits_on_screen(70, 0, 20, 5),
"past the right edge (70+20 > 80)"
);
assert!(
!app.overlay_fits_on_screen(0, 20, 10, 10),
"past the bottom edge (20+10 > 24)"
);
assert!(
!app.overlay_fits_on_screen(u16::MAX - 1, 0, 4, 4),
"a wild origin must saturate rather than wrap into range"
);
// A zero-sized payload has nothing to place. Refused rather than
// trivially in bounds, so a cleared rect cannot slip a bare cursor
// park through.
assert!(!app.overlay_fits_on_screen(0, 0, 0, 5), "zero width");
assert!(!app.overlay_fits_on_screen(0, 0, 5, 0), "zero height");
}
/// Every raw-CUP writer in the post-draw block is guarded, not just the
/// ones that had a reported failure (#513). The block's six writers share
/// one hazard -- an absolute-CUP write ratatui cannot repair -- so a guard
/// on some of them leaves the same class open at the others. This counts
/// the call sites rather than exercising each, which is crude but is what
/// catches a SEVENTH writer being added later without one.
#[test]
fn every_post_draw_overlay_writer_checks_the_screen_bound() {
let src = include_str!("mod.rs");
let guards = src.matches("app.overlay_fits_on_screen(").count();
assert_eq!(
guards, 5,
"expected the five payload writers in the post-draw block to be \
guarded (editor split slots share one call site, plus terminal, \
markdown, minimap, welcome); the activity-bar writer calls \
`self.overlay_fits_on_screen` from inside its own method. A \
change here means a writer was added or removed - guard it."
);
assert!(
src.contains("if !self.overlay_fits_on_screen(*x, *y, 1, 1)"),
"the activity-bar writer keeps its own guard"
);
}
/// Before any frame is drawn there is no screen to land on, so nothing is
/// emittable (#513). Guards the window between startup and the first
/// render, where `last_frame_area` is still zeroed.
#[test]
fn no_overlay_is_emittable_before_the_first_frame() {
let tmp = tempfile::tempdir().unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(
!app.overlay_fits_on_screen(0, 0, 1, 1),
"no frame drawn yet: a 1x1 payload at the origin still has no screen"
);
}
/// Ctrl+B reaches the app running in a focused terminal instead of
/// toggling the side bar (#304). Claude Code backgrounds a running
/// command with it and has no other route to that gesture; croft's
/// sidebar toggle keeps three.
#[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"
);
// The byte has to ARRIVE, not merely fail to toggle. A guard that
// declined the toggle and then swallowed the key would satisfy the
// assertion above while delivering nothing -- which is the whole
// point of the change, so it is the thing to pin.
assert!(
app.terminals[app.active_terminal]
.written_bytes_for_test()
.contains(&0x02),
"Ctrl+B must reach the PTY as 0x02"
);
// Cmd+B is untouched, which is what keeps the side bar reachable from
// the terminal -- releasing the Ctrl form only costs a chord that has
// three other routes.
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"
);
}
/// The release is conditional on focus, not global (#304): the same
/// chord keeps its croft meaning everywhere else, so the rule is about
/// when the chord is unambiguous rather than a preference.
#[test]
fn ctrl_b_still_toggles_the_side_bar_outside_the_terminal() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
let before = app.show_tree;
app.handle_key(key(KeyCode::Char('b'), KeyModifiers::CONTROL))
.unwrap();
assert_ne!(
app.show_tree, before,
"with the editor focused, Ctrl+B is still croft's"
);
}
#[test]
fn maximize_ignores_the_collapse_flags_and_gives_them_back_on_exit() {
// The two gestures are orthogonal: entering maximize does not clear the
// flags, and leaving it restores whatever folding was in force.
let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
app.toggle_terminal_collapse(2);
app.active_terminal = 0;
app.toggle_terminal_pane_maximize();
term.draw(|f| app.render(f)).unwrap();
assert!(
app.terminals[2].collapsed,
"maximize must not silently clear the folding"
);
assert_eq!(
app.terminal_strip_rects
.iter()
.filter(|r| r.width > 0)
.count(),
0,
"but no strip is painted while maximize owns the panel"
);
app.toggle_terminal_pane_maximize();
term.draw(|f| app.render(f)).unwrap();
assert_eq!(
app.terminal_strip_rects[2].width, 1,
"leaving maximize brings the strip back"
);
}
/// Closing the last EXPANDED pane leaves a panel of nothing but strips,
/// and something must bring one back (part of #468).
///
/// `toggle_terminal_collapse` refuses to fold the last expanded pane,
/// but closing reaches that state from the other side, which is a route
/// the fold guard cannot see. `ensure_a_terminal_pane_is_expanded` is
/// the answer and has exactly one caller; this pins that the caller is
/// on the path that needs it.
#[test]
fn closing_the_last_expanded_pane_leaves_one_expanded_behind() {
let (_tmp, mut app, mut term) = app_with_terminal_panes(2);
term.draw(|f| app.render(f)).unwrap();
app.toggle_terminal_collapse(1);
assert!(app.terminals[1].collapsed, "premise: pane 1 is folded");
assert!(
!app.terminals[0].collapsed,
"premise: pane 0 is the only expanded one"
);
// Close the expanded one. The fold guard never fires -- nothing is
// being folded -- so the panel would be all strips without the
// close path's own guard.
app.close_terminal_at(0);
term.draw(|f| app.render(f)).unwrap();
assert_eq!(app.terminals.len(), 1, "one pane left");
assert!(
!app.terminals[0].collapsed,
"the surviving pane must be expanded: a panel of nothing but strips \
has no cursor and no way back that does not depend on the strip \
click still working"
);
}
/// The config row and the picker must agree about hidden compounds (#318).
///
/// The row is the documented route INTO the picker, so a count that
/// includes what the picker drops advertises an entry that is not there:
/// a workspace whose only compound is hidden would render "1 debug entry"
/// over a picker offering nothing to debug.
#[test]
fn the_config_row_does_not_count_a_hidden_compound() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::write(
tmp.path().join(".croft/launch.json"),
r#"{
"configurations": [
{ "name": "A", "type": "lldb", "request": "launch", "program": "/bin/ls" }
],
"compounds": [
{ "name": "OnlyHidden", "configurations": ["A"],
"presentation": { "hidden": true } }
]
}"#,
)
.unwrap();
// `A` is declared, so the compound RESOLVES and the only thing keeping it
// out of the count is `hidden`. With an empty `configurations` the count
// could equally come from an unresolvable member, and the assertion would
// hold for a reason it does not claim.
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.refresh_run_debug();
// Pin the fixture's discriminating property rather than leaving it in a
// comment: the counts below only mean "the compound was excluded" while
// exactly one configuration is declared. A later edit adding a second
// config would make 1 and 2 wrong for a reason that has nothing to do
// with hiding, and the obvious repair -- bumping the numbers -- would
// leave a test that no longer measures what it claims.
assert_eq!(
crate::dap::configs::discover_configs(tmp.path()).len(),
1,
"fixture: exactly one configuration, so the counts isolate the compound"
);
assert_eq!(
app.run_debug.config_count, 1,
"the visible configuration counts; the hidden compound does not"
);
// And the picker agrees: nothing but the always-present rows (the active
// file, and Add Configuration).
app.open_debug_config_picker();
let picker = app.list_picker.as_ref().expect("the picker opened");
assert!(
!picker.rows.iter().any(|r| r.id.starts_with("compound:")),
"no compound rows: {:?}",
picker.rows.iter().map(|r| &r.id).collect::<Vec<_>>()
);
app.list_picker = None;
// The POSITIVE leg. Everything above asserts an absence, and an absence
// is what a broken parser, an unreadable launch.json and a working
// filter all produce. Unhiding the same compound in the same workspace
// must make it appear -- without this the test passes with the filter
// deleted and the file never parsed.
std::fs::write(
tmp.path().join(".croft/launch.json"),
r#"{
"configurations": [
{ "name": "A", "type": "lldb", "request": "launch", "program": "/bin/ls" }
],
"compounds": [
{ "name": "OnlyHidden", "configurations": ["A"],
"presentation": { "hidden": false } }
]
}"#,
)
.unwrap();
let mut shown = App::new(tmp.path().to_path_buf()).unwrap();
shown.refresh_run_debug();
assert_eq!(
shown.run_debug.config_count, 2,
"the same compound, unhidden, IS an entry the row offers alongside A"
);
shown.open_debug_config_picker();
let picker = shown.list_picker.as_ref().expect("the picker opened");
assert!(
picker.rows.iter().any(|r| r.id.starts_with("compound:")),
"and the picker lists it: {:?}",
picker.rows.iter().map(|r| &r.id).collect::<Vec<_>>()
);
}
/// #318: a CONFIGURATION can ask to be hidden too, and the picker and its
/// badge must agree about that the way they already do for a compound.
/// Deleting the configuration half of the filter left the whole suite green.
#[test]
fn a_hidden_configuration_leaves_both_the_picker_and_the_count() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::write(
tmp.path().join(".croft/launch.json"),
r#"{
"configurations": [
{ "name": "Shown", "type": "lldb", "request": "launch", "program": "/bin/ls" },
{ "name": "Hid", "type": "lldb", "request": "launch", "program": "/bin/ls",
"presentation": { "hidden": true } }
]
}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.refresh_run_debug();
assert_eq!(
crate::dap::configs::discover_configs(tmp.path()).len(),
2,
"fixture: both configurations parse, so the count below isolates hiding"
);
assert_eq!(
app.run_debug.config_count, 1,
"the hidden configuration is not an entry the row offers"
);
app.open_debug_config_picker();
let labels: Vec<String> = app
.list_picker
.as_ref()
.expect("the picker opened")
.rows
.iter()
.map(|r| r.label.clone())
.collect();
assert!(
labels.iter().any(|l| l.starts_with("Shown")),
"the visible one is listed: {labels:?}"
);
assert!(
!labels.iter().any(|l| l.starts_with("Hid")),
"and the hidden one is not: {labels:?}"
);
}
/// #318: the row ids are built from the UNSORTED lists, so a row keeps naming
/// the entry it says even after `presentation` reorders the picker. Indexing
/// the sorted sequence instead would launch a different configuration than
/// the row names, which is the trap the module doc calls out and which no
/// test covered while only the hidden filter was exercised.
#[test]
fn a_reordering_presentation_leaves_every_row_naming_its_own_entry() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
// "Last" is declared third and asks to be first, so a sorted-index bug
// cannot hide behind the entries happening to already be in order.
std::fs::write(
tmp.path().join(".croft/launch.json"),
r#"{
"configurations": [
{ "name": "First", "type": "lldb", "request": "launch", "program": "/bin/ls" },
{ "name": "Second", "type": "lldb", "request": "launch", "program": "/bin/ls" },
{ "name": "Last", "type": "lldb", "request": "launch", "program": "/bin/ls",
"presentation": { "order": 1 } }
]
}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_debug_config_picker();
let rows: Vec<(String, String)> = app
.list_picker
.as_ref()
.expect("the picker opened")
.rows
.iter()
.map(|r| (r.id.clone(), r.label.clone()))
.collect();
let configs = crate::dap::configs::discover_configs(tmp.path());
let ordered: Vec<&str> = rows
.iter()
.filter(|(id, _)| id != "active" && id != "add")
.map(|(_, label)| label.split(' ').next().unwrap_or_default())
.collect();
assert_eq!(
ordered,
vec!["Last", "First", "Second"],
"precondition: the presentation actually moved a row"
);
// The claim: every id still indexes the entry whose name the row shows.
for (id, label) in rows.iter().filter(|(id, _)| id != "active" && id != "add") {
let idx: usize = id.parse().expect("a configuration row's id is its index");
assert!(
label.starts_with(&configs[idx].name),
"row {id:?} says {label:?} but index {idx} is {:?}",
configs[idx].name
);
}
}
/// A compound asking `presentation.hidden` is not listed, and hiding one
/// does not misdirect the rows that remain (#318).
///
/// The second half is the subtle one: row ids are `compound:{i}` where `i`
/// indexes `debug_compounds`. Filtering AFTER `enumerate` keeps those ids
/// naming the same compound; filtering before would make every row after a
/// hidden one launch its neighbour.
#[test]
fn a_hidden_compound_is_not_listed_and_the_rest_keep_their_ids() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::write(
tmp.path().join(".croft/launch.json"),
r#"{
"configurations": [
{ "name": "A", "type": "lldb", "request": "launch", "program": "/bin/ls" }
],
"compounds": [
{ "name": "First", "configurations": ["A"] },
{ "name": "Hidden", "configurations": ["A"], "presentation": { "hidden": true } },
{ "name": "Third", "configurations": ["A"] }
]
}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_debug_config_picker();
let picker = app.list_picker.as_ref().expect("the picker opened");
let rows: Vec<(String, String)> = picker
.rows
.iter()
.filter(|r| r.id.starts_with("compound:"))
.map(|r| (r.id.clone(), r.label.clone()))
.collect();
assert_eq!(rows.len(), 2, "the hidden compound is not listed: {rows:?}");
assert!(
!rows.iter().any(|(_, l)| l.contains("Hidden")),
"and it is the hidden one that went: {rows:?}"
);
// Third was at index 2 before the filter and must still say so, or
// selecting it would launch the compound the id points at instead.
assert_eq!(rows[0].0, "compound:0", "First keeps its index");
assert!(rows[0].1.contains("First"));
assert_eq!(
rows[1].0, "compound:2",
"Third keeps index 2 across the hidden row, not 1"
);
assert!(rows[1].1.contains("Third"));
}
/// EXHAUSTIVE recovery sweep for #468: every pane index, both side bar
/// positions, and with a resize or a maximize cycle interleaved, must be
/// recoverable from its strip.
///
/// Four theories about this bug died against the tree by inspection --
/// the editor/panel splitter's grab zone, the maximize/collapse flag
/// interaction, index 0 being special, and the last-expanded guard. This
/// stops arguing and drives the combinations instead, because "I could
/// not construct the path" is a much weaker claim than "the paths were
/// enumerated and all of them recover".
///
/// If this ever goes red it names the reproduction directly.
#[test]
fn every_collapsed_pane_recovers_from_its_strip_in_every_layout() {
for panes in [2usize, 3] {
for right_bar in [false, true] {
for perturb in ["none", "resize", "maximize"] {
for idx in 0..panes {
let (_tmp, mut app, mut term) = app_with_terminal_panes(panes);
app.side_bar_position = if right_bar {
crate::app::SideBarPosition::Right
} else {
crate::app::SideBarPosition::Left
};
term.draw(|f| app.render(f)).unwrap();
app.toggle_terminal_collapse(idx);
assert!(
app.terminals[idx].collapsed,
"premise: pane {idx} folds ({panes} panes, right_bar={right_bar})"
);
// The perturbations #475 and #478 make plausible: a
// resize leaves stale geometry behind, and maximize
// bypasses the pane-constraint path entirely.
match perturb {
"resize" => {
term =
ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 24))
.unwrap();
}
"maximize" => {
app.toggle_terminal_pane_maximize();
term.draw(|f| app.render(f)).unwrap();
app.toggle_terminal_pane_maximize();
}
_ => {}
}
term.draw(|f| app.render(f)).unwrap();
// The perturbation must PRESERVE the fold. A `continue`
// here would let a maximize cycle that clears `collapsed`
// pass the case without ever clicking a strip, so the
// sweep would report paths it never walked -- the exact
// shape of green this test exists to refuse.
assert!(
app.terminals[idx].collapsed,
"pane {idx} must still be folded after {perturb} \
({panes} panes, right_bar={right_bar}); if this \
perturbation legitimately unfolds panes the case \
needs its own assertion, not a skip"
);
let strip = app.terminal_strip_rects[idx];
assert_eq!(
strip.width, 1,
"pane {idx} keeps a one-column strip after {perturb} \
({panes} panes, right_bar={right_bar})"
);
app.handle_mouse(mouse(
crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
strip.x,
strip.y,
));
assert!(
!app.terminals[idx].collapsed,
"pane {idx} must unfold from its strip at ({}, {}) after \
{perturb} ({panes} panes, right_bar={right_bar})",
strip.x, strip.y
);
}
}
}
}
}
#[test]
fn a_collapsed_strip_carries_the_pane_name_down_its_column() {
// The strip is what makes the gesture obviously reversible, so it has to
// be identifiable: the chevron out, then the name.
let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
app.terminals[1].set_manual_name(Some(String::from("build")));
app.toggle_terminal_collapse(1);
term.draw(|f| app.render(f)).unwrap();
let strip = app.terminal_strip_rects[1];
let column: String = (strip.y..strip.y + strip.height)
.map(|y| {
term.backend()
.buffer()
.cell(ratatui::layout::Position::new(strip.x, y))
.unwrap()
.symbol()
.to_string()
})
.collect();
assert!(
column.starts_with('\u{eab6}'),
"the expand chevron heads the strip: {column:?}"
);
assert!(
column.contains("build"),
"the pane's name runs down the strip: {column:?}"
);
}
/// #468 reports the LEFTMOST pane specifically: "works fine for
/// right-side-opened terminals but the default terminal that is on the left
/// side, which fold also on the left side, cannot be recovered after
/// collapse."
///
/// Every other strip test in this file uses index 1 or 2, so index 0 has
/// never been exercised - the shape in which a bug survives a green suite.
/// Two theories (the splitter grab zone, the sidebar seam) already died
/// against the tree, so this asserts the user's gesture end to end rather
/// than any mechanism: fold pane 0, click its strip, and require it back.
#[test]
fn the_leftmost_pane_comes_back_from_its_strip() {
let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
app.toggle_terminal_collapse(0);
term.draw(|f| app.render(f)).unwrap();
let strip = app.terminal_strip_rects[0];
assert_eq!(strip.width, 1, "precondition: pane 0's strip is painted");
assert!(app.terminals[0].collapsed, "precondition: pane 0 is folded");
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
strip.x,
strip.y + 1,
));
assert!(
!app.terminals[0].collapsed,
"a left-click on the leftmost strip unfolds it, the same as any other"
);
}
/// The right-click half of the same gesture, for the same untested index.
#[test]
fn the_leftmost_panes_strip_offers_expand_terminal() {
let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
app.toggle_terminal_collapse(0);
term.draw(|f| app.render(f)).unwrap();
let strip = app.terminal_strip_rects[0];
assert_eq!(strip.width, 1, "precondition: pane 0's 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 leftmost folded pane offers the way back out too: {labels:?}"
);
}
#[test]
fn a_long_pane_name_never_paints_past_the_end_of_its_strip() {
// A PROPERTY, not a case: this never states which row the name should end
// on, only that nothing lands outside the strip. A case written to a
// boundary already reasoned through would confirm the painting code's
// arithmetic rather than probe it, since the same reasoning produced both.
let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
app.toggle_terminal_collapse(1);
term.draw(|f| app.render(f)).unwrap();
let height = app.terminal_strip_rects[1].height;
assert!(
height > 2,
"the strip must be tall enough for a name to overrun"
);
// Omega is one cell wide and appears nowhere else in the chrome, so any
// sighting of it outside the strip is the name having escaped.
const MARK: &str = "\u{3a9}";
for len in 1..=(height as usize + 2) {
app.terminals[1].set_manual_name(Some(MARK.repeat(len)));
term.draw(|f| app.render(f)).unwrap();
let strip = app.terminal_strip_rects[1];
assert_eq!(strip.width, 1, "still one column at name length {len}");
// Containment, counted over the WHOLE screen rather than probed at
// the row below the strip: that probe reads `None` whenever the panel
// reaches the last screen row, and an assertion the buffer's edge can
// satisfy is not an assertion. Comparing totals cannot go vacuous, and
// it states no arithmetic about which row is last.
let buf = term.backend().buffer();
let mark_at = |x: u16, y: u16| {
buf.cell(ratatui::layout::Position::new(x, y))
.is_some_and(|c| c.symbol() == MARK)
};
let area = buf.area();
let on_screen = (0..area.height)
.flat_map(|y| (0..area.width).map(move |x| (x, y)))
.filter(|&(x, y)| mark_at(x, y))
.count();
let in_strip = (strip.y..strip.y + strip.height)
.filter(|&y| mark_at(strip.x, y))
.count();
assert!(
in_strip > 0,
"the name must actually be painted at length {len}, or nothing is being tested"
);
assert_eq!(
on_screen, in_strip,
"a {len}-character name painted outside its own strip"
);
}
}
// --- #313 fallback-review findings: red-first ------------------------------
#[test]
fn cycling_terminals_never_lands_on_a_collapsed_pane() {
// Cmd+] / Cmd+[ walk `active_terminal` by raw modular arithmetic, which
// predates the collapse flag. `toggle_terminal_collapse` documents the
// invariant "focus must not sit on a pane the user cannot see" and
// defends it on its own path only; cycling is the other way in.
//
// The FIXTURE has to be able to tell the two apart: four panes with index
// 1 folded, cycling from 0. Broken lands on 1 (folded, no cursor painted);
// correct skips to 2. A three-pane fixture would not discriminate.
let (_tmp, mut app, _term) = app_with_terminal_panes(4);
app.toggle_terminal_collapse(1);
app.active_terminal = 0;
app.cycle_terminal();
assert_eq!(
app.active_terminal, 2,
"forward cycling steps over the strip"
);
assert!(!app.terminals[app.active_terminal].collapsed);
app.cycle_terminal_back();
assert_eq!(app.active_terminal, 0, "and so does backward cycling");
assert!(!app.terminals[app.active_terminal].collapsed);
// Presence half: with nothing folded the cycle still moves one slot, so
// this cannot pass by the cycle being broken outright.
app.restore_all_terminal_panes();
app.active_terminal = 0;
app.cycle_terminal();
assert_eq!(app.active_terminal, 1, "an unfolded row still steps by one");
}
#[test]
fn collapse_is_inert_while_a_pane_is_maximized() {
// The `‹` button is not painted while maximized and the menu entry is
// suppressed, but the chord and the palette command called through
// unconditionally. `toggle_terminal_collapse` reassigns `active_terminal`,
// and the maximize branch hands the panel to whatever that is - so the
// pane being watched was silently swapped for a neighbour.
let (_tmp, mut app, _term) = app_with_terminal_panes(3);
app.active_terminal = 1;
app.toggle_terminal_pane_maximize();
assert!(app.terminal_pane_maximized, "precondition");
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('['), KeyModifiers::NONE)));
assert_eq!(
app.active_terminal, 1,
"the maximized pane must not be swapped out from under the user"
);
assert!(
!app.terminals.iter().any(|t| t.collapsed),
"and nothing folds while maximize owns the panel"
);
}
#[test]
fn right_clicking_a_collapsed_strip_offers_to_expand_it() {
// `terminal_at_pos` hit-tests `last_area`, which a collapsed pane clears,
// so the right-click never resolved to a folded pane: the menu's
// "Expand Terminal" branch was unreachable while KEYBINDINGS.md advertised
// it, and a strip had exactly one gesture.
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.terminal_strip_rects[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 a_reorder_never_hands_a_collapsed_pane_a_live_hit_rect() {
// `move_terminal` re-seats `last_area` in SLOT order, because the rect is a
// slot's geometry living on the terminal object. Before collapse existed
// every visible slot had a real rect, so that was self-consistent. Now a
// folded pane dragged into an expanded slot inherits a full-size rect it is
// not painted in, and clicks over it resolve to a pane that is not there.
let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
app.toggle_terminal_collapse(1);
term.draw(|f| app.render(f)).unwrap();
app.move_terminal(0, 2);
let folded = app
.terminals
.iter()
.position(|t| t.collapsed)
.expect("the folded pane survived the reorder");
assert_eq!(
app.terminals[folded].last_area,
Rect::default(),
"a folded pane must not inherit an expanded slot's hit rect"
);
// Presence half: the panes that ARE painted keep real rects, so this
// cannot pass by the re-seat having been removed altogether.
assert!(
app.terminals
.iter()
.filter(|t| !t.collapsed)
.any(|t| t.last_area.width > 0),
"expanded panes still carry their slot geometry"
);
}
#[test]
fn closing_the_pane_beside_a_folded_one_never_leaves_focus_on_it() {
// Round 1 fixed ONE route onto a folded pane (cycling) at the call site
// rather than at `sync_focus_flags`, which documents itself as the single
// place every gesture moving `active_terminal` funnels through.
//
// Here: fold the ACTIVE pane 1, which hands focus left to 0, then close 0.
// `close_terminal_at` leaves `active_terminal` at 0, which is now the
// folded pane. `ensure_a_terminal_pane_is_expanded` does not catch it - it
// enforces "SOME pane is expanded", not "the ACTIVE pane is".
let (_tmp, mut app, _term) = app_with_terminal_panes(3);
app.active_terminal = 1;
app.toggle_terminal_collapse(1);
assert_eq!(app.active_terminal, 0, "precondition: focus went left");
assert!(app.close_terminal_at(0), "close the pane holding focus");
assert!(
!app.terminals[app.active_terminal].collapsed,
"closing a neighbour must not leave focus on a strip"
);
}
#[test]
fn dismissing_a_strips_menu_never_leaves_focus_on_the_strip() {
// This route was OPENED by round 1's own fix: making a strip
// right-clickable also made it focusable, because the same line that
// resolves the pane also focuses it. A folded pane paints no cursor and no
// focus border, so the user then types into a pane they cannot see.
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.terminal_strip_rects[1];
assert_eq!(strip.width, 1, "precondition: the strip is painted");
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Right),
strip.x,
strip.y + 1,
));
assert!(
app.context_menu.is_some(),
"precondition: the strip right-click opened the pane menu"
);
// Dismiss through the PRODUCTION path. Assigning `context_menu = None`
// under a comment saying "the user presses Esc" made this test assert
// focus after the RIGHT-CLICK, not after dismissal: the right-click branch
// calls `focus_pane`, which runs the invariant, so the assertion below was
// already satisfied before the line pretending to dismiss anything ran. It
// passed, and it could not have failed for the reason it is named for.
app.handle_menu_key(key(KeyCode::Esc, KeyModifiers::NONE));
assert!(
app.context_menu.is_none(),
"Esc must actually close the menu, or the dismissal path is not what \
this test exercised"
);
assert!(
!app.terminals[app.active_terminal].collapsed,
"dismissing a strip's menu must not leave focus on the strip"
);
}
#[test]
fn leaving_maximize_never_lands_focus_on_a_folded_pane() {
// The rail lists every pane, folded ones included, and a rail click sets
// `active_terminal` with no collapse check. While maximized that is
// harmless - the flags are ignored and the pane is painted full width -
// but leaving maximize drops focus onto a one-column strip.
let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
app.toggle_terminal_collapse(2);
app.active_terminal = 0;
app.toggle_terminal_pane_maximize();
term.draw(|f| app.render(f)).unwrap();
// Hand the maximized pane to the folded terminal the way the rail does.
app.active_terminal = 2;
app.toggle_terminal_pane_maximize();
assert!(
!app.terminal_pane_maximized,
"precondition: back to the split"
);
assert!(
!app.terminals[app.active_terminal].collapsed,
"leaving maximize must not leave focus on a strip"
);
}
#[test]
fn restore_all_is_inert_while_a_pane_is_maximized() {
// The mirror of `collapse_is_inert_while_a_pane_is_maximized`. Collapse
// got the maximize guard in round 1 and restore did not, so Cmd+K ]
// cleared every flag and announced it, for a change invisible until the
// user left maximize - the same silent-state-change shape, reversed.
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() {
// Round 2 moved the "focus never rests on a folded pane" invariant into
// `sync_focus_flags`. That closed three routes and broke a fourth class:
// callers which deliberately TARGET a pane by index and then focus it.
// `sync_focus_flags` sees the target folded and walks focus away, so the
// caller's chosen pane is silently swapped for a neighbour - here the
// capture is applied to a pane the user cannot see while focus lands
// somewhere unrelated. `run_project_task` and `run_block_in_pane` have the
// same shape and write a COMMAND into the invisible pane.
//
// The invariant is right; what was missing is that reaching for a pane by
// index is a request to SEE it, which is the rationale `undo_close_terminal`
// already applies when it force-expands a reopened pane.
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"),
});
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 the_expand_entry_advertises_no_chord_it_cannot_perform() {
// `Cmd+K [` acts on `active_terminal`, which the focus invariant keeps off
// folded panes, so the chord can only ever COLLAPSE. The menu label
// alternates, so a folded pane's menu read `Expand Terminal ⌘K [` -
// advertising a shortcut that does the opposite of the label beside it.
// Contrast `ToggleMaximizeTerminal`, which carries `⌘K M` honestly because
// that chord genuinely toggles both ways.
assert_eq!(
shortcut_for(&MenuAction::ToggleCollapseTerminal(0)),
None,
"a one-way chord must not be advertised beside a two-way label"
);
assert_eq!(
shortcut_for(&MenuAction::ToggleMaximizeTerminal(0)),
Some("⌘K M"),
"and the genuinely two-way sibling keeps its hint, so this is not just \
the hint lookup being broken"
);
}
#[test]
fn a_folded_strips_menu_offers_nothing_that_acts_on_the_active_pane() {
// A strip right-click sets `active_terminal = idx` and focuses the pane,
// and `sync_focus_flags` then walks focus straight off a folded pane to
// its nearest expanded neighbour. Every menu entry that carries no index
// acts on `active_terminal`, so the menu named one pane and acted on
// another: "Open Scrollback in Editor" opened the NEIGHBOUR's scrollback
// under the neighbour's label. The broadcast entry was worse — it read
// its label from `terminals[idx]` and toggled `active_terminal`, so it
// could say "Exclude from Broadcast" and include a different pane.
let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
app.broadcast_input = true;
app.toggle_terminal_collapse(1);
term.draw(|f| app.render(f)).unwrap();
let strip = app.terminal_strip_rects[1];
assert_eq!(strip.width, 1, "precondition: the strip is painted");
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Right),
strip.x,
strip.y + 1,
));
assert_ne!(
app.active_terminal, 1,
"precondition: focus cannot rest on a folded pane, which is what \
makes an index-free entry act on the wrong one"
);
let labels = |app: &App| -> Vec<String> {
app.context_menu
.as_ref()
.expect("a right-click opens the pane menu")
.items
.iter()
.filter_map(|e| match e {
MenuEntry::Item { label, .. } => Some(label.clone()),
_ => None,
})
.collect()
};
let folded = labels(&app);
for entry in [
"Copy",
"Paste",
"Quick Select",
"Copy Mode",
"Command History",
"Open Scrollback in Editor",
"Exclude from Broadcast",
"Include in Broadcast",
] {
assert!(
!folded.iter().any(|l| l == entry),
"{entry:?} acts on the active pane, which is not this one: {folded:?}"
);
}
assert!(
folded.iter().any(|l| l == "Rename Terminal")
&& folded.iter().any(|l| l == "Expand Terminal"),
"the entries that carry their own index stay: {folded:?}"
);
// The control, in the same run: an EXPANDED pane still offers all of
// them, so this is a rule about folded panes and not a menu that lost
// half its entries.
app.context_menu = None;
let area = app.terminals[0].last_area;
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Right),
area.x + 1,
area.y + 1,
));
let expanded = labels(&app);
for entry in [
"Paste",
"Quick Select",
"Copy Mode",
"Command History",
"Open Scrollback in Editor",
] {
assert!(
expanded.iter().any(|l| l == entry),
"{entry:?} belongs on an expanded pane's menu: {expanded:?}"
);
}
}
/// #540: the terminal pane menu carried every terminal gesture except the
/// two a right-click is most often reached for. Copy is offered only while
/// the pane has a selection - the menu model has no disabled state, so an
/// entry that would copy nothing is worse than no entry - and both entries
/// go through the same routes the Cmd+C / Cmd+V chords already use.
#[test]
fn the_pane_menu_copies_a_selection_and_pastes_the_clipboard() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// A silent child: the grid then holds exactly what the test feeds it,
// with no shell prompt racing the selection coordinates.
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from("sleep 60")],
tmp.path(),
)
.unwrap();
app.show_terminal = true;
app.focus_pane(Pane::Terminal);
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let area = app.terminals[0].last_area;
let inner = app.terminals[0].last_inner;
let labels = |app: &App| -> Vec<String> {
menu_labels(
&app.context_menu
.as_ref()
.expect("a right-click opens the pane menu")
.items,
)
.iter()
.map(|l| l.to_string())
.collect()
};
// Nothing selected: Paste is offered, Copy is not.
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Right),
area.x + 1,
area.y + 1,
));
let empty = labels(&app);
assert!(
empty.iter().any(|l| l == "Paste"),
"Paste needs no selection: {empty:?}"
);
assert!(
!empty.iter().any(|l| l == "Copy"),
"Copy must not be offered while there is nothing to copy: {empty:?}"
);
app.context_menu = None;
// With a selection, Copy joins the menu and reaches the clipboard. The
// row is located in the grid rather than assumed: the pane paints a
// launch banner of its own above whatever the child prints.
app.terminals[0].feed_bytes_for_test(b"copy-me-540\r\n");
let (lines, top) = app.terminals[0].grid_lines();
let vrow = (top
+ lines
.iter()
.position(|l| l.starts_with("copy-me-540"))
.expect("the fed text must reach the grid") as i32) as u16;
app.terminals[0].start_selection_at(inner.x, inner.y + vrow);
app.terminals[0].extend_selection_to(inner.x + 20, inner.y + vrow);
let expected = app.terminals[0].selection_text();
assert!(
expected.contains("copy-me-540"),
"precondition: the selection covers the fed text, got {expected:?}"
);
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Right),
area.x + 1,
area.y + 1,
));
let selected = labels(&app);
assert!(
selected.iter().any(|l| l == "Copy"),
"Copy belongs on a pane that has a selection: {selected:?}"
);
app.context_menu = None;
app.dispatch_menu_action(MenuAction::TerminalCopySelection, tmp.path().to_path_buf());
assert_eq!(
crate::clipboard::read_string().as_deref(),
Some(expected.as_str()),
"the menu's Copy must put the selection on the clipboard"
);
// And Paste sends the clipboard on to the pane's child.
let before = app.terminals[0].written_bytes_for_test().len();
assert!(crate::clipboard::write_string("pasted-540"));
app.dispatch_menu_action(MenuAction::TerminalPaste, tmp.path().to_path_buf());
let written = app.terminals[0].written_bytes_for_test();
let sent = String::from_utf8_lossy(&written[before..]).to_string();
assert!(
sent.contains("pasted-540"),
"the menu's Paste must reach the shell, sent {sent:?}"
);
}
#[test]
fn a_pane_named_in_wide_characters_still_marks_its_strip() {
// Only single-width characters are painted, because a CJK glyph or an
// emoji is two cells wide and the pane next door is one column away. But
// FILTERING them out left a pane named entirely in them with a blank
// strip: a folded pane that is not identifiable is the one thing the
// strip exists to prevent.
let (_tmp, mut app, mut term) = app_with_terminal_panes(3);
app.terminals[1].set_manual_name(Some(String::from("\u{9805}\u{76ee}")));
app.toggle_terminal_collapse(1);
term.draw(|f| app.render(f)).unwrap();
let strip = app.terminal_strip_rects[1];
assert_eq!(strip.width, 1, "precondition: the strip is painted");
assert!(strip.height > 2, "precondition: room below the chevron");
let buf = term.backend().buffer();
let at = |x: u16, y: u16| {
buf.cell(ratatui::layout::Position::new(x, y))
.map(|c| c.symbol().to_string())
.unwrap_or_default()
};
let marked = (strip.y + 1..strip.y + strip.height)
.filter(|&y| !at(strip.x, y).trim().is_empty())
.count();
assert!(
marked > 0,
"the strip must carry something under the chevron for a wide-character name"
);
// And the containment property the filter was there for: the stand-in is
// one cell, so the pane one column away is untouched.
assert_eq!(
unicode_width::UnicodeWidthChar::width(TERMINAL_STRIP_WIDE_STANDIN),
Some(1),
"the stand-in has to fit the one column the strip owns"
);
}
#[test]
fn maximizing_from_a_folded_strip_shows_the_pane_the_menu_named() {
// `ToggleMaximizeTerminal` carries its index and assigns `active_terminal`
// directly rather than through `focus_pane`, which makes it the one path
// that deliberately puts focus ON a folded pane. That is correct here:
// maximize ignores the collapse flags by design and paints the active
// pane across the panel, so the pane the menu names is the pane that
// appears. The strip's right-click made this reachable, and nothing
// pinned 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.terminal_strip_rects[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.terminal_strip_rects.iter().all(|r| r.width == 0),
"no strip survives maximize, or a click could land on a pane that is not painted"
);
}
/// #474: a rendered app whose only pane is tracking the mouse with SGR
/// reports, exactly the pair Claude Code sends (`?1000h` + `?1006h`), plus
/// a cell inside the grid and that cell's local coordinates.
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();
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(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() {
// Claude Code's diff panel closes from a click on its ×; htop, lazygit
// and vim's `mouse=a` route clicks the same way. All of them see the
// click only if croft sends the press AND the release: a TUI that got a
// press with no release believes the button is still down. Before #474
// neither was sent -- the click became a one-cell croft selection.
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!(
app.terminal_pointer_forwarded
.is_some_and(|f| f.pane == uid && f.press == (col, row) && !f.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!(
app.terminal_pointer_forwarded.is_none(),
"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() {
// The forward is gated on the child having asked (`report_mouse` declines
// without a tracking mode), so a shell prompt or a plain pager keeps
// croft's click-to-select and nothing reaches the child's stdin.
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!(app.terminal_pointer_forwarded.is_none());
}
#[test]
fn shift_click_over_a_tracking_child_keeps_the_click_for_croft() {
// Shift is the bypass for the whole forwarded family, the same one the
// wheel has and the one xterm, iTerm2 and VS Code use: with it held the
// click anchors croft's selection so text can still be copied out of a
// full-screen app that otherwise owns the pointer.
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!(app.terminal_pointer_forwarded.is_none());
}
#[test]
fn a_click_on_the_pane_border_is_not_forwarded_to_a_tracking_child() {
// `terminal_at_pos` hit-tests the pane INCLUDING its border, while a
// report needs a grid cell. A border click over a tracking child must
// fall through to croft (where it is inert) rather than be reported at a
// cell the child does not have.
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!(app.terminal_pointer_forwarded.is_none());
}
#[test]
fn a_forwarded_drag_reports_motion_only_when_the_child_asked_for_it() {
// DECSET 1000 is click-only: the child wants presses and releases and
// nothing in between. 1002 adds button-held motion. The Drag arm hands
// the event to `report_mouse`, whose motion guard already encodes that
// distinction, so the same drag is silent under 1000 and a `+32` report
// under 1002 -- and croft's own drag-selection never starts either way.
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"
);
// A click-only child cannot use the drag, so croft keeps it: the
// selection is anchored at the PRESS cell, not where the first motion
// event happened to land, and extends to the pointer.
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!(
app.terminal_pointer_forwarded.is_some_and(|f| f.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.terminal_pointer_forwarded.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() {
// A press the child got must be followed by a release the child gets,
// even when the pointer has wandered off the pane by then; otherwise the
// child keeps a button held that the user let go. xterm reports such a
// release at the nearest cell, and so does croft: the coordinates are
// clamped to the pane's grid rather than the report being dropped.
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.terminal_pointer_forwarded.is_none());
}
#[test]
fn a_forwarded_release_over_a_sibling_pane_goes_to_the_pane_that_got_the_press() {
// The point of remembering the pane in `terminal_pointer_forwarded`
// rather than re-hit-testing at release: a drag that ends over the
// NEIGHBOUR pane still owes its release to the child that got the press,
// at that child's nearest edge cell. Re-resolving by pointer would hand
// the release to a pane that never saw a press (or drop it, if that pane
// is not tracking) and leave the first child with a held button.
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");
// Only pane 0 tracks the mouse; pane 1 is a plain shell.
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();
// A cell well inside pane 1, on the same row.
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.terminal_pointer_forwarded.is_none());
}
#[test]
fn a_forwarded_release_finds_its_pane_after_an_earlier_pane_closes() {
// `ForwardedPointer` names the pane by uid, not by index. Close the pane
// BEFORE the pressed one while the button is held: the pressed pane
// slides from index 1 to index 0, and the release must still reach it.
// An index would have delivered the release to whatever now sits at
// the old slot (nothing, here) and left the pressed child holding a
// button.
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!(
app.terminal_pointer_forwarded
.is_some_and(|f| f.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"
);
// The pane was re-laid out by the close; release wherever the pointer
// is, the report is clamped to the pane's current grid.
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.terminal_pointer_forwarded.is_none());
}
#[test]
fn a_click_only_drag_keeps_extending_the_origin_pane_after_the_active_pane_moves() {
// Under click-only 1000 the drag is croft's selection on the pane that
// got the press. `Cmd+]` (cycle_terminal) can move the ACTIVE pane while
// the button is held; the drag must keep extending the origin's
// selection, not the new active pane's, and the release must finalise
// it there. Routing through `terminal_mut()` would have left the origin
// at its one-cell anchor and started nothing on the other pane either.
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"
);
// The keyboard moves the active pane mid-gesture.
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.terminal_pointer_forwarded.is_none());
}
#[test]
fn a_double_click_over_a_tracking_child_is_two_forwarded_clicks_not_a_word_select() {
// Both clicks of the pair are the child's, and neither arms croft's
// double-click tracker, so no word is selected. This is the documented
// trade: word-select is unavailable over a tracking app.
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, col, row, lc, lr) = tracking_terminal_app(b"\x1b[?1000h\x1b[?1006h");
// The token is put ON the click row (the helper's cell is grid row 2),
// and the precondition checks it: a word-select on a blank cell selects
// nothing, so without this the "no word" assertion could not fail.
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() {
// Under 1002 the unshifted drag is the child's; Shift+drag is the way
// left to select text in a `mouse=a` vim or lazygit, and it must never
// leak a report.
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() {
// The forwarded-release tail carries its own copy-on-select, aimed at the
// origin pane; it must put the origin's selection on the clipboard the
// way the ordinary mouse-up does.
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 toggling_log_highlighting_flips_open_views_and_the_default() {
// #466: the palette / Settings toggle reaches the view that is already
// open AND steers views opened afterwards, so the user sees the change
// at once and does not get it undone by the next log they open.
let _exclusive = crate::log_view::DEFAULT_HIGHLIGHT_TEST_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
let log = tmp.path().join("build.log");
std::fs::write(&log, b"\x1b[32mok\x1b[0m 2024-01-02 step 1\nplain step 2\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&log).unwrap();
assert!(
app.editor.log.is_some(),
"a coloured .log opens as a rendered log"
);
let before = app.log_highlight;
let view_before = app.editor.log.as_ref().unwrap().highlight();
assert_eq!(
view_before, before,
"the open view starts at the app's setting"
);
app.toggle_log_highlight();
assert_eq!(app.log_highlight, !before);
assert_eq!(
app.editor.log.as_ref().unwrap().highlight(),
!before,
"the open view followed the toggle"
);
assert_eq!(
crate::log_view::default_highlight(),
!before,
"and so will the next log opened"
);
assert!(app.status.starts_with("Log highlighting (tailspin):"));
// Back to where it was, so the process-wide default is left as found.
app.toggle_log_highlight();
assert_eq!(app.log_highlight, before);
assert_eq!(crate::log_view::default_highlight(), before);
}
#[test]
fn startup_seeds_the_log_view_default_from_the_saved_preference() {
// #466: `App::new` seeds the log view's opening default from the saved
// preference. Under test that seed is recorded per thread instead of
// written (hundreds of apps on parallel threads would race the tests
// reading the process-wide default), which keeps the CALL SITE
// observable: this asserts what `App::new` decided, pinned by a
// workspace layer so it does not move with the developer's own config.
let tmp = tempfile::tempdir().unwrap();
let layer = crate::config_layers::workspace_config_path(tmp.path());
std::fs::create_dir_all(layer.parent().unwrap()).unwrap();
std::fs::write(&layer, r#"{"disable_log_highlight": true}"#).unwrap();
STARTUP_LOG_HIGHLIGHT_SEED.with(|c| c.set(None));
let app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(
!app.log_highlight,
"the workspace layer's opt-out reached the field"
);
assert_eq!(
STARTUP_LOG_HIGHLIGHT_SEED.with(|c| c.get()),
Some(false),
"and App::new seeded the log view's opening default with the same value"
);
std::fs::write(&layer, r#"{"disable_log_highlight": false}"#).unwrap();
STARTUP_LOG_HIGHLIGHT_SEED.with(|c| c.set(None));
let app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.log_highlight);
assert_eq!(STARTUP_LOG_HIGHLIGHT_SEED.with(|c| c.get()), Some(true));
}
#[test]
fn a_workspace_layer_setting_disable_log_highlight_applies_on_remerge() {
// #466: `disable_log_highlight` is a workspace-allowed key, so a repo's
// `.croft/config.json` can set it, and a settings remerge (a save of
// that file) must apply it live: to the field, to the default for logs
// opened later, and to every open log view. Read at startup too.
let _exclusive = crate::log_view::DEFAULT_HIGHLIGHT_TEST_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let before = crate::log_view::default_highlight();
let tmp = tempfile::tempdir().unwrap();
let layer = crate::config_layers::workspace_config_path(tmp.path());
std::fs::create_dir_all(layer.parent().unwrap()).unwrap();
std::fs::write(&layer, r#"{"disable_log_highlight": true}"#).unwrap();
let log = tmp.path().join("build.log");
std::fs::write(&log, b"\x1b[32mok\x1b[0m 2024-01-02 step 1\nplain step 2\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(!app.log_highlight, "the workspace layer is read at startup");
app.editor.open_pinned(&log).unwrap();
assert!(
app.editor.log.is_some(),
"a coloured .log opens as a rendered log"
);
// Force the open view on, as a stale default would have left it, so the
// remerge below has something visible to fix.
app.editor.log.as_mut().unwrap().set_highlight(true);
// A second log parked in another split group, so the fan-out over
// inactive groups is exercised, not just the active tab.
let other = tmp.path().join("other.log");
std::fs::write(&other, b"\x1b[31merr\x1b[0m 2024-01-02 step 9\n").unwrap();
app.split_editor();
app.editor.open_pinned(&other).unwrap();
assert!(app.editor.log.is_some());
app.editor.log.as_mut().unwrap().set_highlight(true);
fn parked_log_flags(app: &mut App) -> Vec<bool> {
app.editor_layout
.inactive_groups_mut()
.into_iter()
.flat_map(|g| g.editors.iter())
.filter_map(|e| e.log.as_ref().map(|l| l.highlight()))
.collect()
}
std::fs::write(&layer, r#"{"disable_log_highlight": false}"#).unwrap();
app.reload_config_for_path(&layer);
assert!(
app.log_highlight,
"the remerge applied the workspace layer's new value"
);
assert!(
app.editor.log.as_ref().unwrap().highlight(),
"and pushed it into the open log view"
);
let parked = parked_log_flags(&mut app);
assert!(
!parked.is_empty() && parked.iter().all(|&h| h),
"and into the log parked in the other split group: {parked:?}"
);
assert!(
crate::log_view::default_highlight(),
"and into the default for later logs"
);
std::fs::write(&layer, r#"{"disable_log_highlight": true}"#).unwrap();
app.reload_config_for_path(&layer);
assert!(!app.log_highlight);
assert!(
!app.editor.log.as_ref().unwrap().highlight(),
"the opt-out reaches the open view"
);
assert!(
parked_log_flags(&mut app).iter().all(|&h| !h),
"and the parked one"
);
crate::log_view::set_default_highlight(before);
}
/// #471: no watcher-reported paths, for the poll-shaped refresh calls.
fn no_paths() -> std::collections::BTreeSet<std::path::PathBuf> {
std::collections::BTreeSet::new()
}
/// #471 fixtures: a repo with one committed file, and the app rooted there.
fn repo_with_seed(text: &str) -> (tempfile::TempDir, std::path::PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
for args in [
vec!["init", "-q", "-b", "main"],
vec!["config", "user.email", "a@b"],
vec!["config", "user.name", "a"],
] {
let st = std::process::Command::new("git")
.arg("-C")
.arg(&root)
.args(&args)
.status()
.unwrap();
assert!(st.success(), "git {args:?}");
}
let f = root.join("seed.txt");
std::fs::write(&f, text).unwrap();
git_ok(&root, &["add", "."]);
git_ok(&root, &["commit", "-m", "init", "--quiet"]);
(tmp, f)
}
fn git_ok(root: &std::path::Path, args: &[&str]) {
let st = std::process::Command::new("git")
.arg("-C")
.arg(root)
.args(args)
.status()
.unwrap();
assert!(st.success(), "git {args:?}");
}
/// Write `text` to `path` so that its `(mtime, len)` stamp differs from the
/// one before the write: a stamp-gated refresh must not miss a rewrite that
/// lands within the filesystem's mtime granularity of the previous one. A
/// different length differs at once; an equal length waits for the clock.
fn rewrite_later(path: &std::path::Path, text: &str) {
let stamp = |p: &std::path::Path| {
std::fs::metadata(p)
.ok()
.and_then(|m| Some((m.modified().ok()?, m.len())))
};
let before = stamp(path);
std::fs::write(path, text).unwrap();
let mut spins = 0;
while stamp(path) == before && spins < 400 {
std::thread::sleep(std::time::Duration::from_millis(5));
std::fs::write(path, text).unwrap();
spins += 1;
}
assert_ne!(
stamp(path),
before,
"the rewrite must move the file's stamp"
);
}
#[test]
fn an_open_head_diff_follows_the_working_file_and_head() {
// The Source Control diff used to be a snapshot: an agent rewriting the
// file, or a save from a sibling tab, left the rows stale until the tab
// was reopened (#471). Now the view is rebuilt in place -- from disk on
// a filesystem trigger, from HEAD too on a git-status trigger -- with
// the reader's viewport kept.
let (tmp, f) = repo_with_seed("one\ntwo\n");
let root = tmp.path().to_path_buf();
let mut app = App::new(root.clone()).unwrap();
// Open exactly what open_source_control_entry opens for a Modified row.
std::fs::write(&f, "one\ntwo\nthree\n").unwrap();
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("seed.txt (HEAD)"),
"one\ntwo\n",
&f,
true,
)
.unwrap();
app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
root: root.clone(),
rel: String::from("seed.txt"),
});
assert_eq!(app.editor.diff.as_ref().unwrap().right_lines.len(), 3);
assert!(
!app.refresh_open_diff_views(false, &[], &no_paths()),
"nothing moved yet: the refresh is a no-op"
);
// The working file grows under the open view.
rewrite_later(&f, "one\ntwo\nthree\nfour\nfive\n");
app.editor.diff.as_mut().unwrap().scroll = 1;
assert!(
app.refresh_open_diff_views(false, &[], &no_paths()),
"a filesystem trigger rebuilds the view from the changed file"
);
let d = app.editor.diff.as_ref().unwrap();
assert_eq!(d.right_lines, vec!["one", "two", "three", "four", "five"]);
assert_eq!(d.left_lines, vec!["one", "two"], "HEAD side untouched");
assert_eq!(
d.scroll, 1,
"the reader's viewport is kept, not reset to the first hunk"
);
assert!(
d.left_is_git_head,
"the rebuilt view still gates stage/revert like the original"
);
assert!(
matches!(
d.source,
crate::widgets::diff::DiffSource::HeadVsWorking { .. }
),
"the source survives the rebuild"
);
assert!(
!app.refresh_open_diff_views(false, &[], &no_paths()),
"the stamps were taken: a second tick does not rebuild again"
);
// A commit moves HEAD: the git-status trigger re-reads the left side.
git_ok(&root, &["add", "."]);
git_ok(&root, &["commit", "-m", "grow", "--quiet"]);
assert!(
!app.refresh_open_diff_views(false, &[], &no_paths()),
"a filesystem-only trigger does not re-read HEAD"
);
assert!(
!app.refresh_open_diff_views(true, &[], &no_paths()),
"nor does a git-status drain in which THIS root's HEAD did not move"
);
assert!(
app.refresh_open_diff_views(true, std::slice::from_ref(&root), &no_paths()),
"the drain that saw this root's HEAD move does"
);
let d = app.editor.diff.as_ref().unwrap();
assert_eq!(
d.left_lines, d.right_lines,
"after the commit both sides agree"
);
}
#[test]
fn edge_autoscroll_stands_down_while_the_forwarded_pane_is_not_active_and_resumes() {
// The tick scrolls the ACTIVE pane. With a click-only forwarded drag
// parked past pane 0's top edge, Cmd+] must not have the tick walk pane
// 1's scrollback, and Cmd+[ back must let it resume without a new Drag
// event, since a parked pointer sends none.
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");
// Enough history in pane 1 that a stray tick would visibly move it.
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);
// Park the pointer above the top edge: the drag arms auto-scroll.
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
col,
inner.y.saturating_sub(1),
));
assert!(
app.terminal_select_autoscroll.is_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!(
app.terminal_select_autoscroll.is_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() {
// The forwarded-release tail runs copy-on-select only for a gesture the
// Drag arm turned into croft's selection. A plain click that stayed the
// child's leaves the clipboard alone even with copy-on-select on.
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() {
// A parked, armed forwarded drag whose origin pane is then closed has
// nothing to resume on: the tick drops the gesture instead of standing
// down until a release that may never come.
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!(
app.terminal_select_autoscroll.is_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.terminal_select_autoscroll.is_none() && app.terminal_pointer_forwarded.is_none(),
"the gesture is dropped, not held"
);
}
#[test]
fn a_staged_diff_view_reruns_git_on_a_status_trigger_only() {
let (tmp, f) = repo_with_seed("alpha\n");
let root = tmp.path().to_path_buf();
let mut app = App::new(root.clone()).unwrap();
let raw = crate::git::diff_staged(&root).unwrap();
app.editor
.open_git_diff_side_by_side(std::path::Path::new("git diff --staged"), &raw)
.unwrap();
app.tag_open_diff(crate::widgets::diff::DiffSource::GitCommand {
root: root.clone(),
kind: crate::widgets::diff::GitDiffKind::Staged,
});
assert!(
app.editor
.diff
.as_ref()
.unwrap()
.right_lines
.contains(&String::from("(no changes)")),
"nothing is staged yet"
);
std::fs::write(&f, "alpha\nbeta\n").unwrap();
git_ok(&root, &["add", "seed.txt"]);
assert!(
!app.refresh_open_diff_views(false, &[], &no_paths()),
"a git-command view is not re-run on a filesystem tick: the index is not a file it watches"
);
assert!(
app.refresh_open_diff_views(true, &[], &no_paths()),
"the git-status drain re-runs it"
);
let d = app.editor.diff.as_ref().unwrap();
assert!(
d.right_lines.iter().any(|l| l == "beta"),
"the staged line now shows: {:?}",
d.right_lines
);
assert!(
!app.refresh_open_diff_views(true, &[], &no_paths()),
"identical output changes nothing"
);
}
#[test]
fn a_snapshot_and_a_two_file_diff_follow_their_files() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
let b = tmp.path().join("b.txt");
std::fs::write(&a, "x\n").unwrap();
std::fs::write(&b, "x\ny\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Timeline snapshot: fixed left text against the working file.
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("b.txt (local snapshot)"),
"x\n",
&b,
false,
)
.unwrap();
app.tag_open_diff(crate::widgets::diff::DiffSource::FixedLeft {
left_text: String::from("x\n"),
});
rewrite_later(&b, "x\ny\nz\n");
assert!(app.refresh_open_diff_views(false, &[], &no_paths()));
let d = app.editor.diff.as_ref().unwrap();
assert_eq!(d.right_lines, vec!["x", "y", "z"]);
assert_eq!(d.left_lines, vec!["x"], "the snapshot side never changes");
assert!(!d.left_is_git_head, "a snapshot view still cannot stage");
// Two real files: either side moving rebuilds.
app.editor.open_diff(&a, &b).unwrap();
rewrite_later(&a, "x\nw\n");
assert!(app.refresh_open_diff_views(false, &[], &no_paths()));
let d = app.editor.diff.as_ref().unwrap();
assert_eq!(d.left_lines, vec!["x", "w"]);
assert!(
d.left_is_real_file,
"Enter on a Removed row still opens the left file"
);
assert!(!app.refresh_open_diff_views(false, &[], &no_paths()));
}
#[test]
fn a_diff_view_in_an_inactive_split_group_is_refreshed_too() {
// Every group is swept, not just the focused one: the diff the user
// parked in the other split is exactly the one they are watching while
// they type in this one.
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
let b = tmp.path().join("b.txt");
std::fs::write(&a, "1\n").unwrap();
std::fs::write(&b, "1\n2\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_diff(&a, &b).unwrap();
app.split_editor();
app.editor.open_pinned(&a).unwrap();
assert!(
app.editor.diff.is_none(),
"the focused group shows a plain buffer"
);
rewrite_later(&b, "1\n2\n3\n");
assert!(app.refresh_open_diff_views(false, &[], &no_paths()));
let stale = app
.editor_layout
.inactive_groups_mut()
.into_iter()
.flat_map(|g| g.editors.iter())
.filter_map(|e| e.diff.as_ref())
.any(|d| d.right_lines.len() != 3);
assert!(!stale, "the inactive group's diff shows the third line");
}
#[test]
fn a_rewrite_that_only_changes_bytes_still_refreshes_the_byte_facts() {
// A final newline added to the working file changes no line text, so the
// rows come back identical -- but `right_no_final_nl` and the "bytes
// differ, lines equal" banner feed the hunk patch and the header. The
// same-content skip must see those facts as content, or stage/revert
// would build a patch from bytes no longer on disk.
let (tmp, f) = repo_with_seed("a\nb\n");
let root = tmp.path().to_path_buf();
let mut app = App::new(root.clone()).unwrap();
std::fs::write(&f, "a\nb").unwrap();
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("seed.txt (HEAD)"),
"a\nb\n",
&f,
true,
)
.unwrap();
app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
root: root.clone(),
rel: String::from("seed.txt"),
});
let d = app.editor.diff.as_ref().unwrap();
assert!(
d.right_no_final_nl && d.bytes_differ_but_lines_equal,
"precondition: {d:?}"
);
rewrite_later(&f, "a\nb\n");
assert!(
app.refresh_open_diff_views(false, &[], &no_paths()),
"the byte-only rewrite counts as a change"
);
let d = app.editor.diff.as_ref().unwrap();
assert!(
!d.right_no_final_nl,
"the working side now ends in a newline"
);
assert!(
!d.bytes_differ_but_lines_equal,
"and the banner's fact is cleared"
);
assert!(
!app.refresh_open_diff_views(false, &[], &no_paths()),
"and it is not rebuilt again"
);
}
#[test]
fn a_same_length_rewrite_with_a_preserved_mtime_refreshes_on_the_watcher_path() {
// `(mtime, len)` cannot see a rewrite that keeps both, and the poll has
// nothing else to go on. The watcher does: it names the path, and a
// named path bypasses the stamp gate.
let (tmp, f) = repo_with_seed("one\ntwo\n");
let root = tmp.path().to_path_buf();
let mut app = App::new(root.clone()).unwrap();
std::fs::write(&f, "one\ntwo\nAAA\n").unwrap();
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("seed.txt (HEAD)"),
"one\ntwo\n",
&f,
true,
)
.unwrap();
app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
root: root.clone(),
rel: String::from("seed.txt"),
});
let mtime = std::fs::metadata(&f).unwrap().modified().unwrap();
std::fs::write(&f, "one\ntwo\nBBB\n").unwrap();
std::fs::File::options()
.write(true)
.open(&f)
.unwrap()
.set_modified(mtime)
.unwrap();
assert_eq!(
std::fs::metadata(&f).unwrap().modified().unwrap(),
mtime,
"precondition: the rewrite preserved the mtime"
);
assert!(
!app.refresh_open_diff_views(false, &[], &no_paths()),
"the poll's stamp gate cannot see this rewrite"
);
let mut written = std::collections::BTreeSet::new();
written.insert(f.clone());
assert!(
app.refresh_open_diff_views(false, &[], &written),
"the watcher naming the path rebuilds the view regardless of the stamp"
);
assert!(
app.editor
.diff
.as_ref()
.unwrap()
.right_lines
.iter()
.any(|l| l == "BBB"),
"the view shows the rewritten bytes"
);
}
#[test]
fn a_rebuild_recomputes_the_find_match_against_the_new_rows() {
// The active find match names a row of the OLD rows. After a rebuild it
// is dropped and, with the find bar open, recomputed: gone when the new
// rows no longer hold the needle, back when they do again.
let (tmp, f) = repo_with_seed("alpha\n");
let root = tmp.path().to_path_buf();
let mut app = App::new(root.clone()).unwrap();
std::fs::write(&f, "alpha\nneedle here\n").unwrap();
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("seed.txt (HEAD)"),
"alpha\n",
&f,
true,
)
.unwrap();
app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
root: root.clone(),
rel: String::from("seed.txt"),
});
app.open_editor_find();
app.diff_find_set_query(String::from("needle"));
assert!(
app.editor.diff.as_ref().unwrap().find.active.is_some(),
"precondition: the needle is found"
);
rewrite_later(&f, "alpha\nnothing to see\n");
assert!(app.refresh_open_diff_views(false, &[], &no_paths()));
let d = app.editor.diff.as_ref().unwrap();
assert!(d.find.active.is_none(), "no row holds the needle now");
assert_eq!(
d.find.needle.as_deref(),
Some("needle"),
"the query itself survives"
);
assert_eq!(
app.editor_find.as_ref().and_then(|s| s.match_index),
None,
"the find bar agrees: no current match"
);
rewrite_later(&f, "alpha\nthe needle is back\nneedle twice\n");
assert!(app.refresh_open_diff_views(false, &[], &no_paths()));
let d = app.editor.diff.as_ref().unwrap();
assert!(
d.find.active.is_some(),
"the match is recomputed on the new rows"
);
assert_eq!(
app.editor_find.as_ref().and_then(|s| s.match_index),
Some(1),
"and the find bar counts from the first"
);
}
#[test]
fn a_staged_view_reruns_when_a_status_refresh_lands_unchanged() {
// Replacing an already-staged file's bytes leaves porcelain status
// identical ("M seed.txt" before and after), so a "status changed"
// gate would never re-run the staged view. The completed refresh is the
// signal, and it flows through the real worker drain here.
let (tmp, f) = repo_with_seed("alpha\n");
let root = tmp.path().to_path_buf();
let mut app = App::new(root.clone()).unwrap();
// Let the worker's first status land so later ones can compare equal.
crate::test_budget::await_spawned(
crate::test_budget::tests::RESTORED_SHELL_BASE,
"the git worker's first status",
|| {
app.try_install_pending_init();
app.git.status().in_repo
},
);
std::fs::write(&f, "alpha\nbeta\n").unwrap();
git_ok(&root, &["add", "seed.txt"]);
let raw = crate::git::diff_staged(&root).unwrap();
app.editor
.open_git_diff_side_by_side(std::path::Path::new("git diff --staged"), &raw)
.unwrap();
app.tag_open_diff(crate::widgets::diff::DiffSource::GitCommand {
root: root.clone(),
kind: crate::widgets::diff::GitDiffKind::Staged,
});
assert!(
app.editor
.diff
.as_ref()
.unwrap()
.right_lines
.iter()
.any(|l| l == "beta")
);
// Same porcelain status, different index bytes.
std::fs::write(&f, "alpha\ngamma\n").unwrap();
git_ok(&root, &["add", "seed.txt"]);
app.active_git_bypass_debounce();
app.refresh_git_status_debounced();
crate::test_budget::await_spawned(
crate::test_budget::tests::RESTORED_SHELL_BASE,
"the staged view to show the re-staged bytes",
|| {
app.try_install_pending_init();
app.editor
.diff
.as_ref()
.is_some_and(|d| d.right_lines.iter().any(|l| l == "gamma"))
},
);
}
#[test]
fn a_head_diff_tagged_with_the_repo_toplevel_refreshes_from_a_subdirectory_workspace() {
// The Source Control opener tags a view with `scm_root()`, the git
// TOPLEVEL. From a subdirectory workspace that is not the workspace
// root the drain keys its HEAD-oid bookkeeping on, so `heads_moved`
// has to record the toplevel (and compare canonically), or a commit
// never re-reads the HEAD side. This drives the real drain.
let (tmp, f) = repo_with_seed("one\n");
let root = tmp.path().to_path_buf();
let sub = root.join("sub");
std::fs::create_dir_all(&sub).unwrap();
let mut app = App::new(sub.clone()).unwrap();
crate::test_budget::await_spawned(
crate::test_budget::tests::RESTORED_SHELL_BASE,
"the git worker's first status",
|| {
app.try_install_pending_init();
app.git.status().in_repo
},
);
let scm = app.scm_root();
assert_ne!(
scm, sub,
"precondition: the toplevel is not the workspace root"
);
std::fs::write(&f, "one\ntwo\n").unwrap();
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("seed.txt (HEAD)"),
"one\n",
&f,
true,
)
.unwrap();
app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
root: scm.clone(),
rel: String::from("seed.txt"),
});
git_ok(&root, &["add", "."]);
git_ok(&root, &["commit", "-m", "two", "--quiet"]);
app.active_git_bypass_debounce();
app.refresh_git_status_debounced();
crate::test_budget::await_spawned(
crate::test_budget::tests::RESTORED_SHELL_BASE,
"the HEAD side to follow the commit through the status drain",
|| {
app.try_install_pending_init();
app.editor
.diff
.as_ref()
.is_some_and(|d| d.left_lines == d.right_lines && d.right_lines.len() == 2)
},
);
}
#[test]
fn a_background_diff_refresh_leaves_the_active_diff_find_and_anchor_alone() {
// Only a rebuild of the ACTIVE tab recomputes the find bar; a diff
// refreshing in another split must not scroll or re-anchor the view the
// reader is on.
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
let b = tmp.path().join("b.txt");
let c = tmp.path().join("c.txt");
let d = tmp.path().join("d.txt");
std::fs::write(&a, "1\n").unwrap();
std::fs::write(&b, "1\n2\n").unwrap();
std::fs::write(&c, "x\n").unwrap();
std::fs::write(&d, "x\nneedle\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_diff(&a, &b).unwrap();
app.split_editor();
app.editor.open_diff(&c, &d).unwrap();
app.open_editor_find();
app.diff_find_set_query(String::from("needle"));
// Anchored AFTER the query: `diff_find_apply` scrolls to its match and
// clears the hunk anchor, which is exactly why a spurious recompute
// from a background refresh would be visible here.
app.editor.diff.as_mut().unwrap().nav_anchor = Some(0);
let before = app.editor.diff.as_ref().unwrap().clone();
assert!(
before.find.active.is_some(),
"precondition: the active diff has a match"
);
rewrite_later(&b, "1\n2\n3\n");
assert!(
app.refresh_open_diff_views(false, &[], &no_paths()),
"the background split's diff rebuilt"
);
let after = app.editor.diff.as_ref().unwrap();
assert_eq!(
after.nav_anchor,
Some(0),
"the active diff's hunk anchor is untouched"
);
assert_eq!(after.scroll, before.scroll, "and its viewport");
assert_eq!(
after.find.active, before.find.active,
"and its active match"
);
}
#[test]
fn a_rebuild_that_changes_the_rows_drops_the_hunk_anchor() {
// `nav_anchor` is the one input to `action_row`, which S/U/R read. Over
// rebuilt rows the remembered index names whatever now sits there, so
// the anchor is dropped and the actions fall back to the viewport, as
// after a manual scroll.
let (tmp, f) = repo_with_seed("a\nb\nc\nd\ne\n");
let root = tmp.path().to_path_buf();
let mut app = App::new(root.clone()).unwrap();
std::fs::write(&f, "a\nB\nc\nd\nE\n").unwrap();
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("seed.txt (HEAD)"),
"a\nb\nc\nd\ne\n",
&f,
true,
)
.unwrap();
app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
root: root.clone(),
rel: String::from("seed.txt"),
});
app.jump_diff_change(true);
assert!(
app.editor.diff.as_ref().unwrap().nav_anchor.is_some(),
"precondition: a jump anchored a hunk"
);
// A new hunk ABOVE the anchored one shifts every row under the index.
rewrite_later(&f, "A\nB\nc\nd\nE\n");
assert!(app.refresh_open_diff_views(false, &[], &no_paths()));
assert_eq!(
app.editor.diff.as_ref().unwrap().nav_anchor,
None,
"the anchor does not survive rows it no longer describes"
);
}
#[test]
fn a_background_diff_keeps_its_find_band_across_a_rebuild() {
// The active match is recomputed inside `carry_view_from`, so a view
// rebuilt in a background split keeps its band without the app's
// find-bar recompute, which only runs for the active tab.
let tmp = tempfile::tempdir().unwrap();
let c = tmp.path().join("c.txt");
let d = tmp.path().join("d.txt");
std::fs::write(&c, "x\n").unwrap();
std::fs::write(&d, "x\nneedle\n").unwrap();
let plain = tmp.path().join("plain.txt");
std::fs::write(&plain, "hi\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_diff(&c, &d).unwrap();
app.open_editor_find();
app.diff_find_set_query(String::from("needle"));
assert!(app.editor.diff.as_ref().unwrap().find.active.is_some());
// The diff moves to the background: a split, and a plain file on top.
app.split_editor();
app.editor.open_pinned(&plain).unwrap();
assert!(
app.editor.diff.is_none(),
"the active tab is the plain file"
);
rewrite_later(&d, "x\nstill a needle\nmore\n");
assert!(app.refresh_open_diff_views(false, &[], &no_paths()));
let mut seen = 0;
for group in app.editor_layout.inactive_groups_mut() {
for ed in &group.editors {
if let Some(dd) = ed.diff.as_ref().filter(|dd| dd.right_path == d) {
seen += 1;
assert_eq!(dd.find.needle.as_deref(), Some("needle"));
assert!(
dd.find.active.is_some(),
"the background view's active match was recomputed in place"
);
}
}
}
assert!(seen >= 1, "the background split still holds the diff");
}
#[test]
fn an_ssh_session_raises_the_offer_once_and_drops_it_when_the_session_ends() {
// #364: the offer appears when a pane's foreground BECOMES `ssh <host>`
// for a known host, not on every sample of the same session, and it
// leaves with the session.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// The refusal memory is read from the real cache directory at startup;
// this machine's must not decide the test.
app.remote_offer_refused.clear();
let pane = app.terminals[0].uid();
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(
app.ssh_offer
.as_ref()
.is_some_and(|o| o.pane == pane && o.host == "db-1"),
"a new session offers"
);
assert!(
app.status.starts_with("Connected to db-1"),
"{:?}",
app.status
);
app.status = String::from("something else happened");
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert_eq!(
app.status, "something else happened",
"the same session sampled again does not re-prompt"
);
app.status = String::from("Connected to db-1 · Open workspace here?");
app.consider_ssh_offer(pane, None);
assert!(
app.ssh_offer.is_none(),
"the session ended: the offer is gone"
);
assert!(app.status.is_empty(), "and its status line with it");
// A NEW session to the same host offers again.
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(app.ssh_offer.is_some());
}
#[test]
fn the_offer_respects_the_global_switch_the_host_list_and_learned_refusals() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.remote_offer_refused.clear();
let pane = app.terminals[0].uid();
app.remote_offer_excluded = vec![String::from("DB-1")];
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(
app.ssh_offer.is_none(),
"per-host opt-out, case-insensitive"
);
app.remote_offer_excluded.clear();
app.remote_offer_refused
.insert(String::from("db-1"), std::time::SystemTime::now());
app.consider_ssh_offer(pane, None);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(
app.ssh_offer.is_none(),
"a host that refused provisioning is not offered"
);
app.remote_offer_refused.clear();
app.remote_offer_disabled = true;
app.consider_ssh_offer(pane, None);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(app.ssh_offer.is_none(), "the global switch");
app.remote_offer_disabled = false;
app.consider_ssh_offer(pane, None);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(
app.ssh_offer.is_some(),
"and with every gate open it offers"
);
}
#[test]
fn accepting_or_dismissing_the_offer_clears_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// The refusal memory is read from the real cache directory at startup;
// this machine's must not decide the test.
app.remote_offer_refused.clear();
let pane = app.terminals[0].uid();
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert_eq!(
app.accept_ssh_offer().map(|(host, _)| host).as_deref(),
Some("db-1")
);
assert!(app.ssh_offer.is_none() && app.status.is_empty());
assert_eq!(app.accept_ssh_offer(), None, "nothing to accept twice");
app.consider_ssh_offer(pane, None);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(app.ssh_offer.is_some());
// Esc dismisses through the ordinary key path, whatever pane has focus.
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(app.ssh_offer.is_none(), "Esc dismissed the offer");
assert!(app.status.is_empty());
}
#[test]
fn 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();
// The refusal memory is read from the real cache directory at startup;
// this machine's must not decide the test.
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() {
// `ssh a cmd; ssh b cmd` inside one sample gap: the offer for A must not
// stay up (and be accepted with Cmd+K G) once the pane is on B, whether
// or not B itself is offerable.
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 the_offer_switches_apply_on_a_settings_remerge() {
// The two prefs re-apply on a config save like every other boolean pref,
// and switching the offer off takes down one already on screen.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// The refusal memory is read from the real cache directory at startup;
// this machine's must not decide the test.
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,
remote_offer_excluded_hosts: vec![String::from("jump")],
..Default::default()
};
app.apply_merged_settings(&prefs);
assert!(app.remote_offer_disabled && app.remote_offer_excluded == vec![String::from("jump")]);
assert!(
app.ssh_offer.is_none(),
"the live offer went down with the switch"
);
prefs.disable_remote_offer = false;
app.apply_merged_settings(&prefs);
assert!(!app.remote_offer_disabled);
// An offer on screen for a host that just joined the exclusion list
// goes down too, not only on the global switch.
app.consider_ssh_offer(pane, None);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(app.ssh_offer.is_some());
prefs.remote_offer_excluded_hosts = vec![String::from("db-1")];
app.apply_merged_settings(&prefs);
assert!(
app.ssh_offer.is_none(),
"the newly excluded host's offer went down"
);
}
#[test]
fn switching_the_offer_off_and_on_forgets_what_each_pane_was_last_seen_on() {
// While the offer is off the label thread ships no samples, so the
// per-pane memory stops tracking reality. Session A on db-1, offer off,
// session A ends and session B to db-1 starts, offer on: B is a new
// session and must be offered, not mistaken for a continuation of A.
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");
// No `None` sample in between: nothing observed the gap.
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"
);
}
#[test]
fn taking_a_host_off_the_exclusion_list_offers_the_session_already_on_it() {
// A pane sampled on db-1 while db-1 was excluded is remembered as seen
// there; the same host on the next sample would read as the same
// session and never prompt. Un-excluding the host forgets that, so the
// next sample offers it.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.remote_offer_refused.clear();
let pane = app.terminals[0].uid();
let mut prefs = crate::prefs::Prefs {
remote_offer_excluded_hosts: vec![String::from("DB-1")],
..Default::default()
};
app.apply_merged_settings(&prefs);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(app.ssh_offer.is_none(), "excluded: no offer");
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(
app.ssh_offer.is_none(),
"still the same session, still excluded"
);
prefs.remote_offer_excluded_hosts.clear();
app.apply_merged_settings(&prefs);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(
app.ssh_offer
.as_ref()
.is_some_and(|o| o.pane == pane && o.host == "db-1"),
"the live session is offered once its host is allowed again"
);
// A pane on a host that stayed excluded is untouched by the change.
prefs.remote_offer_excluded_hosts = vec![String::from("jump"), String::from("db-1")];
app.apply_merged_settings(&prefs);
assert!(
app.ssh_offer.is_none(),
"re-excluding db-1 takes its offer down"
);
app.consider_ssh_offer(pane, Some(String::from("jump")));
prefs.remote_offer_excluded_hosts = vec![String::from("jump")];
app.apply_merged_settings(&prefs);
app.consider_ssh_offer(pane, Some(String::from("jump")));
assert!(
app.ssh_offer.is_none(),
"jump stayed excluded and stayed quiet"
);
}
#[test]
fn an_in_memory_refusal_stops_blocking_once_its_window_has_passed() {
// The TTL is applied when the policy is asked, not only when the file
// is loaded: a croft left open past the window offers the host again.
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_refused.insert(
String::from("db-1"),
std::time::SystemTime::now()
- crate::remote::REFUSED_HOST_TTL
- std::time::Duration::from_secs(60),
);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(
app.ssh_offer.is_some(),
"a refusal older than the TTL no longer suppresses the offer"
);
}
#[test]
fn cmd_k_g_with_no_offer_open_says_so_instead_of_connecting() {
// The chord's guidance branch: nothing to accept, nothing launched, a
// status that says where the offer comes from. (The accept branch runs
// `request_remote_launch`, which spawns a real ssh; `accept_ssh_offer`
// is covered directly instead of reaching the network from a test.)
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.ssh_offer.is_none());
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('g'), KeyModifiers::NONE)));
assert!(
app.status.starts_with("No ssh workspace offer is open"),
"status: {}",
app.status
);
assert!(app.connect_dialog.is_none(), "nothing was launched");
assert!(app.pending_remote_launch_host.is_none());
}
#[test]
fn ssh_samples_from_the_label_thread_drive_the_offer_by_shell_pid() {
// The label thread ships `(shell pid, host)`; the app maps the shell pid
// to the pane's uid and feeds the same transition logic the direct tests
// cover. An unknown shell pid is ignored.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.remote_offer_refused.clear();
let shell = app.terminals[0]
.shell_pid()
.expect("the pane has a shell pid");
let uid = app.terminals[0].uid();
app.apply_ssh_samples(vec![
(shell, Some(String::from("db-1"))),
(-42, Some(String::from("x"))),
]);
assert!(
app.ssh_offer
.as_ref()
.is_some_and(|o| o.pane == uid && o.host == "db-1")
);
app.apply_ssh_samples(vec![(shell, None)]);
assert!(
app.ssh_offer.is_none(),
"the session ended through the same path"
);
}
#[test]
fn a_failed_provisioning_is_remembered_and_a_later_success_forgets_it() {
// Drives the two notes the install session calls, against the cache-dir
// override so nothing touches this machine's real memory.
let _serial = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
struct Restore;
impl Drop for Restore {
fn drop(&mut self) {
*crate::app::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = None;
}
}
let _restore = Restore;
*crate::app::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = Some(tmp.path().join("cache"));
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(
app.remote_offer_refused.is_empty(),
"a fresh cache dir remembers nothing"
);
let pane = app.terminals[0].uid();
app.note_provisioning_failed("DB-1", "refused");
assert!(
app.remote_offer_refused.contains_key("db-1"),
"remembered in memory, lower-cased"
);
let refused_path = crate::remote::refused_hosts_path(&tmp.path().join("cache"));
let on_disk = crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now());
assert!(on_disk.contains_key("db-1"), "and on disk: {on_disk:?}");
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(app.ssh_offer.is_none(), "a refused host is not offered");
app.note_provisioning_succeeded("db-1");
assert!(
!app.remote_offer_refused.contains_key("db-1"),
"a success forgets it in memory"
);
let on_disk = crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now());
assert!(!on_disk.contains_key("db-1"), "and on disk");
app.consider_ssh_offer(pane, None);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(app.ssh_offer.is_some(), "and the host is offered again");
}
#[test]
fn a_success_forgets_a_refusal_another_croft_recorded() {
// The refusal file is shared by every croft on the machine. A refusal
// this instance never loaded (recorded by another one after this one
// started) must still be erased by a success here, or it outlives the
// host that demonstrably works for its whole seven-day TTL.
let _serial = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::tempdir().unwrap();
struct Restore;
impl Drop for Restore {
fn drop(&mut self) {
*crate::app::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = None;
}
}
let _restore = Restore;
let cache = tmp.path().join("cache");
*crate::app::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = Some(cache.clone());
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.remote_offer_refused.clear();
let refused_path = crate::remote::refused_hosts_path(&cache);
// "Another instance" writes the refusal behind this one's back.
crate::remote::remember_refused_host(&refused_path, "db-1", std::time::SystemTime::now())
.unwrap();
assert!(
crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now())
.contains_key("db-1")
);
app.note_provisioning_succeeded("DB-1");
assert!(
!crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now())
.contains_key("db-1"),
"the disk refusal is gone even though this instance never held it"
);
}
/// A committed git repo at `dir` for the worktree-lane tests (#348): a lane
/// is a sibling of the repo, so callers put the repo one level inside their
/// tempdir to keep the lane inside it too.
fn init_lane_repo(dir: &std::path::Path) {
std::fs::create_dir_all(dir).unwrap();
let git = |args: &[&str]| {
let st = std::process::Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.status()
.unwrap();
assert!(st.success(), "git {args:?}");
};
git(&["init", "-q", "-b", "main"]);
git(&["config", "user.email", "a@b"]);
git(&["config", "user.name", "a"]);
std::fs::write(dir.join("seed.txt"), "one\n").unwrap();
git(&["add", "."]);
git(&["commit", "-q", "-m", "init"]);
}
#[test]
fn a_new_lane_opens_a_named_pane_in_the_worktree_running_the_agent_command() {
// One chord's worth (#348): worktree, root, and a pane named after the
// lane sitting in it with the configured agent's launch line typed in.
// The "agent" is a printf whose typed line does not spell the probe.
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
init_lane_repo(&repo);
let mut app = App::new(repo.clone()).unwrap();
app.terminal_session_path = tmp.path().join("sessions.json");
app.agents = crate::agents::AgentTable::from_json(
r#"[{ "name": "probe", "launch": "printf '%s%s\\n' 'croft-lane' '-seated-1'" }]"#,
);
app.lane_agent = Some(String::from("Probe"));
let before = app.terminals.len();
app.create_worktree_lane("fix login");
let lane = tmp.path().join("repo-fix-login");
assert!(lane.is_dir(), "the worktree exists: {}", app.status);
assert!(
app.roots.iter().any(|r| r == lane.canonicalize().unwrap()),
"and is a workspace root"
);
assert_eq!(app.terminals.len(), before + 1, "one new pane");
let pane = &app.terminals[app.active_terminal];
assert_eq!(pane.manual_name(), Some("Lane: fix-login"));
let rec = app
.lane_panes
.get(&pane.uid())
.expect("the pane is recorded as the lane's");
assert_eq!(rec.branch, "agent/fix-login");
assert_eq!(rec.agent.as_deref(), Some("probe"), "lower-cased row name");
assert!(app.status.contains("probe started"), "{}", app.status);
let budget = crate::test_budget::spawn_budget(crate::test_budget::tests::TERMINAL_PROBE_BASE);
let started = std::time::Instant::now();
while started.elapsed() < budget {
if app.terminals[app.active_terminal]
.visible_text()
.contains("croft-lane-seated-1")
{
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert!(
app.terminals[app.active_terminal]
.visible_text()
.contains("croft-lane-seated-1"),
"the launch line ran in the lane's pane; screen:\n{}",
app.terminals[app.active_terminal].visible_text()
);
// The saved session carries the lane, so a relaunch can seat it again.
let saved = crate::terminal_session::load(&app.terminal_session_path);
let root_key = app.workspace_root().display().to_string();
let lanes: Vec<_> = saved[&root_key]
.panes
.iter()
.filter_map(|p| p.lane.clone())
.collect();
assert_eq!(lanes.len(), 1, "{saved:?}");
assert_eq!(lanes[0].agent.as_deref(), Some("probe"));
assert_eq!(
std::path::Path::new(&lanes[0].path),
lane.canonicalize().unwrap(),
"recorded canonical, like the roots"
);
}
#[test]
fn a_lane_without_a_configured_agent_opens_a_plain_shell_and_says_so() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
init_lane_repo(&repo);
let mut app = App::new(repo.clone()).unwrap();
app.terminal_session_path = tmp.path().join("sessions.json");
app.lane_agent = None;
app.create_worktree_lane("docs");
let pane = &app.terminals[app.active_terminal];
assert_eq!(pane.manual_name(), Some("Lane: docs"));
assert_eq!(app.lane_panes[&pane.uid()].agent, None);
assert!(app.status.contains("set lane_agent"), "{}", app.status);
// An agent named but without a launch line: shell, and the status names
// the gap rather than reading as a working lane.
app.agents = crate::agents::AgentTable::from_json(r#"[{ "name": "mute" }]"#);
app.lane_agent = Some(String::from("mute"));
app.create_worktree_lane("tests");
let pane = &app.terminals[app.active_terminal];
assert_eq!(pane.manual_name(), Some("Lane: tests"));
assert_eq!(
app.lane_panes[&pane.uid()].agent,
None,
"no agent was seated"
);
assert!(
app.status.contains("no launch line for \"mute\""),
"{}",
app.status
);
}
#[cfg(target_os = "linux")]
#[test]
fn a_restore_reattaches_a_shell_still_running_in_its_pane_host() {
// #694: croft was killed, not quit, so the pane's host still holds its
// shell. Restoring reattaches to it (same shell, its screen redrawn)
// instead of starting a fresh one; a pane whose host is gone falls back
// to a fresh shell as before. The record keeps naming the live host, so
// a second crash finds it again.
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();
assert_eq!(app.terminals.len(), 2);
let kept = &app.terminals[0];
assert_eq!(kept.host_socket(), Some(socket.as_path()), "reattached");
assert_eq!(kept.manual_name(), Some("kept"));
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(4);
loop {
let (lines, _) = kept.grid_lines();
if lines.iter().any(|l| l.contains("still-42")) {
assert!(
!lines.iter().any(|l| l.contains("old transcript")),
"the live screen, not the saved transcript: {lines:?}"
);
break;
}
assert!(std::time::Instant::now() < deadline, "{lines:?}");
std::thread::sleep(std::time::Duration::from_millis(20));
}
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);
// Quitting closes the panes, which ends the reattached shell too.
drop(app);
host.join().unwrap().unwrap();
}
#[test]
fn a_restored_lane_pane_is_a_lane_again_with_its_agent_seated() {
// The association survives a relaunch (#348): the saved lane record
// brings the pane back in the worktree, re-registered as the lane's, and
// the agent's CURRENT launch line typed in. A lane whose worktree is
// gone comes back as an ordinary pane.
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
init_lane_repo(&repo);
let session = tmp.path().join("sessions.json");
let lane_dir = tmp.path().join("repo-fix-login");
std::fs::create_dir_all(&lane_dir).unwrap();
let root_key = repo.display().to_string();
let rec = crate::terminal_session::SessionRecord {
panes: vec![
crate::terminal_session::PaneRecord {
host: None,
cwd: root_key.clone(),
name: None,
transcript: Vec::new(),
lane: None,
},
crate::terminal_session::PaneRecord {
host: None,
cwd: lane_dir.display().to_string(),
name: Some(String::from("Lane: fix-login")),
transcript: Vec::new(),
lane: Some(crate::terminal_session::LaneRecord {
path: lane_dir.display().to_string(),
branch: String::from("agent/fix-login"),
agent: Some(String::from("probe")),
base: None,
}),
},
crate::terminal_session::PaneRecord {
host: None,
cwd: root_key.clone(),
name: Some(String::from("Lane: gone")),
transcript: Vec::new(),
lane: Some(crate::terminal_session::LaneRecord {
path: tmp.path().join("repo-gone").display().to_string(),
branch: String::from("agent/gone"),
agent: Some(String::from("probe")),
base: None,
}),
},
],
active: 1,
};
crate::terminal_session::save_for_root(&session, &root_key, rec).unwrap();
let mut app = App::new(repo.clone()).unwrap();
app.terminal_session_path = session;
app.agents = crate::agents::AgentTable::from_json(
r#"[{ "name": "probe", "launch": "printf '%s%s\\n' 'croft-lane' '-back-2'" }]"#,
);
app.restore_terminal_session();
assert_eq!(app.terminals.len(), 3);
let uid = app.terminals[1].uid();
assert_eq!(
app.lane_panes.get(&uid).map(|l| l.branch.as_str()),
Some("agent/fix-login")
);
assert!(
!app.lane_panes.contains_key(&app.terminals[2].uid()),
"a lane whose worktree is gone is not a lane"
);
let budget = crate::test_budget::spawn_budget(crate::test_budget::tests::TERMINAL_PROBE_BASE);
let started = std::time::Instant::now();
while started.elapsed() < budget
&& !app.terminals[1]
.visible_text()
.contains("croft-lane-back-2")
{
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert!(
app.terminals[1]
.visible_text()
.contains("croft-lane-back-2"),
"the agent was seated again; screen:\n{}",
app.terminals[1].visible_text()
);
assert!(
!app.terminals[2]
.visible_text()
.contains("croft-lane-back-2"),
"nothing was typed into the pane whose lane is gone"
);
}
#[test]
fn a_restored_lane_pane_spawns_in_its_worktree_not_where_the_shell_had_wandered() {
// The launch line is typed into the restored shell, so that shell must
// be in the lane: not in the directory the old shell had cd'd to at save
// time, and not, when that directory is gone, in the PRIMARY repo the
// cwd fallback names. The "agent" prints its cwd so the test can read
// where it was seated.
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
init_lane_repo(&repo);
let session = tmp.path().join("sessions.json");
let lane_dir = tmp.path().join("repo-fix-login");
std::fs::create_dir_all(&lane_dir).unwrap();
let elsewhere = tmp.path().join("notes");
std::fs::create_dir_all(&elsewhere).unwrap();
let vanished = lane_dir.join("scratch");
let root_key = repo.display().to_string();
let lane = |agent: &str| crate::terminal_session::LaneRecord {
path: lane_dir.display().to_string(),
branch: String::from("agent/fix-login"),
agent: Some(String::from(agent)),
base: None,
};
let rec = crate::terminal_session::SessionRecord {
panes: vec![
crate::terminal_session::PaneRecord {
host: None,
cwd: elsewhere.display().to_string(),
name: Some(String::from("Lane: fix-login")),
transcript: Vec::new(),
lane: Some(lane("probe-a")),
},
crate::terminal_session::PaneRecord {
host: None,
cwd: vanished.display().to_string(),
name: Some(String::from("Lane: fix-login")),
transcript: Vec::new(),
lane: Some(lane("probe-b")),
},
],
active: 0,
};
crate::terminal_session::save_for_root(&session, &root_key, rec).unwrap();
let mut app = App::new(repo.clone()).unwrap();
app.terminal_session_path = session;
app.agents = crate::agents::AgentTable::from_json(
r#"[
{ "name": "probe-a", "launch": "printf '%s%s\\n' 'croft-seat' \"-a:$(pwd)\"" },
{ "name": "probe-b", "launch": "printf '%s%s\\n' 'croft-seat' \"-b:$(pwd)\"" }
]"#,
);
app.restore_terminal_session();
assert_eq!(app.terminals.len(), 2);
let lane_canon = lane_dir.canonicalize().unwrap().display().to_string();
let budget = crate::test_budget::spawn_budget(crate::test_budget::tests::TERMINAL_PROBE_BASE);
let started = std::time::Instant::now();
let seated = |app: &App, tag: &str| {
app.terminals
.iter()
.any(|t| t.visible_text().contains(&format!("croft-seat-{tag}:")))
};
while started.elapsed() < budget && !(seated(&app, "a") && seated(&app, "b")) {
std::thread::sleep(std::time::Duration::from_millis(20));
}
for tag in ["a", "b"] {
let screen = app
.terminals
.iter()
.map(|t| t.visible_text())
.find(|s| s.contains(&format!("croft-seat-{tag}:")))
.unwrap_or_else(|| panic!("probe {tag} never printed its cwd"));
let line = screen
.lines()
.find(|l| l.contains(&format!("croft-seat-{tag}:")))
.unwrap();
assert!(
line.trim_end().ends_with(&lane_canon)
|| line.trim_end().ends_with(&lane_dir.display().to_string()),
"agent {tag} was seated in the lane, got: {line:?}"
);
}
for t in &app.terminals {
assert!(
app.lane_panes.contains_key(&t.uid()),
"both restored panes are the lane's"
);
}
}
#[test]
fn a_lane_pane_closed_by_any_route_is_no_longer_the_lanes_even_when_reopened() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
init_lane_repo(&repo);
let mut app = App::new(repo.clone()).unwrap();
app.terminal_session_path = tmp.path().join("sessions.json");
app.lane_agent = None;
app.create_worktree_lane("fix login");
let uid = app.terminals[app.active_terminal].uid();
assert!(app.lane_panes.contains_key(&uid));
assert!(app.close_active_terminal(), "the ordinary close");
assert!(
app.lane_panes.is_empty(),
"the map does not keep dead panes"
);
app.undo_close_terminal();
assert!(
app.terminals.iter().any(|t| t.uid() == uid),
"the pane came back"
);
assert!(
app.lane_panes.is_empty(),
"but not as the lane's: nobody asked for an agent to be re-seated"
);
}
#[test]
fn closing_a_lane_whose_pane_is_the_last_one_replaces_it_with_a_shell_in_the_primary_root() {
// The close refuses the last pane, and a lane pane left standing would
// sit in a directory git just removed. So a fresh shell in the primary
// root is opened first, and the lane pane closes like any other.
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
init_lane_repo(&repo);
let mut app = App::new(repo.clone()).unwrap();
app.terminal_session_path = tmp.path().join("sessions.json");
app.lane_agent = None;
app.create_worktree_lane("solo");
// Drop the original pane so the lane's is the only one left.
assert!(app.close_terminal_at(0));
assert_eq!(app.terminals.len(), 1);
let lane_uid = app.terminals[0].uid();
assert_eq!(app.terminals[0].manual_name(), Some("Lane: solo"));
let lane = tmp.path().join("repo-solo").canonicalize().unwrap();
app.active_scm_root = lane.clone();
app.close_worktree_lane();
assert!(!lane.exists(), "{}", app.status);
assert_eq!(app.terminals.len(), 1, "one pane remains: the replacement");
assert_ne!(app.terminals[0].uid(), lane_uid, "and it is not the lane's");
assert_eq!(app.terminals[0].manual_name(), None);
assert!(app.lane_panes.is_empty());
assert!(
app.closed_terminals
.iter()
.any(|c| c.term.uid() == lane_uid),
"the lane pane went through the undoable close"
);
assert!(app.status.contains("closed its pane"), "{}", app.status);
// The replacement is a live shell in the primary root, not in the
// removed directory: it can print its cwd.
app.terminals[0].write_input(b"printf '%s%s\\n' 'croft-repl' \"-at:$(pwd)\"\r");
let budget = crate::test_budget::spawn_budget(crate::test_budget::tests::TERMINAL_PROBE_BASE);
let started = std::time::Instant::now();
while started.elapsed() < budget && !app.terminals[0].visible_text().contains("croft-repl-at:")
{
std::thread::sleep(std::time::Duration::from_millis(20));
}
let screen = app.terminals[0].visible_text();
let line = screen
.lines()
.find(|l| l.contains("croft-repl-at:"))
.unwrap_or_else(|| panic!("the replacement shell never answered; screen:\n{screen}"));
let repo_canon = repo.canonicalize().unwrap().display().to_string();
assert!(
line.trim_end().ends_with(&repo_canon)
|| line.trim_end().ends_with(&repo.display().to_string()),
"the replacement sits in the primary root, got: {line:?}"
);
}
#[test]
fn closing_a_lane_closes_its_pane_through_the_undoable_path() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
init_lane_repo(&repo);
let mut app = App::new(repo.clone()).unwrap();
app.terminal_session_path = tmp.path().join("sessions.json");
app.lane_agent = None;
app.create_worktree_lane("fix login");
let lane = tmp.path().join("repo-fix-login").canonicalize().unwrap();
assert_eq!(app.terminals.len(), 2);
let lane_uid = app.terminals[app.active_terminal].uid();
// Close targets the ACTIVE root; the lane is what the user is in.
app.active_scm_root = lane.clone();
app.close_worktree_lane();
assert!(!lane.exists(), "the worktree is gone: {}", app.status);
assert!(!app.roots.iter().any(|r| r == lane), "and the root");
assert_eq!(
app.terminals.len(),
1,
"and the lane's pane: {}",
app.status
);
assert!(!app.terminals.iter().any(|t| t.uid() == lane_uid));
assert!(app.lane_panes.is_empty());
assert!(
app.closed_terminals
.iter()
.any(|c| c.term.uid() == lane_uid),
"closed through the undoable path"
);
assert!(app.status.contains("closed its pane"), "{}", app.status);
}
#[test]
fn cmd_k_shift_l_asks_for_a_new_lane_and_plain_l_still_folds() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('L'), KeyModifiers::SHIFT)));
assert_eq!(
app.input_prompt.as_ref().map(|p| p.purpose.clone()),
Some(crate::widgets::input_prompt::InputPurpose::NewWorktreeLane)
);
app.close_input_prompt();
// CSI-u hosts report Shift+L as a lower-case char with SHIFT.
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('l'), KeyModifiers::SHIFT)));
assert_eq!(
app.input_prompt.as_ref().map(|p| p.purpose.clone()),
Some(crate::widgets::input_prompt::InputPurpose::NewWorktreeLane)
);
app.close_input_prompt();
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('l'), KeyModifiers::NONE)));
assert!(
app.input_prompt.is_none(),
"plain L is still the fold toggle"
);
}
#[test]
fn a_lanes_root_row_wears_its_branch_and_its_agent() {
// The badge text in its three shapes, then the app-side sync: a lane's
// root gets a badge keyed by its canonical path, a plain-shell lane shows
// the branch alone, and a closed lane's badge goes with it.
use crate::agents::{AgentLane, AgentStatus};
let seated = AgentLane {
name: String::from("claude"),
status: AgentStatus::Waiting,
};
assert_eq!(
lane_root_badge("agent/fix-login", Some(&seated), Some("claude")),
"agent/fix-login \u{b7} \u{25c6} claude \u{25d0}"
);
assert_eq!(
lane_root_badge("agent/fix-login", None, Some("claude")),
"agent/fix-login \u{b7} claude",
"configured but not yet seated: the bare name"
);
assert_eq!(lane_root_badge("agent/docs", None, None), "agent/docs");
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
init_lane_repo(&repo);
let mut app = App::new(repo.clone()).unwrap();
app.terminal_session_path = tmp.path().join("sessions.json");
app.lane_agent = None;
app.create_worktree_lane("docs");
app.sync_lane_root_badges();
let lane = tmp.path().join("repo-docs").canonicalize().unwrap();
assert_eq!(
app.tree.root_badges.get(&lane).map(String::as_str),
Some("agent/docs"),
"{:?}",
app.tree.root_badges
);
assert!(
!app.tree.root_badges.contains_key(app.roots.primary()),
"the primary is not a lane"
);
app.active_scm_root = lane.clone();
app.close_worktree_lane();
app.sync_lane_root_badges();
assert!(
app.tree.root_badges.is_empty(),
"the badge went with the lane"
);
}
#[test]
fn a_lanes_badge_follows_the_seat_and_a_seated_pane_outranks_a_plain_one() {
// App-side: the configured name shows until the sampler seats the
// agent, the seated badge replaces it, and it falls back when the agent
// leaves. With two panes on one lane, the seated one decides whichever
// uid order the map walks.
use crate::agents::{AgentLane, AgentStatus};
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
init_lane_repo(&repo);
let mut app = App::new(repo.clone()).unwrap();
app.terminal_session_path = tmp.path().join("sessions.json");
// A table of the test's own, not this machine's agents.json: claude
// needs a launch line for the lane to record the agent, and that line
// must not start the real thing in the test's shell.
app.agents =
crate::agents::AgentTable::from_json(r#"[{ "name": "claude", "launch": "true" }]"#);
app.lane_agent = Some(String::from("claude"));
app.create_worktree_lane("fix login");
let lane = tmp.path().join("repo-fix-login").canonicalize().unwrap();
let idx = app.active_terminal;
app.sync_lane_root_badges();
assert_eq!(
app.tree.root_badges.get(&lane).map(String::as_str),
Some("agent/fix-login \u{b7} claude"),
"configured, not yet seated"
);
app.terminals[idx].set_agent(Some(AgentLane {
name: String::from("claude"),
status: AgentStatus::Working,
}));
app.sync_lane_root_badges();
assert_eq!(
app.tree.root_badges.get(&lane).map(String::as_str),
Some("agent/fix-login \u{b7} \u{25c6} claude \u{25cf}"),
"seated"
);
// A second pane on the same lane with a HIGHER uid, so the map walks the
// first pane before it. Seated-first-then-plain and plain-first-then-
// seated must both end on the seated badge.
let plain = crate::widgets::terminal::PtyTerminal::new(&lane).unwrap();
let second_uid = plain.uid();
assert!(app.terminals[idx].uid() < second_uid);
app.lane_panes.insert(
second_uid,
crate::terminal_session::LaneRecord {
path: lane.display().to_string(),
branch: String::from("agent/fix-login"),
agent: None,
base: None,
},
);
app.terminals.push(plain);
let last = app.terminals.len() - 1;
app.sync_lane_root_badges();
assert_eq!(
app.tree.root_badges.get(&lane).map(String::as_str),
Some("agent/fix-login \u{b7} \u{25c6} claude \u{25cf}"),
"seated first, plain second: the plain sibling does not hide it"
);
app.terminals[idx].set_agent(None);
app.terminals[last].set_agent(Some(AgentLane {
name: String::from("claude"),
status: AgentStatus::Idle,
}));
app.sync_lane_root_badges();
assert_eq!(
app.tree.root_badges.get(&lane).map(String::as_str),
Some("agent/fix-login \u{b7} \u{25c6} claude \u{25cb}"),
"plain first, seated second: the seated pane still decides"
);
app.terminals[last].set_agent(None);
app.sync_lane_root_badges();
assert_eq!(
app.tree.root_badges.get(&lane).map(String::as_str),
Some("agent/fix-login \u{b7} claude"),
"back to the configured name once nobody is seated"
);
}
#[test]
fn the_review_queue_names_the_lane_each_agents_files_are_in() {
// #348: with a worktree lane in the workspace the queue groups by root,
// naming a lane by its BRANCH and any other root by its display label,
// so two files of the same basename are told apart.
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
init_lane_repo(&repo);
let mut app = App::new(repo.clone()).unwrap();
app.terminal_session_path = tmp.path().join("sessions.json");
app.lane_agent = None;
app.create_worktree_lane("fix login");
let repo = app.roots.primary().to_path_buf();
let lane = tmp.path().join("repo-fix-login").canonicalize().unwrap();
let working = vec![String::from("claude")];
app.agent_ledger
.record_write(&repo.join("src/mod.rs"), 1, &working);
app.agent_ledger
.record_write(&lane.join("src/mod.rs"), 2, &working);
app.agent_ledger
.record_write(&lane.join("src/other.rs"), 3, &working);
let rows = app.agent_lane_rows();
assert_eq!(rows.len(), 1, "one row per agent: {rows:?}");
let row = &rows[0];
assert!(row.starts_with("claude: 3 to review \u{2014} "), "{row}");
let repo_label = repo
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap();
assert!(
row.contains(&format!("{repo_label} 1")),
"the primary root is named by its folder: {row}"
);
assert!(
row.contains("agent/fix-login 2"),
"the lane is named by its branch: {row}"
);
assert!(
!row.contains("mod.rs"),
"a grouped row carries labels and counts, not file names, so the \
status bar cannot elide the labels away: {row}"
);
assert!(
row.find(&repo_label) < row.find("agent/fix-login"),
"root order, primary first: {row}"
);
// A file outside every root still appears, under its own heading. Only
// reachable defensively: the ledger's one production feeder drops paths
// under no root before recording them.
app.agent_ledger
.record_write(&tmp.path().join("stray.rs"), 4, &working);
let row = app.agent_lane_rows().remove(0);
assert!(
row.contains("outside the workspace 1"),
"an unowned file is counted, not dropped: {row}"
);
}
#[test]
fn two_lanes_sharing_a_branch_are_named_by_their_folders_instead() {
// A lane's branch comes from its slug alone, so lanes cut from two
// different repos can carry the same one. Naming both groups
// `agent/fix` would be worse than naming neither: the fallback is the
// disambiguated root label the workspace already computes.
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
init_lane_repo(&repo);
let mut app = App::new(repo.clone()).unwrap();
app.terminal_session_path = tmp.path().join("sessions.json");
let one = tmp.path().join("one-fix");
let two = tmp.path().join("two-fix");
for dir in [&one, &two] {
std::fs::create_dir_all(dir).unwrap();
app.add_workspace_folder(dir.clone());
}
let (one, two) = (one.canonicalize().unwrap(), two.canonicalize().unwrap());
// Two panes, two lanes, one branch name between them.
for (i, dir) in [(0u64, &one), (1, &two)] {
app.lane_panes.insert(
1000 + i,
crate::terminal_session::LaneRecord {
path: dir.display().to_string(),
branch: String::from("agent/fix"),
agent: None,
base: None,
},
);
}
let working = vec![String::from("claude")];
app.agent_ledger
.record_write(&one.join("a.rs"), 1, &working);
app.agent_ledger
.record_write(&two.join("b.rs"), 2, &working);
let row = app.agent_lane_rows().remove(0);
assert!(
!row.contains("agent/fix"),
"a branch shared by two groups names neither: {row}"
);
assert!(
row.contains("one-fix 1") && row.contains("two-fix 1"),
"both groups fall back to their folder labels: {row}"
);
// One lane alone: the branch is unique again, so it names its group.
app.lane_panes.remove(&1001);
let row = app.agent_lane_rows().remove(0);
assert!(
row.contains("agent/fix 1"),
"a unique branch still names its lane: {row}"
);
}
#[test]
fn a_grouped_review_queue_row_survives_the_status_bar() {
// The bar is one row and elides the MIDDLE (`elide_middle`), so a row
// long enough to be cut loses its group labels — the one thing grouping
// adds. Labels and counts keep it short enough to land whole. Same
// shape as `status_transient_keeps_its_tail_when_longer_than_the_bar`.
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
init_lane_repo(&repo);
let mut app = App::new(repo.clone()).unwrap();
app.terminal_session_path = tmp.path().join("sessions.json");
app.lane_agent = None;
app.create_worktree_lane("fix login");
let repo = app.roots.primary().to_path_buf();
let lane = tmp.path().join("repo-fix-login").canonicalize().unwrap();
let working = vec![String::from("claude")];
for i in 0..4 {
app.agent_ledger
.record_write(&repo.join(format!("src/r{i}.rs")), i as u64, &working);
app.agent_ledger
.record_write(&lane.join(format!("src/l{i}.rs")), 100 + i as u64, &working);
}
app.run_command(crate::widgets::command_palette::Command::ShowAgentLane);
let backend = ratatui::backend::TestBackend::new(120, 40);
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 last_row: String = (a.x..a.x + a.width)
.map(|x| buf[(x, a.y + a.height - 1)].symbol().to_string())
.collect();
assert!(
last_row.contains("agent/fix-login 4"),
"the lane's group must reach the bar unelided: {last_row:?}"
);
assert!(
last_row.contains("Ln 1, Col 1"),
"the right cluster must still paint: {last_row:?}"
);
}
#[test]
fn a_single_root_review_queue_reads_as_it_always_did() {
// Grouping is for workspaces with more than one root: with one, the
// label would name the only place the files could be and the group
// count would repeat the total, so the row keeps its old flat shape.
// A truncated sample says so, and an empty queue has no dangling tail.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let working = vec![String::from("claude")];
app.agent_ledger
.record_write(&tmp.path().join("a.rs"), 1, &working);
app.agent_ledger
.record_write(&tmp.path().join("b.rs"), 2, &working);
assert_eq!(
app.agent_lane_rows(),
vec![String::from("claude: 2 to review (b.rs, a.rs)")],
"the pre-grouping shape, unchanged"
);
for i in 0..3 {
app.agent_ledger.record_write(
&tmp.path().join(format!("f{i}.rs")),
10 + i as u64,
&working,
);
}
let row = app.agent_lane_rows().remove(0);
assert_eq!(
row, "claude: 5 to review (f2.rs, f1.rs, f0.rs, \u{2026})",
"a sample of three says it is a sample"
);
// Nothing unreviewed: no trailing separator, no empty group.
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f = tmp.path().join("z.rs");
std::fs::write(&f, "x").unwrap();
app.agent_ledger.record_write(&f, 1, &working);
let hash = app.agent_ledger.lane("claude")[0].current_hash;
app.agent_ledger.mark_reviewed("claude", &f, hash, None);
assert_eq!(
app.agent_lane_rows(),
vec![String::from("claude: 0 to review ()")],
"an emptied lane keeps the old shape too"
);
}
/// Stand up a `croft view` listener on `app` without touching process env.
///
/// The real `bind_view_socket` also exports `CROFT_VIEW_SOCK`, which is
/// process-global: setting it in one test would publish a socket into every
/// other test running in the same process. This binds the same way and
/// publishes nothing, so the server half is exercised and the neighbours are
/// left alone.
fn seat_view_listener(app: &mut App, dir: &std::path::Path) -> std::path::PathBuf {
let sock = dir.join("view-test.sock");
// Deliberately the production helper: seating a hand-built listener here
// would let `prepare_view_listener` lose its non-blocking mode without a
// single test noticing.
let listener = crate::app::prepare_view_listener(&sock).unwrap();
app.view_listener = Some(listener);
sock
}
/// Accept one client from a NON-blocking listener, waiting for it (#362).
///
/// `prepare_view_listener` makes the listener non-blocking on purpose, so a
/// single `accept()` after a fixed sleep asserts that the client thread was
/// scheduled inside that window - a property of machine load rather than of
/// the code under test. When it loses, the panic names the client rather than
/// the deadline, the blocking flag or the length cap the test is about.
fn accept_when_ready(
listener: &std::os::unix::net::UnixListener,
) -> std::os::unix::net::UnixStream {
// Load-scaled rather than a fresh constant (CONTRIBUTING.md, "Waiting on
// a spawned process in a test"). What blows a flat five seconds here is
// not the accept: it is every other test in the suite spawning a shell at
// the same moment, which is contention no constant chosen inside this
// test can know about.
let budget = crate::test_budget::spawn_budget(crate::test_budget::tests::VIEW_ACCEPT_BASE);
let started = std::time::Instant::now();
loop {
match listener.accept() {
Ok((stream, _)) => return stream,
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
assert!(
started.elapsed() < budget,
"no client connected within {budget:?}"
);
std::thread::sleep(std::time::Duration::from_millis(5));
}
Err(e) => panic!("accept failed: {e}"),
}
}
}
/// Send one request from a client thread and hand back its reply.
fn view_from_a_pane(
sock: &std::path::Path,
path: &std::path::Path,
) -> std::thread::JoinHandle<crate::view_ipc::ViewReply> {
let sock = sock.to_path_buf();
let path = path.to_path_buf();
std::thread::spawn(move || {
crate::view_ipc::send(&sock, &crate::view_ipc::ViewRequest::new(&path)).unwrap()
})
}
/// Drain until the request lands: the client connects on another thread, so
/// the first non-blocking accept can legitimately find nothing yet.
///
/// The budget is the shared load-scaled one rather than a fixed two seconds
/// (CONTRIBUTING.md, "Waiting on a spawned process in a test"): `App::new`
/// has already spawned a PTY shell, a git worker and an FS watcher, and the
/// client is a thread racing all of them. Panics rather than returning false,
/// so a caller cannot turn a timeout into a bare `assert!` that says nothing
/// about which of the two happened.
fn drain_until_answered(
app: &mut App,
client: &std::thread::JoinHandle<crate::view_ipc::ViewReply>,
) {
crate::test_budget::await_spawned(
crate::test_budget::tests::VIEW_DRAIN_BASE,
"the view request to be answered",
|| {
app.drain_view_requests();
client.is_finished()
},
);
}
#[test]
fn a_view_request_from_a_pane_opens_the_file_in_the_editor() {
// #362: the point of the whole channel. A shell prompt asks, and the file
// arrives as an editor tab exactly as an Explorer click would leave it.
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_view_request_for_a_directory_is_refused_with_a_reason_the_client_prints() {
// The server knows why; the client only relays. A silent refusal would
// exit the user's shell 0 having opened nothing.
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("subdir");
std::fs::create_dir(&dir).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let sock = seat_view_listener(&mut app, tmp.path());
let client = view_from_a_pane(&sock, &dir);
// Load-scaled, and it still cannot hang: `await_spawned` panics naming
// what it waited for, so the `join` below is only reached once the client
// thread has finished (CONTRIBUTING.md, "Waiting on a spawned process in
// a test"). A fixed two seconds decided pass or fail here before.
drain_until_answered(&mut app, &client);
match client.join().unwrap() {
crate::view_ipc::ViewReply::Err { message } => {
assert!(
message.contains("is a directory"),
"the reason must name what went wrong, got {message:?}"
);
}
other => panic!("a directory must not open as a file: {other:?}"),
}
}
#[test]
fn draining_an_idle_listener_reports_no_change_and_does_not_block() {
// Polled from the frame loop: a blocking accept here would freeze every
// redraw until somebody happened to run `croft view`.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
seat_view_listener(&mut app, tmp.path());
// Asserted on the fd rather than only on elapsed time: if the mode is
// lost, `accept` blocks forever and a timing assertion is never reached,
// so the test would HANG instead of failing and read as a CI timeout
// rather than as this defect. Reading O_NONBLOCK turns that into a
// one-line failure that names the cause.
let flags = {
use std::os::unix::io::AsRawFd;
let listener = app.view_listener.as_ref().unwrap();
unsafe { libc::fcntl(listener.as_raw_fd(), libc::F_GETFL) }
};
assert!(
flags != -1 && flags & libc::O_NONBLOCK != 0,
"the frame loop polls this listener, so it must be non-blocking"
);
let started = std::time::Instant::now();
assert!(!app.drain_view_requests(), "nothing was sent");
assert!(
started.elapsed() < std::time::Duration::from_millis(500),
"the drain blocked for {:?}",
started.elapsed()
);
}
#[test]
fn the_socket_sweep_removes_a_dead_crofts_file_and_spares_a_live_one() {
// Sockets are not auto-unlinked, so a crashed croft leaves its file for
// the next one to clear. Getting this wrong in the other direction would
// be worse than litter: deleting a LIVE croft's socket silently breaks
// `croft view` in every pane it owns.
let tmp = tempfile::tempdir().unwrap();
// A pid that has certainly exited: spawn, reap, and its number is free.
let dead = {
let mut child = std::process::Command::new("true").spawn().unwrap();
let pid = child.id();
child.wait().unwrap();
pid
};
// A live pid that is NOT this process. Naming the live socket for
// `process::id()` made this half unfalsifiable: production reads
// `pid != me && kill(pid, 0) != 0`, so for our own pid the first term
// decides it and the liveness probe never runs. Measured - replacing the
// whole condition with `pid != me` left all three assertions passing,
// while production would then unlink the socket of every OTHER running
// croft, which is the outcome the comment above calls worse than litter.
let mut peer = std::process::Command::new("sleep")
.arg("30")
.spawn()
.unwrap();
let live = peer.id();
// `view-<pid>-<nonce>.sock` is the ONLY shape production writes now, so
// the fixture uses it. The pre-nonce spelling is kept for the dead pid as
// well, because the sweep still has to clear what an older croft left.
let dead_sock = tmp.path().join(format!("view-{dead}.sock"));
let dead_nonce_sock = tmp.path().join(format!("view-{dead}-a1b2c3d4.sock"));
let live_sock = tmp.path().join(format!("view-{live}-e5f6a7b8.sock"));
let stranger = tmp.path().join("not-a-view-socket");
// The lock `bind_socket_0600` writes beside each socket, which the sweep
// is supposed to take with it.
let dead_lock = tmp.path().join(format!("view-{dead}-a1b2c3d4.bind.lock"));
let live_lock = tmp.path().join(format!("view-{live}-e5f6a7b8.bind.lock"));
// A lock whose socket NEVER APPEARED: a croft that died between the
// lock's creation and the rename leaves this, and nothing keyed on the
// `.sock` suffix can ever reach it.
let orphan_lock = tmp.path().join(format!("view-{dead}-99887766.bind.lock"));
// `bind_socket_0600` binds inside `.s<pid>-<n>` and removes it on both
// paths; a croft killed inside that window strands one, and nothing else
// ever looks at it again.
let dead_stage = tmp.path().join(format!(".s{dead}-0"));
let live_stage = tmp.path().join(format!(".s{live}-0"));
// Same prefix, no counter: not ours, so the sweep must leave it.
let stage_lookalike = tmp.path().join(format!(".s{dead}-notanumber"));
for d in [&dead_stage, &live_stage, &stage_lookalike] {
std::fs::create_dir(d).unwrap();
std::fs::write(d.join("s"), b"").unwrap();
}
for p in [
&dead_sock,
&dead_nonce_sock,
&live_sock,
&stranger,
&dead_lock,
&live_lock,
&orphan_lock,
] {
std::fs::write(p, b"").unwrap();
}
crate::app::sweep_dead_view_sockets(tmp.path());
let live_survived = live_sock.exists();
let live_lock_survived = live_lock.exists();
let live_stage_survived = live_stage.exists();
let _ = peer.kill();
let _ = peer.wait();
assert!(!dead_sock.exists(), "a dead croft's socket must be cleared");
assert!(
!dead_nonce_sock.exists(),
"and the nonce-shaped name, which is the only one production writes"
);
assert!(
!dead_lock.exists(),
"the lock beside a dead croft's socket goes with it"
);
assert!(
!orphan_lock.exists(),
"a lock whose socket never appeared must be swept too, or it leaks \
forever: nothing else in croft ever looks at it again"
);
assert!(
live_survived,
"another croft is alive, so its socket must survive the sweep"
);
assert!(
live_lock_survived,
"and so must its lock: removing it lets a second croft bind the \
socket this one is serving"
);
assert!(
!dead_stage.exists(),
"a dead croft's bind staging directory leaks forever otherwise: \
nothing but this sweep ever reads that name again"
);
assert!(
live_stage_survived,
"and a LIVE croft's staging directory must survive: removing one \
mid-bind takes the socket it is about to rename out with it"
);
assert!(
stage_lookalike.exists(),
"the counter must parse as a number, or the sweep is matching on a \
prefix and will eat directories it did not create"
);
assert!(
stranger.exists(),
"the sweep must only touch files it recognises by name"
);
}
/// One drain serves EVERY client waiting, not just the first (#362).
///
/// `drain_view_requests` loops on accept under a shared 20ms deadline
/// precisely so a frame that finds three `croft view` calls queued answers
/// all three. Nothing pinned that: every other fixture hands it exactly one
/// connection, so replacing the loop body's tail with `return changed` after
/// the first client passes the whole suite.
///
/// Both requests are written SYNCHRONOUSLY from this thread before the drain
/// runs, so "both were pending in the same frame" is a property of the
/// fixture rather than of the scheduler.
#[test]
fn one_drain_answers_every_client_already_waiting() {
use std::io::{BufRead, Write};
let tmp = tempfile::tempdir().unwrap();
let first = tmp.path().join("first.txt");
let second = tmp.path().join("second.txt");
std::fs::write(&first, "one").unwrap();
std::fs::write(&second, "two").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Production's 20ms is shorter than one file open under a loaded full
// suite, and then the drain rightly defers client 1 to the next frame.
// Stretched, a drain that stops after the first client still fails.
app.view_drain_budget =
crate::test_budget::spawn_budget(crate::test_budget::tests::VIEW_DRAIN_BASE);
let sock = seat_view_listener(&mut app, tmp.path());
let mut clients = Vec::new();
for target in [&first, &second] {
let mut c = std::os::unix::net::UnixStream::connect(&sock).unwrap();
// A read timeout, so losing FAILS rather than hangs: a drain that
// serves only client 0 still passes the assert below, because
// something opened, and an untimed `read_line` on client 1 would then
// block forever. That is a CI timeout with no message, which two
// other tests in this file go out of their way to avoid.
c.set_read_timeout(Some(crate::test_budget::spawn_budget(
crate::test_budget::tests::VIEW_DRAIN_BASE,
)))
.unwrap();
// Through `ViewRequest::new`, so a change to the byte encoding is
// exercised here rather than bypassed by hand-rolling the field.
let req = crate::view_ipc::ViewRequest::new(target);
let mut line = serde_json::to_string(&req).unwrap();
line.push('\n');
c.write_all(line.as_bytes()).unwrap();
c.flush().unwrap();
clients.push(c);
}
assert!(
app.drain_view_requests(),
"one drain, with two complete requests already on the socket"
);
for (i, c) in clients.iter().enumerate() {
let mut reply = String::new();
std::io::BufReader::new(c)
.read_line(&mut reply)
.unwrap_or_else(|e| {
panic!(
"client {i} was never answered ({e}): one drain must serve \
every client already waiting, not just the first"
)
});
let reply: crate::view_ipc::ViewReply = serde_json::from_str(reply.trim())
.unwrap_or_else(|e| panic!("client {i} got no parseable reply: {e}"));
assert_eq!(
reply,
crate::view_ipc::ViewReply::Ok,
"client {i} must be answered by the SAME drain as client 0: a loop \
that serves one connection and returns leaves this one waiting a \
whole frame, and every other test hands the drain a single client"
);
}
let open: Vec<_> = app
.editor
.editors
.iter()
.filter_map(|e| e.path.clone())
.collect();
assert!(
open.contains(&first) && open.contains(&second),
"both files must be open, got {open:?}"
);
}
/// A relative path is refused rather than resolved against croft's cwd (#362).
///
/// `view_ipc`'s header states that the server only ever sees absolute paths,
/// because the client resolves against ITS cwd before sending. Nothing
/// enforced it, so a relative path from anything that is not `croft view`
/// opened whatever that name meant from croft's own working directory, which
/// is a different file than the sender named. Same-uid, so this is an
/// invariant rather than a boundary, but an unchecked invariant is a comment.
#[test]
fn a_relative_path_in_a_request_is_refused_rather_than_resolved_here() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let reply = app.apply_view_request(std::path::Path::new("relative.txt"));
match reply {
crate::view_ipc::ViewReply::Err { message } => assert!(
message.contains("absolute"),
"the refusal must name the invariant it is enforcing, got {message:?}"
),
other => panic!("a relative path must not be resolved here: {other:?}"),
}
}
/// The status arm that no test could reach (#362).
///
/// `bind_view_socket` returns early under `cfg(test)` so a test cannot leave
/// a live socket in the real cache dir, which also means nothing in the suite
/// ever latches `VIEW_BIND_ERROR`: the arm that tells the user their bind
/// failed had never once run. `view_status` is the pure half, split out so it
/// can. Short-circuit it to always answer "Ready" and this goes red.
#[test]
fn a_failed_view_bind_reaches_the_status_line_with_its_cause() {
assert_eq!(
crate::app::view_status(None),
"Ready",
"a croft whose bind succeeded says nothing about it"
);
let said = crate::app::view_status(Some("Permission denied (os error 13)"));
assert!(
said.contains("croft view"),
"the message must name the feature that is off, or the user cannot \
connect it to the command that fails: {said:?}"
);
assert!(
said.contains("Permission denied (os error 13)"),
"and it must carry the CAUSE: a bare 'unavailable' sends the user \
looking in the wrong place, which is what the latch exists to \
prevent: {said:?}"
);
}
// --- #362 fallback-review blocker: the startup pane's environment ----------
#[test]
fn a_pane_command_carries_the_view_socket_when_one_is_bound() {
// The blocker this replaces: the socket was published with `set_var`
// AFTER `App::new` had already built the first pane, and portable-pty
// snapshots `std::env::vars_os()` inside `CommandBuilder::new` and then
// clears the child's environment before applying only that snapshot. So
// `croft view` failed in the startup pane and worked in every pane opened
// later. No test could see it: `bind_view_socket` returns early under
// `cfg!(test)` and the server-side helper seats a listener by hand, so
// nothing exercised the publish path at all.
//
// Passing the path IN keeps this pure: a process-global set once inside
// one test would leak into every other test in the binary.
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:?}"
);
// Presence half over the same state: the terminal identity still travels,
// so this cannot pass by the env application having been removed.
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() {
// A croft launched FROM a croft pane inherits the outer croft's
// `CROFT_VIEW_SOCK` through `CommandBuilder::new`, which seeds itself from
// `std::env::vars_os()`. If the inner croft's own bind fails, adding
// nothing is not the same as clearing: its panes keep the PARENT's socket,
// and `croft view report.pdf` opens the file in the wrong window and exits
// 0. The field doc promises the opposite ("panes then see no
// CROFT_VIEW_SOCK and the client says so plainly").
//
// Asserted through `iter_full_env_as_str`, which is what the CHILD
// receives. The sibling test below reads `iter_extra_env_as_str`, which
// filters out every inherited entry and is therefore structurally blind to
// this: it can only ever prove nothing was ADDED.
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:?}"
);
// Presence half over the same view: the terminal identity still reaches
// the child, so this cannot pass by the whole env having been dropped.
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() {
// A croft that failed to bind must not hand its panes a stale or empty
// path: `croft view` then says the socket is unset, which is true and
// actionable, rather than failing to connect to a name that is not there.
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_client_that_never_sends_a_newline_is_refused_by_the_deadline() {
// The socket's read timeout does NOT bound `read_request` on its own:
// SO_RCVTIMEO applies per `recv`, while the read loops until it sees a
// newline. A client writing inside every window re-arms it forever, and
// the drain runs on the frame loop, so that freezes the editor.
//
// Asserted on the REPLY, not on elapsed time. The wall-clock version of
// this test was load-sensitive to the point of being a flake in waiting:
// measured, the fixed path took 20-90ms and the broken path 147-495ms, so
// the two bands nearly touch and any threshold between them is a coin
// toss on a busy machine. The deadline path produces a message no other
// path produces, which is load-independent and says WHICH bound fired.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let sock = seat_view_listener(&mut app, tmp.path());
let sock2 = sock.clone();
// The dribbler stops when the SERVER is done with it, not after a fixed
// count. It used to run 240 x 5ms, a flat 1.2s, while the accept it races
// is load-scaled to as much as sixteen seconds: on a machine slow enough
// to need that budget the dribbler had already exited, the server read
// EOF on `{"path":[47,47`, and the test failed on a serde parse error
// while asserting about a deadline. That is the same class this fixture
// was converted to tolerate, left in the fixture instead of the budget.
let served = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let dribbling = std::sync::Arc::clone(&served);
let dribbler = std::thread::spawn(move || {
let Ok(mut c) = std::os::unix::net::UnixStream::connect(&sock2) else {
return;
};
// Continuously, and INSIDE the budget. Writing once and going quiet
// does not reproduce the defect: the per-read timeout fires and the
// drain moves on, so a fixture shaped that way passes against the
// unbounded read too. The hang needs a client that keeps re-arming.
let _ = std::io::Write::write_all(&mut c, br#"{"path":[47"#);
let _ = std::io::Write::flush(&mut c);
while !dribbling.load(std::sync::atomic::Ordering::Relaxed) {
std::thread::sleep(std::time::Duration::from_millis(5));
if std::io::Write::write_all(&mut c, b",47").is_err() {
return;
}
let _ = std::io::Write::flush(&mut c);
}
});
let listener = app.view_listener.as_ref().unwrap();
let stream = accept_when_ready(listener);
let deadline = std::time::Instant::now() + std::time::Duration::from_millis(20);
let (reply, opened) = app.answer_view_client(stream, deadline);
served.store(true, std::sync::atomic::Ordering::Relaxed);
let _ = dribbler.join();
assert!(
!opened,
"nothing was ever named, so nothing can have opened"
);
match reply {
crate::view_ipc::ViewReply::Err { message } => assert!(
message.contains("did not arrive within the frame budget"),
"the DEADLINE must be what refuses this client. Any other error \
means some incidental bound fired instead and the deadline is \
still unenforced: {message}"
),
other => panic!("a request with no newline cannot succeed: {other:?}"),
}
}
#[test]
fn a_non_blocking_accepted_stream_is_still_answered() {
// The PREVIOUS version of this test could not fail: it accepted a
// connection, called `set_nonblocking(false)` itself, and then asserted
// the flag it had just set. Deleting the production call left it green on
// every platform, and its own comment claimed the opposite.
//
// The version after that could not fail either, for a NEW reason, and the
// fix that broke it was in the same round: `read_line_by_deadline` now
// swallows `WouldBlock`/`TimedOut` and loops, precisely so a per-recv
// errno cannot end a read early. A non-blocking stream therefore busy
// spins until the bytes arrive and the reply is `Ok` either way, so
// asserting the reply says nothing about the flag. Measured: with
// `set_nonblocking(false)` deleted from production, that version passed.
//
// The flag itself is the claim, so the flag is what this asserts. The
// probe is a DUP rather than a second connection: a dup shares the open
// file description, so it reads back the same `O_NONBLOCK` the server
// cleared on the original. The reply assertion stays alongside it, since
// a cleared flag on an unanswered request would not be a pass either.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let sock = seat_view_listener(&mut app, tmp.path());
let target = tmp.path().join("seen.txt");
std::fs::write(&target, b"hello").unwrap();
let sock2 = sock.clone();
let target2 = target.clone();
let client = std::thread::spawn(move || {
let mut c = std::os::unix::net::UnixStream::connect(&sock2).unwrap();
// Connect, PAUSE, then write. The pause is what makes the blocking
// mode observable at all: a client that writes before the server
// accepts leaves the bytes sitting in the socket buffer, so the first
// read succeeds immediately whether the socket blocks or not, and the
// test passes with the flag cleared or set. The read has to WAIT for
// the mode to matter, which is exactly the case a real `croft view`
// hits whenever the shell is a little slower than the frame loop.
std::thread::sleep(std::time::Duration::from_millis(120));
// `ViewRequest::new` rather than the field by hand, so the byte
// encoding is exercised rather than reimplemented beside it.
let req = crate::view_ipc::ViewRequest::new(&target2);
let mut line = serde_json::to_string(&req).unwrap();
line.push('\n');
let _ = std::io::Write::write_all(&mut c, line.as_bytes());
let _ = std::io::Write::flush(&mut c);
std::thread::sleep(std::time::Duration::from_millis(300));
});
// Long enough for the CONNECT to land, short enough that the request has
// not been written yet.
std::thread::sleep(std::time::Duration::from_millis(30));
let listener = app.view_listener.as_ref().unwrap();
let stream = accept_when_ready(listener);
// The state macOS hands production, forced here so Linux exercises it too.
stream.set_nonblocking(true).unwrap();
let probe = stream.try_clone().expect("a dup of the accepted stream");
// The client thread sleeps before it writes, so this deadline is racing a
// scheduler, not the server. Load-scaled for the same reason every other
// spawn wait here is (CONTRIBUTING.md).
let deadline = std::time::Instant::now()
+ crate::test_budget::spawn_budget(crate::test_budget::tests::VIEW_SERVER_DEADLINE_BASE);
let (reply, opened) = app.answer_view_client(stream, deadline);
let _ = client.join();
let flags = unsafe { libc::fcntl(std::os::fd::AsRawFd::as_raw_fd(&probe), libc::F_GETFL) };
assert!(
flags >= 0,
"F_GETFL on the dup failed: {}",
std::io::Error::last_os_error()
);
assert_eq!(
flags & libc::O_NONBLOCK,
0,
"production must clear O_NONBLOCK on an accepted stream: macOS inherits \
the listener's flags across accept, and a non-blocking read there \
returns before the client has written"
);
assert_eq!(
reply,
crate::view_ipc::ViewReply::Ok,
"and the request is still answered: a cleared flag with no reply \
behind it would not be a pass"
);
assert!(opened, "and the file must actually have been opened");
}
#[test]
fn the_sweep_spares_staged_stdin_a_croft_may_still_be_showing() {
// The previous version of this test modelled the "live" file as
// `stdin-{own_pid}-0.csv` and passed. Production never produces that name:
// `stage_stdin` runs inside `view_ipc::run`, the short-lived `croft view`
// CLIENT, which exits milliseconds later. So every staged file carries a
// pid that is dead by construction, the pid-liveness sweep matched all of
// them, and launching a second croft deleted a file the first one had open
// in a tab. `sqlite_view::table_page` re-opens by path on every page turn,
// so that breaks the tab rather than merely littering.
//
// Staged through the real function, so the name is the shape production
// makes rather than the shape the old fixture assumed.
let tmp = tempfile::tempdir().unwrap();
let fresh = crate::view_ipc::stage_stdin(tmp.path(), b"a,b\n1,2\n", None).unwrap();
assert!(fresh.exists(), "precondition: the pipe was staged");
crate::app::sweep_dead_view_sockets(tmp.path());
assert!(
fresh.exists(),
"a just-staged pipe must survive: a pane may be showing it right now"
);
}
/// A staged pipe a LIVE croft holds survives the sweep at any age (#362).
///
/// Age alone was the whole rule, and age alone deletes a file that is open in
/// a tab as soon as the session outlives the window. That is not litter:
/// `sqlite_view::table_page` re-opens by path on every page turn, so the tab
/// breaks, and `vault read ... | croft view -` cannot be produced again by
/// re-running anything. The server stamps its pid in at open time and this
/// asserts the sweep honours it.
///
/// Both files here are twice the retention age, so age cannot be what
/// separates them: only the holder's liveness can.
#[test]
fn the_staging_sweep_spares_a_pipe_a_live_croft_still_holds() {
let tmp = tempfile::tempdir().unwrap();
let staged = tmp.path().join("view-stdin");
std::fs::create_dir_all(&staged).unwrap();
// A live pid that is NOT this process, so `holder == process::id()` in
// production cannot be what spares it and the liveness probe has to run.
let mut peer = std::process::Command::new("sleep")
.arg("30")
.spawn()
.unwrap();
let live = peer.id();
let dead = {
let mut child = std::process::Command::new("true").spawn().unwrap();
let pid = child.id();
child.wait().unwrap();
pid
};
let held_live = staged.join(format!("held-{live}-stdin-999999-0.csv"));
let held_dead = staged.join(format!("held-{dead}-stdin-999999-1.csv"));
let unclaimed = staged.join("stdin-999999-2.csv");
for p in [&held_live, &held_dead, &unclaimed] {
std::fs::write(p, b"a,b\n1,2\n").unwrap();
}
let old = std::time::SystemTime::now() - (STAGED_STDIN_RETENTION * 2);
for p in [&held_live, &held_dead, &unclaimed] {
let f = std::fs::File::options().write(true).open(p).unwrap();
f.set_times(std::fs::FileTimes::new().set_modified(old))
.unwrap();
}
crate::app::sweep_dead_view_sockets(tmp.path());
let live_survived = held_live.exists();
let _ = peer.kill();
let _ = peer.wait();
assert!(
live_survived,
"a pipe held by a running croft must survive the sweep at any age: \
the tab re-opens it by path and the bytes cannot be regenerated"
);
assert!(
!held_dead.exists(),
"a pipe whose holder has exited, and which has aged out, is litter"
);
assert!(
!unclaimed.exists(),
"and an unclaimed staged file still ages out, or the sweep stops \
bounding the pile at all"
);
}
/// The server stamps its own pid onto a staged file when it opens it (#362).
///
/// The rename is what gives the sweep a live holder to see. It must happen
/// BEFORE the open, so the editor holds the name the sweep will spare rather
/// than one that is about to move under it.
#[test]
fn opening_a_staged_pipe_claims_it_for_this_croft() {
let tmp = tempfile::tempdir().unwrap();
let staged = crate::view_ipc::stage_stdin(tmp.path(), b"a,b\n1,2\n", None).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let reply = app.apply_view_request(&staged);
assert_eq!(reply, crate::view_ipc::ViewReply::Ok, "the pipe must open");
assert!(
!staged.exists(),
"the staged name must be gone: it is the name the sweep judges by age"
);
let open = app.editor.editors[app.editor.active_index()]
.path
.clone()
.expect("a file is open");
let name = open.file_name().unwrap().to_str().unwrap();
assert_eq!(
crate::view_ipc::holder_of_staged(name),
Some(std::process::id()),
"the EDITOR must hold the claimed path, or a page turn re-opens a \
name that no longer exists: {name}"
);
assert!(
open.exists(),
"and the claimed file must be on disk under its new name"
);
}
/// An ordinary file is never renamed by the claim (#362).
#[test]
fn opening_a_named_file_does_not_rename_it() {
let tmp = tempfile::tempdir().unwrap();
// Deliberately named like a staged file, but NOT in the staging dir: the
// directory check is what stops croft renaming a user's own file.
let decoy = tmp.path().join("stdin-1-0.txt");
std::fs::write(&decoy, b"mine").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let reply = app.apply_view_request(&decoy);
assert_eq!(reply, crate::view_ipc::ViewReply::Ok, "it must still open");
assert!(
decoy.exists(),
"a file the user named must keep its name, whatever it looks like"
);
assert_eq!(
app.editor.editors[app.editor.active_index()]
.path
.as_deref(),
Some(decoy.as_path()),
"and the editor holds the path the user asked for"
);
}
#[test]
fn the_staging_sweep_leaves_a_file_it_did_not_stage() {
// The name filter, which had no negative case: the socket sweep has one
// and this did not. A user who drops a note in the staging directory, or
// any other program that writes there, must not have it deleted on a
// guess just for being old.
let tmp = tempfile::tempdir().unwrap();
let staged = tmp.path().join("view-stdin");
std::fs::create_dir_all(&staged).unwrap();
let stranger = staged.join("notes.txt");
std::fs::write(&stranger, b"not croft's").unwrap();
let ours = staged.join("stdin-999999-0.txt");
std::fs::write(&ours, b"croft's").unwrap();
// Both older than the window, so age cannot be what separates them.
let old = std::time::SystemTime::now() - (STAGED_STDIN_RETENTION * 2);
for p in [&stranger, &ours] {
let f = std::fs::File::options().write(true).open(p).unwrap();
f.set_times(std::fs::FileTimes::new().set_modified(old))
.unwrap();
}
crate::app::sweep_staged_stdin(tmp.path());
assert!(
stranger.exists(),
"a file croft did not stage is not croft's to delete"
);
assert!(
!ours.exists(),
"and the control: a staged file that old goes"
);
}
#[test]
fn the_sweep_removes_staged_stdin_old_enough_that_nothing_can_be_showing_it() {
// The other half. Age is the honest key here: the pid in the name belongs
// to a process that is always gone, so liveness answers a question the
// name cannot pose. Anything older than the retention window predates any
// running croft's session.
let tmp = tempfile::tempdir().unwrap();
let stale = crate::view_ipc::stage_stdin(tmp.path(), b"secret", Some("txt")).unwrap();
// Backdate past the window without waiting for it.
let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60 * 60 * 30);
let f = std::fs::File::options().write(true).open(&stale).unwrap();
f.set_modified(old).unwrap();
drop(f);
crate::app::sweep_dead_view_sockets(tmp.path());
assert!(
!stale.exists(),
"a staged pipe older than the window must not outlive it: the module's \
own rationale names `vault read | croft view -`"
);
}
// NOT a test: `a_client_that_never_reads_its_reply` was written for the
// missing write timeout and removed rather than kept green. Measured, the
// drain returned in 13ms because the reply is bounded by MAX_REQUEST_BYTES
// (~16KB of path) while Linux's default unix-socket buffer is an order of
// magnitude larger, so `write_all` never blocks here whatever the timeout is.
// The fix (`set_write_timeout` in `answer_view_client`) is correct on macOS,
// whose buffers are small enough to hit it and which is croft's primary
// platform - but a test that passes identically with and without it is not
// evidence, and keeping one would misrepresent this as covered.
#[test]
fn the_view_socket_is_bound_before_the_first_pane_is_spawned() {
// The blocker this PR exists to fix, pinned. `croft view` failed in the
// STARTUP pane because `App::new` built that pane before binding the
// socket, and portable-pty snapshots the environment inside
// `CommandBuilder::new`. Every other test on this branch seats a listener
// by hand and skips the bind entirely, so reverting the ordering left the
// whole suite green - the one defect this branch is about had no guard.
//
// Checked against the SOURCE rather than at runtime, deliberately.
// `view_ipc::SOCK_PATH` is a set-once process global: a test that ran the
// real bind would publish a temp path into every other test in this
// binary, which is the hazard `CACHE_DIR_OVERRIDE_FOR_TEST` exists to
// avoid for the cache dir. The repo already checks source-level properties
// this way (`scripts/check_doc_ownership.py`). It is brittle to a rename,
// and it fails loudly and says why, which is the trade being made.
let src = include_str!("mod.rs");
let ctor = src
.find("pub fn new(root: PathBuf)")
.expect("App::new must exist for this guard to mean anything");
// Bounded to App::new's own body. Slicing to the end of the file let two
// plausible edits satisfy the guard while inverting the runtime order:
// extracting the pane spawn into a helper defined BELOW App::new (the
// marker's offset then jumps past the bind's), or a doc comment naming
// `Self::bind_view_socket()` somewhere above a later spawn.
let end = src[ctor..]
.find("\n pub fn ")
.map(|i| ctor + i)
.unwrap_or(src.len());
let body = &src[ctor..end];
// And each marker must be unique in the file, so a second occurrence
// cannot silently be the one measured.
for marker in ["Self::bind_view_socket()", "PtyTerminal::new(&root)"] {
assert_eq!(
src.matches(marker).count(),
1,
"{marker} must appear exactly once, or this guard measures whichever \
copy comes first rather than the one that runs"
);
}
let bind = body
.find("Self::bind_view_socket()")
.expect("App::new must bind the view socket");
let pane = body
.find("PtyTerminal::new(&root)")
.expect("App::new must spawn the first pane");
assert!(
bind < pane,
"the view socket must be bound BEFORE the first pane is spawned: \
portable-pty snapshots the environment when a pane's CommandBuilder \
is built, so a pane constructed first never learns the socket and \
`croft view` fails in it while working in every pane opened later"
);
}
#[test]
fn a_view_request_for_a_fifo_is_refused_rather_than_opened() {
// `apply_view_request` refused only directories, so a FIFO passed the
// check and reached `Editor::open`, whose `File::open` BLOCKS until a
// writer appears. `mkfifo /tmp/f && croft view /tmp/f` from any pane froze
// the whole editor permanently, recoverable only by SIGKILL, and
// `/dev/zero` took the same route and read until OOM.
//
// The 20ms drain deadline does not help: it bounds the READ of the
// request, and this is the step after it. Bounding one stage of a pipeline
// says nothing about the next.
//
// Run on a thread with a join deadline: against the old behaviour this
// hangs forever, and a hang reads as a CI timeout rather than as this
// defect.
let tmp = tempfile::tempdir().unwrap();
let fifo = tmp.path().join("pipe");
let c = std::ffi::CString::new(fifo.as_os_str().as_encoded_bytes()).unwrap();
assert_eq!(
unsafe { libc::mkfifo(c.as_ptr(), 0o600) },
0,
"precondition: the fixture must actually create a FIFO"
);
assert!(
fifo.exists(),
"and `exists()` must say yes, as it did in production"
);
let root = tmp.path().to_path_buf();
let target = fifo.clone();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut app = App::new(root).unwrap();
let _ = tx.send(app.apply_view_request(&target));
});
let reply = rx
.recv_timeout(crate::test_budget::spawn_budget(
crate::test_budget::tests::VIEW_FIFO_RECV_BASE,
))
.expect("opening a FIFO must not block the frame loop forever");
assert!(
matches!(reply, crate::view_ipc::ViewReply::Err { .. }),
"a FIFO is not a regular file and must be refused with a reason the \
client prints, got {reply:?}"
);
}
#[test]
fn a_terminated_request_over_the_cap_is_refused_like_an_unterminated_one() {
// The cap was tested on the iteration AFTER the newline branch, so a
// request carrying its newline in the very chunk that crossed the limit
// was accepted and deserialised. The bound held for an unterminated flood
// and not for a terminated one - which is the shape a real client sends.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let sock = seat_view_listener(&mut app, tmp.path());
let sock2 = sock.clone();
let flood = std::thread::spawn(move || {
let Ok(mut c) = std::os::unix::net::UnixStream::connect(&sock2) else {
return;
};
// Just past the cap, and TERMINATED, so the newline lands INSIDE the
// chunk that crosses the limit. The size matters: overshoot by more
// than one 4096-byte chunk and the accumulate-path check fires on an
// earlier read, before the newline arrives, which the old ordering
// also refused - a fixture that big cannot tell the two apart. This is
// the only window where the newline branch runs first.
let mut line = vec![b'x'; (crate::view_ipc::MAX_REQUEST_BYTES as usize) + 100];
line.push(b'\n');
let _ = std::io::Write::write_all(&mut c, &line);
let _ = std::io::Write::flush(&mut c);
std::thread::sleep(std::time::Duration::from_millis(300));
});
std::thread::sleep(std::time::Duration::from_millis(50));
let listener = app.view_listener.as_ref().unwrap();
let stream = accept_when_ready(listener);
// The client thread sleeps before it writes, so this deadline is racing a
// scheduler, not the server. Load-scaled for the same reason every other
// spawn wait here is (CONTRIBUTING.md).
let deadline = std::time::Instant::now()
+ crate::test_budget::spawn_budget(crate::test_budget::tests::VIEW_SERVER_DEADLINE_BASE);
let (reply, opened) = app.answer_view_client(stream, deadline);
let _ = flood.join();
assert!(!opened, "an oversized request names nothing to open");
match reply {
crate::view_ipc::ViewReply::Err { message } => assert!(
message.contains("exceeded the maximum length"),
"the LENGTH cap must be what refuses this, not an incidental parse \
failure downstream of accepting it: {message}"
),
other => panic!("an oversized request must not be accepted: {other:?}"),
}
}
/// Pick the row of the open list picker whose id is `id`.
fn pick_row_id(app: &mut App, id: &str) {
let picker = app.list_picker.as_mut().expect("a picker is open");
picker.selected = picker
.rows
.iter()
.position(|r| r.id == id)
.unwrap_or_else(|| panic!("no row {id}"));
app.confirm_list_picker();
}
/// Type `value` over whatever the open prompt holds and press Enter.
fn answer_prompt(app: &mut App, value: &str) {
app.input_prompt.as_mut().expect("a prompt is open").value = value.to_string();
app.submit_input_prompt();
}
/// #250: Debug: Add Configuration… walks the fields a launch needs, refuses
/// a value that does not fit without losing the rest, and writes the entry
/// to `.croft/launch.json`, selected for F5 and listed in the picker.
#[test]
fn add_debug_configuration_writes_a_launch_entry() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Reachable from the picker, not only the palette.
app.open_debug_config_picker();
pick_row_id(&mut app, "add");
pick_row_id(&mut app, "python");
pick_row_id(&mut app, "launch");
let prompt = app.input_prompt.as_ref().expect("the name is asked");
assert_eq!(prompt.value, "Launch Python", "seeded with a name");
answer_prompt(&mut app, "Serve");
assert_eq!(app.input_prompt.as_ref().unwrap().value, "${file}");
answer_prompt(&mut app, "${workspaceFolder}/api.py");
answer_prompt(&mut app, "--port \"80 00");
assert!(app.status.contains("quote"), "{}", app.status);
assert_eq!(
app.input_prompt.as_ref().unwrap().value,
"--port \"80 00",
"the refused value is offered back to fix"
);
answer_prompt(&mut app, "--port 8000");
// Optional fields take a blank Enter.
answer_prompt(&mut app, "");
answer_prompt(&mut app, "DEBUG=1");
answer_prompt(&mut app, "");
assert!(app.input_prompt.is_none(), "the draft is complete");
assert!(app.status.contains("Added \"Serve\""), "{}", app.status);
assert_eq!(app.selected_debug_config.as_deref(), Some("Serve"));
let cfgs = crate::dap::configs::discover_configs(tmp.path());
assert_eq!(cfgs.len(), 1);
assert_eq!(cfgs[0].source, ".croft/launch.json");
let written: serde_json::Value = serde_json::from_str(
&std::fs::read_to_string(tmp.path().join(".croft/launch.json")).unwrap(),
)
.unwrap();
let entry = &written["configurations"][0];
assert_eq!(entry["program"], "${workspaceFolder}/api.py");
assert_eq!(entry["args"], serde_json::json!(["--port", "8000"]));
assert_eq!(entry["env"]["DEBUG"], "1");
assert!(entry.get("cwd").is_none() && entry.get("preLaunchTask").is_none());
app.open_debug_config_picker();
assert!(
app.list_picker
.as_ref()
.unwrap()
.rows
.iter()
.any(|r| r.label.starts_with("Serve")),
"and the picker lists it"
);
}
/// #250: an attach asks only where to attach, and the palette starts it.
#[test]
fn add_debug_configuration_attaches_by_port() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(crate::widgets::command_palette::Command::AddDebugConfig);
pick_row_id(&mut app, "node");
pick_row_id(&mut app, "attach");
answer_prompt(&mut app, "Web");
answer_prompt(&mut app, "nope");
assert!(app.status.contains("Not a port"), "{}", app.status);
answer_prompt(&mut app, "9229");
assert!(app.input_prompt.is_none());
let cfgs = crate::dap::configs::discover_configs(tmp.path());
assert_eq!(
(cfgs.len(), cfgs[0].request),
(1, crate::dap::configs::RequestKind::Attach)
);
}
/// Open the debug picker and confirm the row whose label starts with `label`.
fn pick_debug_row(app: &mut App, label: &str) {
app.open_debug_config_picker();
let idx = app
.list_picker
.as_ref()
.expect("picker open")
.rows
.iter()
.position(|r| r.label.starts_with(label))
.unwrap_or_else(|| panic!("{label} is listed"));
app.list_picker.as_mut().unwrap().selected = idx;
app.confirm_list_picker();
}
/// A workspace with two configs and compounds with and without a task. The
/// task never finishes on its own, so a parked launch stays parked.
fn compound_workspace() -> tempfile::TempDir {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(
tmp.path().join(".vscode/tasks.json"),
r#"{ "version": "2.0.0", "tasks": [
{ "label": "build", "type": "shell", "command": "true" }
]}"#,
)
.unwrap();
std::fs::write(
tmp.path().join(".vscode/launch.json"),
r#"{ "configurations": [
{ "name": "Server", "type": "python", "request": "launch", "program": "s.py" },
{ "name": "Client", "type": "python", "request": "launch", "program": "c.py" }
],
"compounds": [
{ "name": "Tasked", "configurations": ["Server"], "preLaunchTask": "build" },
{ "name": "Both", "configurations": ["Server", "Client"] }
]}"#,
)
.unwrap();
tmp
}
#[test]
fn restart_relaunches_the_selected_compound_not_a_stale_config() {
// #567 item 6: a compound launch never became the F5 target, so restart
// (and F5 after the sessions end) ran whatever was selected before.
let tmp = compound_workspace();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.selected_debug_config = Some(String::from("Client"));
pick_debug_row(&mut app, "Tasked");
assert_eq!(app.selected_debug_compound.as_deref(), Some("Tasked"));
assert_eq!(
app.selected_debug_config, None,
"the compound replaces the old target"
);
app.refresh_run_debug();
assert_eq!(app.run_debug.selected_config.as_deref(), Some("Tasked"));
// Restart goes back through the compound, so its task parks the launch
// again. Launching "Client" (the stale target) or bare "Server" (its
// member) would clear the parking instead.
app.pending_debug_launch = None;
app.debug_restart();
assert!(
app.pending_debug_launch.is_some() && app.status.contains("compound preLaunchTask"),
"restart re-runs the compound behind its own task: {}",
app.status
);
// Choosing a configuration afterwards drops the compound selection.
pick_debug_row(&mut app, "Server");
assert_eq!(app.selected_debug_compound, None);
assert_eq!(app.selected_debug_config.as_deref(), Some("Server"));
}
#[test]
fn a_direct_compound_launch_drops_an_older_parked_task() {
// #567 item 5: the parked launch outlived a newer compound launch, and
// its task's exit would later start its config and stop the compound.
let tmp = compound_workspace();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
pick_debug_row(&mut app, "Tasked");
assert!(
app.pending_debug_launch.is_some(),
"the task-gated launch is parked"
);
pick_debug_row(&mut app, "Both");
assert!(
app.pending_debug_launch.is_none(),
"the newer compound launch supersedes the parked one"
);
}
#[test]
fn a_zero_config_launch_drops_an_older_parked_task() {
let tmp = compound_workspace();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
pick_debug_row(&mut app, "Tasked");
assert!(app.pending_debug_launch.is_some());
pick_debug_row(&mut app, "Debug active file");
assert!(app.pending_debug_launch.is_none());
}
/// A stand-in adapter that emits one DAP `terminated` event and then idles,
/// or (with `ends: false`) never says anything. Real processes, so the test
/// drives the same transport and `poll` the app does.
fn stub_member(ends: bool) -> crate::dap::session::DapSession {
let script = if ends {
"printf 'Content-Length: %d\r\n\r\n%s' 45 '{\"seq\":1,\"type\":\"event\",\"event\":\"terminated\"}'; sleep 30"
} else {
"sleep 30"
};
crate::dap::session::DapSession::launch_with(
"sh",
&[String::from("-c"), String::from(script)],
std::path::Path::new("."),
serde_json::json!({"seq": 2, "type": "request", "command": "launch", "arguments": {}}),
std::collections::BTreeMap::new(),
)
.expect("sh spawns")
}
/// A stand-in adapter that sends each JSON DAP message in `messages`, framed
/// with its byte length, and then idles.
fn stub_emitting(messages: &[&str]) -> crate::dap::session::DapSession {
let mut script = String::new();
for m in messages {
script.push_str(&format!(
"printf 'Content-Length: %d\\r\\n\\r\\n%s' {} '{}'; ",
m.len(),
m
));
}
script.push_str("sleep 30");
crate::dap::session::DapSession::launch_with(
"sh",
&[String::from("-c"), script],
std::path::Path::new("."),
serde_json::json!({"seq": 2, "type": "request", "command": "launch", "arguments": {}}),
std::collections::BTreeMap::new(),
)
.expect("sh spawns")
}
/// Poll until `done` holds or two seconds pass.
fn poll_until(app: &mut App, done: impl Fn(&App) -> bool) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
while !done(app) && std::time::Instant::now() < deadline {
app.poll_dap();
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
/// #567 item 1: a background member's program output used to be drained and
/// dropped. It reaches the debug console, tagged with the member's name.
#[test]
fn a_background_members_output_reaches_the_console_with_its_name() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.debug_sessions.push(
"A",
stub_emitting(&[
r#"{"seq":1,"type":"event","event":"output","body":{"category":"stdout","output":"hello from A\n"}}"#,
]),
);
app.debug_sessions.push("B", stub_member(false));
app.debug_sessions.focus(1);
poll_until(&mut app, |a| {
a.debug_console.iter().any(|l| l.contains("hello from A"))
});
assert!(
app.debug_console.iter().any(|l| l == "[A] hello from A"),
"console: {:?}",
app.debug_console
);
assert_eq!(
app.debug_sessions.focused_name(),
Some("B"),
"output alone does not steal focus"
);
app.debug_stop();
}
/// #567 item 1: a background member hitting a breakpoint looked hung, its
/// `stopped` drained and dropped. With the focused member still running, the
/// view moves to the stopped one and says so.
#[test]
fn a_background_stop_moves_the_view_to_the_stopped_member() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.debug_sessions.push(
"A",
stub_emitting(&[
r#"{"seq":1,"type":"event","event":"stopped","body":{"reason":"breakpoint","threadId":1}}"#,
]),
);
app.debug_sessions.push("B", stub_member(false));
app.debug_sessions.focus(1);
poll_until(&mut app, |a| a.debug_sessions.focused_name() == Some("A"));
assert_eq!(app.debug_sessions.focused_name(), Some("A"));
assert!(app.status.contains("A stopped"), "status: {}", app.status);
assert_eq!(
app.run_debug.feedback.as_deref(),
Some("Paused (breakpoint)"),
"the stop replays through the normal handler once A is focused"
);
app.debug_stop();
}
const STOPPED_EVENT: &str =
r#"{"seq":1,"type":"event","event":"stopped","body":{"reason":"breakpoint","threadId":1}}"#;
/// A compound can list one configuration twice, so two members can share a
/// name: the member that stopped is the one shown, not the first of that name.
#[test]
fn a_stop_shows_the_member_that_stopped_even_when_names_repeat() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.debug_sessions.push("A", stub_member(false));
app.debug_sessions
.push("A", stub_emitting(&[STOPPED_EVENT]));
app.debug_sessions.push("B", stub_member(false));
app.debug_sessions.focus(2);
poll_until(&mut app, |a| a.debug_sessions.focused_index() != 2);
assert_eq!(
app.debug_sessions.focused_index(),
1,
"the second A stopped"
);
app.debug_stop();
}
/// A member ending in the same poll shifts the stopped member's position; the
/// view still lands on the member that stopped.
#[test]
fn a_stop_lands_on_the_right_member_when_an_earlier_one_ends_alongside() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.debug_sessions.push(
"Gone",
stub_emitting(&[r#"{"seq":1,"type":"event","event":"terminated"}"#]),
);
app.debug_sessions
.push("Stops", stub_emitting(&[STOPPED_EVENT]));
app.debug_sessions.push("Watched", stub_member(false));
app.debug_sessions.focus(2);
poll_until(&mut app, |a| {
a.debug_sessions.len() == 2 && a.debug_sessions.focused_name() == Some("Stops")
});
assert_eq!(app.debug_sessions.names(), vec!["Stops", "Watched"]);
assert_eq!(app.debug_sessions.focused_name(), Some("Stops"));
app.debug_stop();
}
/// The stopped member's position once members that ended in the same poll
/// are removed: shifted past removals below it, untouched by those above,
/// and gone if it ended itself.
#[test]
fn index_after_removals_shifts_past_lower_removals_only() {
assert_eq!(index_after_removals(2, &[]), Some(2));
assert_eq!(index_after_removals(2, &[0]), Some(1));
assert_eq!(index_after_removals(3, &[0, 1]), Some(1));
assert_eq!(
index_after_removals(1, &[2, 3]),
Some(1),
"removals above do not move it"
);
assert_eq!(index_after_removals(2, &[0, 2]), None, "it ended itself");
}
/// The switch command cycles the members, and says so when there is only one.
#[test]
fn switch_debug_session_cycles_the_members() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.debug_sessions.push("A", stub_member(false));
app.switch_debug_session();
assert_eq!(app.status, "Only one debug session is running");
app.debug_sessions.push("B", stub_member(false));
assert_eq!(app.debug_sessions.focused_name(), Some("B"));
app.switch_debug_session();
assert_eq!(app.debug_sessions.focused_name(), Some("A"));
assert!(
app.status.starts_with("Debugging A"),
"status: {}",
app.status
);
app.switch_debug_session();
assert_eq!(app.debug_sessions.focused_name(), Some("B"));
assert!(is_switch_debug_session_key(key(
KeyCode::Char('g'),
KeyModifiers::SUPER | KeyModifiers::ALT | KeyModifiers::SHIFT,
)));
assert!(!is_switch_debug_session_key(key(
KeyCode::Char('g'),
KeyModifiers::SUPER | KeyModifiers::ALT,
)));
app.debug_stop();
}
/// What a member reported in the background replays when it is switched to:
/// a queued `stopped` drives the same handler it would have when focused.
#[test]
fn a_switched_to_member_replays_its_queued_stop() {
use crate::dap::session::DapEvent;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.debug_sessions.push("A", stub_member(false));
app.debug_sessions.push("B", stub_member(false));
let (_, a) = app
.debug_sessions
.iter_named_mut_indexed()
.find(|(i, _)| *i == 0)
.unwrap();
a.backlog.push(DapEvent::Stopped {
thread_id: 1,
reason: String::from("exception"),
});
app.poll_dap();
assert_ne!(
app.run_debug.feedback.as_deref(),
Some("Paused (exception)"),
"not replayed while A is in the background"
);
app.switch_debug_session();
app.poll_dap();
assert_eq!(
app.run_debug.feedback.as_deref(),
Some("Paused (exception)")
);
app.debug_stop();
}
/// A workspace with two source files and breakpoints set in both (#250).
fn app_with_breakpoints() -> (tempfile::TempDir, App, PathBuf, PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.rs");
let b = tmp.path().join("b.rs");
std::fs::write(&a, "fn a() {}\nfn b() {}\nfn c() {}\n").unwrap();
std::fs::write(&b, "x\ny\nz\nw\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor
.breakpoints
.entry(b.clone())
.or_default()
.insert(4);
app.editor
.breakpoints
.entry(a.clone())
.or_default()
.extend([3, 1]);
app.editor
.breakpoint_conditions
.entry(a.clone())
.or_default()
.insert(3, String::from("n > 2"));
app.editor
.breakpoint_logs
.entry(b.clone())
.or_default()
.insert(4, String::from("at {i}"));
(tmp, app, a, b)
}
#[test]
fn breakpoint_items_list_every_breakpoint_by_file_then_line() {
let (_tmp, app, _a, _b) = app_with_breakpoints();
let items = app.breakpoint_items();
let shown: Vec<(String, Option<String>)> = items
.iter()
.map(|i| (i.label.clone(), i.detail.clone()))
.collect();
assert_eq!(
shown,
vec![
(String::from("a.rs:1"), None),
(String::from("a.rs:3"), Some(String::from("if n > 2"))),
(String::from("b.rs:4"), Some(String::from("log at {i}"))),
]
);
}
/// The ✕ removes the breakpoint and the condition that went with it, so a
/// breakpoint set again later on that line starts plain.
#[test]
fn removing_from_the_list_drops_the_breakpoint_and_its_condition() {
let (_tmp, mut app, a, _b) = app_with_breakpoints();
app.sync_breakpoint_list();
let idx = app
.run_debug
.breakpoints
.iter()
.position(|i| i.label == "a.rs:3")
.unwrap();
app.breakpoint_list_click(idx, true);
assert!(!app.editor.breakpoints[&a].contains(&3));
assert!(
app.editor.breakpoints[&a].contains(&1),
"only that one goes"
);
assert!(!app.editor.breakpoint_conditions[&a].contains_key(&3));
assert_eq!(app.run_debug.breakpoints.len(), 2, "the list follows");
}
#[test]
fn clicking_a_breakpoint_opens_its_file_at_the_line() {
// Line 1 of a three-line file: a jump one row off lands on a different
// line, where the file's LAST line would be clamped back and hide it.
let (_tmp, mut app, a, _b) = app_with_breakpoints();
app.sync_breakpoint_list();
let idx = app
.run_debug
.breakpoints
.iter()
.position(|i| i.label == "a.rs:1")
.unwrap();
app.breakpoint_list_click(idx, false);
assert_eq!(app.editor.path.as_deref(), Some(a.as_path()));
assert_eq!(app.editor.cursor_row, 0, "line 1, 0-based");
}
/// While a session is shown the tree carries the list as its last section;
/// a change swaps that section rather than stacking a second one.
#[test]
fn the_tree_breakpoint_section_follows_changes_without_duplicating() {
use crate::widgets::run_debug::{DebugRow, DebugRowKind};
let (_tmp, mut app, a, _b) = app_with_breakpoints();
app.run_debug.debug_active = true;
app.run_debug.debug_rows = vec![DebugRow {
indent: 0,
kind: DebugRowKind::Header {
title: String::from("CALL STACK"),
},
}];
app.sync_breakpoint_list();
let count = |app: &App| {
(
app.run_debug
.debug_rows
.iter()
.filter(
|r| matches!(&r.kind, DebugRowKind::Header { title } if title == "BREAKPOINTS"),
)
.count(),
app.run_debug
.debug_rows
.iter()
.filter(|r| matches!(r.kind, DebugRowKind::Breakpoint { .. }))
.count(),
)
};
assert_eq!(count(&app), (1, 3));
app.editor.breakpoints.get_mut(&a).unwrap().insert(2);
app.sync_breakpoint_list();
assert_eq!(count(&app), (1, 4), "one header, one more row");
assert!(matches!(
&app.run_debug.debug_rows[0].kind,
DebugRowKind::Header { title } if title == "CALL STACK"
));
}
fn resolved_attach(json: &str) -> crate::dap::configs::ResolvedConfig {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(tmp.path().join(".vscode/launch.json"), json).unwrap();
let cfg = crate::dap::configs::discover_configs(tmp.path())
.into_iter()
.next()
.expect("one config");
let ctx = crate::dap::configs::SubstCtx {
workspace_folder: tmp.path().to_path_buf(),
file: None,
};
crate::dap::configs::resolve(&cfg, &ctx).expect("resolves")
}
/// #250: an lldb attach whose `processId` is `${command:pickProcess}` opens
/// a process picker instead of failing, and the chosen pid resumes it.
#[test]
fn a_pick_process_attach_opens_the_process_picker() {
use crate::widgets::list_picker::ListPurpose;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let rc = resolved_attach(
r#"{ "configurations": [ { "name": "Attach", "type": "lldb", "request": "attach",
"processId": "${command:pickProcess}" } ] }"#,
);
app.launch_resolved_config(rc);
let picker = app.list_picker.as_ref().expect("the picker opens");
assert!(matches!(picker.purpose, ListPurpose::AttachProcess));
assert!(
!picker.rows.is_empty(),
"this test process's siblings are listed"
);
assert!(
picker.rows.iter().all(|r| r.id.parse::<i64>().is_ok()),
"every row id is a pid"
);
assert!(
!picker
.rows
.iter()
.any(|r| r.id == std::process::id().to_string()),
"croft does not offer itself"
);
assert!(
app.debug_sessions.is_empty(),
"nothing launched before the pick"
);
let (rc, _) = app.take_pending_attach(4242).expect("the attach is parked");
assert_eq!(rc.process_id, Some(4242));
assert!(
app.take_pending_attach(4242).is_none(),
"taken once, not twice"
);
}
/// `pickProcess` on an adapter that does not attach by pid is refused with
/// a message, not launched with the key silently dropped.
#[test]
fn pick_process_on_a_non_lldb_config_is_refused() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let rc = resolved_attach(
r#"{ "configurations": [ { "name": "Py", "type": "python", "request": "attach",
"processId": "${command:pickProcess}" } ] }"#,
);
app.launch_resolved_config(rc);
assert!(app.list_picker.is_none());
assert!(
app.status.contains("pickProcess")
|| app
.run_debug
.feedback
.as_deref()
.unwrap_or("")
.contains("pickProcess"),
"status: {} / feedback: {:?}",
app.status,
app.run_debug.feedback
);
}
/// Poll until the set shrinks below `from` members or two seconds pass.
fn poll_until_shrinks(app: &mut App, from: usize) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
while app.debug_sessions.len() >= from && std::time::Instant::now() < deadline {
app.poll_dap();
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
/// A workspace whose tasks.json declares a `cleanup` task (#250).
fn app_with_cleanup_task() -> (tempfile::TempDir, App) {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(
tmp.path().join(".vscode/tasks.json"),
r#"{ "version": "2.0.0", "tasks": [
{ "label": "cleanup", "type": "shell", "command": "true" }
]}"#,
)
.unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
(tmp, app)
}
fn last_task_label(app: &App) -> Option<String> {
app.last_task.as_ref().map(|t| t.label.clone())
}
/// #250: a config's `postDebugTask` runs when the user stops the session.
#[test]
fn stopping_a_session_runs_its_post_debug_task_once() {
let (_tmp, mut app) = app_with_cleanup_task();
app.debug_sessions.push("A", stub_member(false));
app.debug_post_tasks = vec![String::from("cleanup")];
app.debug_stop_by_user();
assert_eq!(last_task_label(&app).as_deref(), Some("cleanup"));
assert!(app.debug_post_tasks.is_empty(), "it runs once, not again");
}
/// With nothing running there is no session to clean up after: a launch
/// that failed before a session started must not trigger the task.
#[test]
fn stopping_with_no_session_runs_no_post_debug_task() {
let (_tmp, mut app) = app_with_cleanup_task();
app.debug_post_tasks = vec![String::from("cleanup")];
app.debug_stop_by_user();
assert_eq!(last_task_label(&app), None);
}
/// #250: a session that ends by itself runs the task too.
#[test]
fn a_session_ending_on_its_own_runs_its_post_debug_task() {
let (_tmp, mut app) = app_with_cleanup_task();
app.debug_sessions.push("A", stub_member(true));
app.debug_post_tasks = vec![String::from("cleanup")];
poll_until_shrinks(&mut app, 1);
assert!(app.debug_sessions.is_empty(), "the stub terminated");
assert_eq!(last_task_label(&app).as_deref(), Some("cleanup"));
}
/// Replacing the set for a new launch is not the end of a debug run, so
/// the internal stop leaves the task alone (VS Code runs it on stop and on
/// termination, not on relaunch).
#[test]
fn the_internal_stop_before_a_relaunch_runs_no_post_debug_task() {
let (_tmp, mut app) = app_with_cleanup_task();
app.debug_sessions.push("A", stub_member(false));
app.debug_post_tasks = vec![String::from("cleanup")];
app.debug_stop();
assert_eq!(last_task_label(&app), None);
}
#[test]
fn stop_all_true_stops_the_set_when_a_background_member_ends() {
// #567 item 4: `stopAll: true` was refused; it is honoured now.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.debug_sessions.push("A", stub_member(true));
app.debug_sessions.push("B", stub_member(false));
app.debug_sessions.focus(1);
app.debug_stop_all = true;
poll_until_shrinks(&mut app, 2);
assert!(
app.debug_sessions.is_empty(),
"A ending takes B with it: {:?}",
app.debug_sessions.names()
);
assert!(
app.status.contains("stopAll"),
"and says why: {}",
app.status
);
}
#[test]
fn stop_all_false_leaves_the_siblings_running() {
// The control: without stopAll only the member that ended goes.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.debug_sessions.push("A", stub_member(true));
app.debug_sessions.push("B", stub_member(false));
app.debug_sessions.focus(1);
poll_until_shrinks(&mut app, 2);
assert_eq!(app.debug_sessions.names(), vec!["B"]);
app.debug_stop();
}
/// A compound that is REFUSED (here, it names a configuration no
/// launch.json declares) leaves the running set alone, so it must not leave
/// its `stopAll` behind either: that set never asked for it.
#[test]
fn a_refused_compound_does_not_hand_its_stop_all_to_the_running_set() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(
tmp.path().join(".vscode/launch.json"),
r#"{"version":"0.2.0","configurations":[],
"compounds":[{"name":"Bad","configurations":["Missing"],"stopAll":true}]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.debug_sessions.push("A", stub_member(true));
app.debug_sessions.push("B", stub_member(false));
app.debug_sessions.focus(1);
let compound = crate::dap::configs::discover_compounds(tmp.path())
.into_iter()
.find(|c| c.name == "Bad")
.expect("the compound parses");
assert!(compound.stop_all);
app.launch_compound(&compound);
assert_eq!(
app.debug_sessions.len(),
2,
"the refusal leaves the set running"
);
poll_until_shrinks(&mut app, 2);
assert_eq!(
app.debug_sessions.names(),
vec!["B"],
"A ending must not take B: the running set never asked for stopAll"
);
app.debug_stop();
}
#[test]
fn a_background_member_ending_rebuilds_the_report_from_the_live_set() {
// #567 items 2 and 3: the status and panel line kept naming the ended
// session. Both now say what ended, what is shown, and what still runs.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.debug_sessions.push("A", stub_member(true));
app.debug_sessions.push("B", stub_member(false));
app.debug_sessions.focus(1);
app.debug_compound = Some(String::from("Stack"));
app.run_debug.feedback = Some(String::from("Debugging compound Stack: A, B"));
poll_until_shrinks(&mut app, 2);
assert_eq!(app.debug_sessions.names(), vec!["B"]);
assert_eq!(
app.run_debug.feedback.as_deref(),
Some("Debugging compound Stack: B (A ended)")
);
assert!(
app.status.starts_with("A ended — showing B; running: B"),
"{}",
app.status
);
app.debug_stop();
assert_eq!(app.debug_compound, None, "a full stop forgets the compound");
}
#[test]
fn the_focused_member_ending_names_the_session_now_shown() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.debug_sessions.push("A", stub_member(true));
app.debug_sessions.push("B", stub_member(false));
app.debug_sessions.focus(0);
app.debug_compound = Some(String::from("Stack"));
poll_until_shrinks(&mut app, 2);
assert_eq!(app.debug_sessions.names(), vec!["B"]);
assert!(
app.status.starts_with("A ended — showing B; running: B"),
"{}",
app.status
);
app.debug_stop();
}
// ---- Live Run (Cmd+K V) ----
#[test]
fn live_run_refuses_a_file_that_is_not_python() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "notes.txt", "hello\n");
app.run_command(crate::widgets::command_palette::Command::ToggleLiveRun);
assert!(app.live_run_files.is_empty(), "nothing is armed");
assert!(app.status.contains("Python"), "{}", app.status);
}
#[test]
fn live_run_arms_only_the_active_file_and_disarming_clears_its_trailers() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.py", "x = 1\n");
let path = app.editor.path.clone().unwrap();
app.run_command(crate::widgets::command_palette::Command::ToggleLiveRun);
assert_eq!(
app.live_run_files.iter().collect::<Vec<_>>(),
vec![&path],
"exactly the active file is armed"
);
app.editor.live_run = Some(crate::live_run::View::default());
app.run_command(crate::widgets::command_palette::Command::ToggleLiveRun);
assert!(app.live_run_files.is_empty());
assert!(
app.editor.live_run.is_none(),
"a disarmed file keeps no trailers"
);
}
/// The whole loop against a real interpreter, when the machine has one:
/// arm, tick until the run lands, and find its values on the tab.
#[test]
fn live_run_lands_a_real_run_on_the_tab() {
let has_python = std::process::Command::new("python3")
.arg("--version")
.output()
.is_ok_and(|o| o.status.success());
if !has_python {
return;
}
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.py", "n = len('abc')\nprint(n * 2)\n");
app.run_command(crate::widgets::command_palette::Command::ToggleLiveRun);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while app.editor.live_run.is_none() && std::time::Instant::now() < deadline {
app.tick_live_run();
std::thread::sleep(std::time::Duration::from_millis(20));
}
let view = app.editor.live_run.as_ref().expect("the run landed");
assert_eq!(
view.note(0, "n = len('abc')").map(|n| n[0].0.as_str()),
Some("n = 3")
);
assert_eq!(
view.note(1, "print(n * 2)").map(|n| n[0].0.as_str()),
Some("\u{25b8} 6")
);
assert!(app.status.starts_with("Live Run: ok"), "{}", app.status);
}
// ---- Explorer moves ask the servers first (#610) ----
#[test]
fn a_file_move_applies_the_servers_edits_before_renaming() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::write(root.join("util.py"), "def f(): pass\n").unwrap();
std::fs::write(root.join("main.py"), "import util\n").unwrap();
let mut app = App::new(root.clone()).unwrap();
let pending = PendingFileMove {
request_id: 7,
op: FileMove::Rename {
parent: root.clone(),
old: root.join("util.py"),
new_name: String::from("helpers.py"),
},
renames: vec![crate::lsp::manager::FileRenameOp {
old: root.join("util.py"),
new: root.join("helpers.py"),
is_dir: false,
}],
deadline: std::time::Instant::now(),
};
let edits = vec![(
root.join("main.py"),
vec![crate::widgets::editor::TextSpanEdit {
start: (0, 7),
end: (0, 11),
new_text: String::from("helpers"),
utf16: false,
}],
)];
app.finish_file_move(pending, edits);
assert!(root.join("helpers.py").exists(), "the file moved");
assert!(!root.join("util.py").exists());
assert_eq!(
std::fs::read_to_string(root.join("main.py")).unwrap(),
"import helpers\n",
"the import followed it"
);
assert!(
app.status.contains("references updated in 1 file"),
"{}",
app.status
);
}
#[test]
fn moving_files_and_folders_carries_every_open_tab_along() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::create_dir_all(root.join("dir")).unwrap();
std::fs::create_dir_all(root.join("dest")).unwrap();
std::fs::write(root.join("a.txt"), "a").unwrap();
std::fs::write(root.join("dir/b.txt"), "b").unwrap();
std::fs::write(root.join("c.txt"), "c").unwrap();
let mut app = App::new(root.clone()).unwrap();
app.editor.open_pinned(&root.join("a.txt")).unwrap();
app.editor.open_in_new_tab(&root.join("dir/b.txt")).unwrap();
app.editor.open_in_new_tab(&root.join("c.txt")).unwrap();
// c.txt is active; a.txt and dir/b.txt sit in background tabs.
assert!(app.apply_paste_or_drop(
&root.join("dest"),
&[root.join("a.txt"), root.join("dir")],
ExplorerClipMode::Cut
));
let paths: Vec<_> = app
.editor
.editors
.iter()
.filter_map(|e| e.path.clone())
.collect();
assert!(paths.contains(&root.join("dest/a.txt")), "{paths:?}");
assert!(paths.contains(&root.join("dest/dir/b.txt")), "{paths:?}");
}
/// A move re-points the file's tab in the OTHER split too, not only in the
/// focused group.
#[test]
fn moving_a_file_repoints_its_tab_in_every_split() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::create_dir_all(root.join("dest")).unwrap();
std::fs::write(root.join("a.txt"), "a").unwrap();
std::fs::write(root.join("c.txt"), "c").unwrap();
let mut app = App::new(root.clone()).unwrap();
app.editor.open_pinned(&root.join("a.txt")).unwrap();
app.focus_pane(Pane::Editor);
app.split_editor();
// The focused (right) group moves on to another file; a.txt stays open
// in the left one.
app.editor.open_pinned(&root.join("c.txt")).unwrap();
app.editor.close_tab(0);
assert!(app.apply_paste_or_drop(
&root.join("dest"),
&[root.join("a.txt")],
ExplorerClipMode::Cut
));
let groups = app.editor_layout.inactive_groups_mut();
let paths: Vec<_> = groups[0]
.editors
.iter()
.filter_map(|e| e.path.clone())
.collect();
assert!(paths.contains(&root.join("dest/a.txt")), "{paths:?}");
}
#[test]
fn a_failed_move_leaves_the_importers_alone_and_edits_follow_a_moved_file() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::create_dir_all(root.join("pkg/sub")).unwrap();
std::fs::write(root.join("main.rs"), "use pkg;\n").unwrap();
let mut app = App::new(root.clone()).unwrap();
let edit = |path: PathBuf| {
vec![(
path,
vec![crate::widgets::editor::TextSpanEdit {
start: (0, 4),
end: (0, 7),
new_text: String::from("pkg::sub::pkg"),
utf16: false,
}],
)]
};
// A folder into its own child: refused, and main.rs must not change.
let pending = PendingFileMove {
request_id: 1,
op: FileMove::Paste {
dest_dir: root.join("pkg/sub"),
paths: vec![root.join("pkg")],
},
renames: vec![crate::lsp::manager::FileRenameOp {
old: root.join("pkg"),
new: root.join("pkg/sub/pkg"),
is_dir: true,
}],
deadline: std::time::Instant::now(),
};
app.finish_file_move(pending, edit(root.join("main.rs")));
assert_eq!(
std::fs::read_to_string(root.join("main.rs")).unwrap(),
"use pkg;\n"
);
assert!(root.join("pkg/sub").is_dir());
// An edit to a file inside the moved folder lands at its new place.
std::fs::write(root.join("pkg/lib.rs"), "use pkg;\n").unwrap();
std::fs::create_dir_all(root.join("dest")).unwrap();
let pending = PendingFileMove {
request_id: 2,
op: FileMove::Paste {
dest_dir: root.join("dest"),
paths: vec![root.join("pkg")],
},
renames: vec![crate::lsp::manager::FileRenameOp {
old: root.join("pkg"),
new: root.join("dest/pkg"),
is_dir: true,
}],
deadline: std::time::Instant::now(),
};
app.finish_file_move(pending, edit(root.join("pkg/lib.rs")));
assert_eq!(
std::fs::read_to_string(root.join("dest/pkg/lib.rs")).unwrap(),
"use pkg::sub::pkg;\n"
);
}
#[test]
fn a_pending_move_goes_ahead_at_its_deadline_without_an_answer() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::write(root.join("a.txt"), "x").unwrap();
let mut app = App::new(root.clone()).unwrap();
app.pending_file_move = Some(PendingFileMove {
request_id: u64::MAX,
op: FileMove::Rename {
parent: root.clone(),
old: root.join("a.txt"),
new_name: String::from("b.txt"),
},
renames: Vec::new(),
deadline: std::time::Instant::now() - std::time::Duration::from_millis(1),
});
assert!(app.tick_file_moves());
assert!(app.pending_file_move.is_none());
assert!(
root.join("b.txt").exists(),
"a silent server cannot block the move"
);
}
#[test]
fn rename_target_validates_without_touching_the_disk() {
let tmp = tempfile::tempdir().unwrap();
let old = tmp.path().join("a.txt");
std::fs::write(&old, "x").unwrap();
std::fs::write(tmp.path().join("taken.txt"), "y").unwrap();
let target = crate::widgets::file_tree::rename_target(tmp.path(), &old, "b.txt").unwrap();
assert_eq!(target, tmp.path().join("b.txt"));
assert!(old.exists(), "nothing moved yet");
assert!(crate::widgets::file_tree::rename_target(tmp.path(), &old, "taken.txt").is_err());
}
// ---- Markdown preview scroll sync across a split (#619) ----
#[test]
fn a_split_preview_follows_the_source_pane_scroll() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("doc.md");
let mut body = String::from("# Top\n\n");
for i in 0..30 {
body.push_str(&format!("para {i}\n\n"));
}
std::fs::write(&f, &body).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.focus_pane(Pane::Editor);
assert!(
app.editor.toggle_markdown_preview(),
"left pane shows the preview"
);
app.split_editor();
assert!(
app.editor.markdown_preview.is_none(),
"the new pane shows the source"
);
app.editor.scroll = 20;
assert!(
app.sync_markdown_scroll(),
"the preview pane is told to follow"
);
let preview_pane = app
.editor_layout
.inactive_groups()
.into_iter()
.find_map(|g| g.editors.get(g.active_index()))
.and_then(|t| t.markdown_preview.as_ref())
.expect("the other pane still shows the preview");
assert_eq!(preview_pane.scroll_to_source, Some(20));
assert!(
!app.sync_markdown_scroll(),
"a still viewport costs nothing"
);
}
// ---- Code lenses (#608) ----
fn lens_at(line: usize, text: &str, title: &str, command: &str) -> crate::code_lens::EditorLens {
crate::code_lens::EditorLens {
line,
line_text: text.to_string(),
title: title.to_string(),
command: Some(command.to_string()),
arguments: Vec::new(),
server_side: false,
}
}
#[test]
fn clicking_a_painted_code_lens_runs_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}\n");
app.editor.code_lenses = vec![lens_at(
0,
"fn main() {}",
"Frobnicate",
"vendor.frobnicate",
)];
let area = ratatui::layout::Rect::new(0, 0, 80, 10);
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(
&mut *app.editor as &mut crate::widgets::editor::Editor,
area,
&mut buf,
);
let (y, xs, idx) = app
.editor
.code_lens_spans
.first()
.cloned()
.expect("lens painted");
assert_eq!(idx, 0);
let painted: String = xs
.clone()
.map(|x| buf[(x, y)].symbol().to_string())
.collect();
assert_eq!(painted, "Frobnicate");
assert_eq!(app.editor.code_lens_at(xs.start, y), Some(0));
app.run_code_lens(0);
assert!(
app.status
.contains("vendor.frobnicate is not a command croft runs"),
"an unmappable lens says why: {}",
app.status
);
}
#[test]
fn a_code_lens_hides_once_its_line_changes() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}\n");
app.editor.code_lenses = vec![lens_at(0, "fn main() {}", "Run", "x")];
assert_eq!(app.editor.lenses_on_line(0), vec![0]);
app.editor.lines[0] = String::from("fn main() { edited }");
assert!(
app.editor.lenses_on_line(0).is_empty(),
"stale lens is not shown"
);
}
#[test]
fn cmd_k_shift_e_runs_the_caret_lines_only_lens() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}\n");
app.editor.code_lenses = vec![lens_at(
0,
"fn main() {}",
"Frobnicate",
"vendor.frobnicate",
)];
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('E'), KeyModifiers::SHIFT)));
assert!(app.status.starts_with("Code lens:"), "{}", app.status);
app.editor
.code_lenses
.push(lens_at(0, "fn main() {}", "Other", "vendor.other"));
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('e'), KeyModifiers::SHIFT)));
assert!(
app.context_menu.is_some(),
"two lenses open a menu to pick from"
);
}
// ---- #611: hit counts, function breakpoints, Run to Cursor ----
#[test]
fn a_hit_count_prompt_sets_the_breakpoints_hit_condition() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.py", "x = 1\ny = 2\n");
app.editor.cursor_row = 1;
app.run_command(crate::widgets::command_palette::Command::DebugAddHitCountBreakpoint);
let path = app.editor.path.clone().unwrap();
assert!(matches!(
app.prompt.as_ref().map(|p| &p.kind),
Some(PromptKind::HitCondition { line: 2, .. })
));
app.commit_hit_condition(path.clone(), 2, " 5 ");
let lines = app.editor.breakpoints.get(&path).cloned().unwrap();
assert!(lines.contains(&2), "the breakpoint exists");
let specs = app.editor.source_breakpoints(&path, &lines);
assert_eq!(specs[0].hit_condition.as_deref(), Some("5"));
app.commit_hit_condition(path.clone(), 2, "");
let specs = app.editor.source_breakpoints(&path, &lines);
assert_eq!(specs[0].hit_condition, None, "blank clears it");
}
#[test]
fn function_breakpoints_are_kept_for_the_next_session() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.commit_function_breakpoint(String::from("main"));
app.commit_function_breakpoint(String::from("main"));
assert_eq!(
app.function_breakpoints,
vec![String::from("main")],
"no duplicates"
);
app.debug_clear_function_breakpoints();
assert!(app.function_breakpoints.is_empty());
}
#[test]
fn run_to_cursor_without_a_session_says_so() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.py", "x = 1\n");
let ctrl_f10 = crossterm::event::KeyEvent::new(KeyCode::F(10), KeyModifiers::CONTROL);
assert!(is_run_to_cursor_key(ctrl_f10));
assert!(!is_run_to_cursor_key(crossterm::event::KeyEvent::new(
KeyCode::F(10),
KeyModifiers::NONE
)));
app.debug_run_to_cursor();
assert_eq!(app.status, "Run to Cursor: no debug session");
}
// ---- Search Editor (#615) ----
#[test]
fn a_search_editor_reruns_its_header_and_opens_results() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::write(root.join("a.txt"), "one\nthe needle is here\nthree\n").unwrap();
std::fs::write(root.join("b.txt"), "no match\n").unwrap();
let mut app = App::new(root.clone()).unwrap();
app.run_command(crate::widgets::command_palette::Command::OpenSearchEditor);
assert!(crate::search_editor::is_search_editor(&app.editor.lines));
app.editor.lines[0] = String::from("# Query: needle");
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('R'), KeyModifiers::SHIFT)));
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_search_editor() && std::time::Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(10));
}
let text = app.editor.lines.join("\n");
assert!(text.contains("1 result - 1 file"), "{text}");
assert!(text.contains("a.txt:"), "{text}");
let row = app
.editor
.lines
.iter()
.position(|l| l.contains("the needle is here"))
.expect("result row");
app.focus_pane(Pane::Editor);
app.editor.cursor_row = row;
app.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Enter,
KeyModifiers::NONE,
))
.unwrap();
assert_eq!(
app.editor.path.as_deref(),
Some(root.join("a.txt").as_path())
);
assert_eq!(app.editor.cursor_row, 1, "the match's line, 0-based");
}
// ---- Interactive rebase in croft (#620) ----
#[test]
fn rebase_todo_keys_set_the_action_and_step_down() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(
tmp.path(),
"git-rebase-todo",
"pick aaa111 first\npick bbb222 second\n# comment\n",
);
app.editor.cursor_row = 1;
app.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Char('f'),
KeyModifiers::NONE,
))
.unwrap();
assert_eq!(app.editor.lines[1], "fixup bbb222 second");
assert_eq!(app.editor.cursor_row, 2, "the caret moves to the next line");
app.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Char('d'),
KeyModifiers::NONE,
))
.unwrap();
assert_eq!(
app.editor.lines[2], "d# comment",
"a comment line types normally"
);
}
#[test]
fn rebase_keys_type_normally_outside_a_todo_file() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "notes.txt", "pick aaa111 first\n");
app.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Char('s'),
KeyModifiers::NONE,
))
.unwrap();
assert_eq!(app.editor.lines[0], "spick aaa111 first");
}
#[test]
fn a_probe_reports_whether_the_file_is_still_open() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "git-rebase-todo", "pick a b\n");
let path = app.editor.path.clone().unwrap();
assert_eq!(
app.probe_view_path(&path),
crate::view_ipc::ViewReply::Err {
message: String::from(crate::view_ipc::PROBE_OPEN)
}
);
app.run_command(crate::widgets::command_palette::Command::CloseEditor);
assert!(matches!(
app.probe_view_path(&path),
crate::view_ipc::ViewReply::Err { .. }
));
}
#[test]
fn the_sequence_editor_command_quotes_the_binary_path() {
assert_eq!(
crate::widgets::terminal::sequence_editor_command(std::path::Path::new(
"/opt/my croft/croft"
)),
"'/opt/my croft/croft' edit --wait --sequence-editor"
);
}
#[test]
fn a_plain_view_request_has_no_probe_field_on_the_wire() {
// An older croft must read this build's `croft view` unchanged.
let json = serde_json::to_string(&crate::view_ipc::ViewRequest::new(std::path::Path::new(
"/a",
)))
.unwrap();
assert!(!json.contains("probe"), "{json}");
let probe = serde_json::to_string(&crate::view_ipc::ViewRequest::probe(std::path::Path::new(
"/a",
)))
.unwrap();
assert!(probe.contains("\"probe\":true"));
}
// ---- Keyboard Shortcuts editor (#612) ----
#[test]
fn recording_a_shortcut_writes_it_and_takes_effect_at_once() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.keybindings_file = tmp.path().join("keybindings.json");
app.open_keyboard_shortcuts();
let cmd = crate::widgets::command_palette::Command::ToggleLiveRun;
app.recording_shortcut = Some((cmd, std::time::Instant::now()));
// Plain typing is refused and ends the recording.
app.handle_key(key(KeyCode::Char('j'), KeyModifiers::NONE))
.unwrap();
assert!(
app.status.contains("needs a function key"),
"{}",
app.status
);
assert!(!app.keybindings_file.exists());
app.recording_shortcut = Some((cmd, std::time::Instant::now()));
app.handle_key(key(
KeyCode::Char('j'),
KeyModifiers::CONTROL | KeyModifiers::ALT,
))
.unwrap();
assert!(
app.status.starts_with("ctrl+alt+j now runs"),
"{}",
app.status
);
let written = std::fs::read_to_string(&app.keybindings_file).unwrap();
assert!(written.contains("\"toggle_live_run\""), "{written}");
assert_eq!(app.keymap.chord_for(cmd).as_deref(), Some("ctrl+alt+j"));
}
#[test]
fn escape_leaves_the_shortcut_unchanged() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.keybindings_file = tmp.path().join("keybindings.json");
app.recording_shortcut = Some((
crate::widgets::command_palette::Command::ToggleLiveRun,
std::time::Instant::now(),
));
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.status, "Shortcut unchanged");
assert!(!app.keybindings_file.exists());
}
#[test]
fn a_stale_or_clicked_away_shortcut_prompt_records_nothing() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.keybindings_file = tmp.path().join("keybindings.json");
let cmd = crate::widgets::command_palette::Command::ToggleLiveRun;
let long_ago = std::time::Instant::now() - std::time::Duration::from_secs(60);
app.recording_shortcut = Some((cmd, long_ago));
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::CONTROL))
.unwrap();
assert!(
!app.keybindings_file.exists(),
"a late chord is not recorded"
);
app.recording_shortcut = Some((cmd, std::time::Instant::now()));
app.handle_mouse(MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column: 1,
row: 1,
modifiers: KeyModifiers::NONE,
});
assert!(
app.recording_shortcut.is_none(),
"a click cancels the prompt"
);
}
// ---- Profiles (#618) ----
#[test]
fn the_profiles_picker_offers_the_default_and_a_new_profile() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(crate::widgets::command_palette::Command::SwitchProfile);
let picker = app.list_picker.as_ref().expect("picker open");
assert!(matches!(
picker.purpose,
crate::widgets::list_picker::ListPurpose::Profiles
));
let ids: Vec<&str> = picker.rows.iter().map(|r| r.id.as_str()).collect();
assert_eq!(ids.first(), Some(&"profile:"), "Default comes first");
assert!(ids.contains(&"new"));
assert!(
!ids.contains(&"workspace-clear"),
"no workspace choice to clear in a fresh workspace"
);
}
#[test]
fn a_new_profile_prompt_refuses_an_unsafe_name_in_place() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.prompt = Some(Prompt {
label: String::from("New profile name"),
buffer: String::from("../escape"),
kind: PromptKind::NewProfile,
target_dir: tmp.path().to_path_buf(),
error: None,
});
app.commit_prompt();
let p = app.prompt.as_ref().expect("the prompt stays open");
assert!(
p.error
.as_deref()
.is_some_and(|e| e.contains("profile name")),
"{:?}",
p.error
);
}
// ---- Inline AI suggestions (#607) ----
/// A one-shot fake `/v1/messages`: answers the first request with `text`
/// and hands back the raw request it read.
fn fake_messages_endpoint(text: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
use std::io::{Read, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let Ok((mut stream, _)) = listener.accept() else {
return;
};
let mut buf = Vec::new();
let mut chunk = [0u8; 8192];
// Headers, then as much body as Content-Length says.
loop {
let n = stream.read(&mut chunk).unwrap_or(0);
if n == 0 {
break;
}
buf.extend_from_slice(&chunk[..n]);
let s = String::from_utf8_lossy(&buf).to_string();
if let Some(h) = s.find("\r\n\r\n") {
let len = s[..h]
.lines()
.find_map(|l| {
l.to_ascii_lowercase()
.strip_prefix("content-length:")
.map(|v| v.trim().parse::<usize>().unwrap_or(0))
})
.unwrap_or(0);
if buf.len() >= h + 4 + len {
break;
}
}
}
let body = serde_json::json!({"stop_reason": "end_turn", "content": [{"type": "text", "text": text}]}).to_string();
let _ = write!(
stream,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{}",
body.len(),
body
);
let _ = tx.send(String::from_utf8_lossy(&buf).to_string());
});
(url, rx)
}
/// #614: a key typed after a suggestion was painted makes it stale; Right
/// before the echo arrives moves the cursor instead of typing the old
/// suggestion's rest after the new key.
#[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_failed_inline_suggestion_is_not_asked_again_until_the_caret_moves() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "let x = \n");
app.inline_config = Some(crate::inline_complete::Config {
backend: crate::inline_complete::Backend::Claude {
base_url: String::from("http://127.0.0.1:1"),
api_key: String::from("test-key"),
},
model: String::from("claude-opus-5"),
});
app.inline_worker = Some(crate::inline_complete::Worker::spawn());
app.inline_enabled = true;
app.editor.cursor_row = 0;
app.editor.cursor_col = 8;
app.editor.last_edit_at = Some(std::time::Instant::now() - std::time::Duration::from_secs(2));
let first = app.inline_next_id;
let deadline = std::time::Instant::now() + std::time::Duration::from_millis(500);
while std::time::Instant::now() < deadline {
app.tick_inline_complete();
std::thread::sleep(std::time::Duration::from_millis(5));
}
assert_eq!(app.inline_next_id - first, 1, "one request for one caret");
}
#[test]
fn an_inline_suggestion_appears_after_a_pause_and_tab_takes_it() {
let (url, requests) = fake_messages_endpoint("1 + 1;");
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "let x = \n");
app.inline_config = Some(crate::inline_complete::Config {
backend: crate::inline_complete::Backend::Claude {
base_url: url,
api_key: String::from("test-key"),
},
model: String::from("claude-opus-5"),
});
app.inline_worker = Some(crate::inline_complete::Worker::spawn());
app.inline_enabled = true;
app.editor.cursor_row = 0;
app.editor.cursor_col = 8;
app.editor.last_edit_at = Some(std::time::Instant::now() - std::time::Duration::from_secs(2));
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while app.editor.live_ghost().is_none() && std::time::Instant::now() < deadline {
app.tick_inline_complete();
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert_eq!(app.editor.live_ghost(), Some("1 + 1;"));
let req = requests
.recv_timeout(std::time::Duration::from_secs(5))
.unwrap();
assert!(req.contains("x-api-key: test-key"), "{req}");
assert!(req.contains("anthropic-version: 2023-06-01"));
assert!(
req.contains("let x = <CURSOR>"),
"the caret is marked: {req}"
);
app.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Tab,
KeyModifiers::NONE,
))
.unwrap();
assert_eq!(app.editor.lines[0], "let x = 1 + 1;");
assert!(app.editor.live_ghost().is_none());
}
#[test]
fn an_edit_makes_a_suggestion_stale_and_esc_dismisses_one() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "let x = \n");
app.editor.cursor_col = 8;
let seq = app.editor.edit_seq;
app.editor.ghost = Some((0, 8, seq, String::from("1;")));
assert!(app.editor.live_ghost().is_some());
app.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Esc,
KeyModifiers::NONE,
))
.unwrap();
assert!(app.editor.ghost.is_none(), "Esc dismisses");
app.editor.ghost = Some((0, 8, seq, String::from("1;")));
app.handle_key(crossterm::event::KeyEvent::new(
KeyCode::Char('2'),
KeyModifiers::NONE,
))
.unwrap();
assert!(app.editor.live_ghost().is_none(), "typing makes it stale");
}
/// A git repo holding `a.rs` and a fake `gh` that answers the review
/// calls (#366, #368): (tempdir, repo root, a.rs, gh's call log, the last
/// review payload, the gh script).
fn review_fixture() -> (
tempfile::TempDir,
std::path::PathBuf,
std::path::PathBuf,
std::path::PathBuf,
std::path::PathBuf,
std::path::PathBuf,
) {
use std::os::unix::fs::PermissionsExt as _;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("repo");
std::fs::create_dir(&root).unwrap();
for args in [
vec!["init", "-q", "-b", "main"],
vec!["config", "user.email", "a@b"],
vec!["config", "user.name", "a"],
] {
let _ = std::process::Command::new("git")
.arg("-C")
.arg(&root)
.args(&args)
.status();
}
let f = root.join("a.rs");
std::fs::write(&f, "fn a() {}\nfn b() {}\n").unwrap();
for args in [vec!["add", "."], vec!["commit", "-m", "init", "--quiet"]] {
let _ = std::process::Command::new("git")
.arg("-C")
.arg(&root)
.args(&args)
.status();
}
let log = tmp.path().join("gh.log");
let stdin = tmp.path().join("gh.stdin");
let gh = tmp.path().join("gh");
std::fs::write(
&gh,
format!(
r#"#!/bin/sh
echo "$@" >> '{log}'
case "$*" in
"pr view"*) echo 7 ;;
"pr diff"*) printf 'diff --git a/a.rs b/a.rs\n--- a/a.rs\n+++ b/a.rs\n@@ -1,1 +1,2 @@\n fn a() {{}}\n+fn b() {{}}\n' ;;
*graphql*reviewThreads*) echo '{{"data":{{"repository":{{"pullRequest":{{"reviewThreads":{{"nodes":[{{"id":"PRRT_1","isResolved":false,"comments":{{"nodes":[{{"databaseId":5}}]}}}}]}}}}}}}}}}' ;;
*graphql*) echo '{{}}' ;;
*"/comments --paginate"*) echo '[{{"id":5,"path":"a.rs","line":1,"user":{{"login":"ada"}},"body":"why?"}}]' ;;
*reviews*) cat > '{stdin}'; echo '{{}}' ;;
*) echo '{{}}' ;;
esac
"#,
log = log.display(),
stdin = stdin.display(),
),
)
.unwrap();
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
(tmp, root, f, log, stdin, gh)
}
/// An app on the review fixture, with git's view of the repo in place.
fn review_app(root: &std::path::Path, f: &std::path::Path, gh: &std::path::Path) -> App {
let mut app = App::new(root.to_path_buf()).unwrap();
app.review_gh = gh.display().to_string();
app.editor.open_pinned(f).unwrap();
crate::test_budget::await_spawned(
std::time::Duration::from_secs(5),
"git to find the repository",
|| {
app.git.drain_into(None);
app.git.status().repo_root.is_some()
},
);
app
}
/// #366's write side end to end against a fake `gh`: threads load with
/// their GraphQL resolution, a reply and a resolve go to GitHub off the
/// frame loop, and a pending comment is submitted with the chosen verdict.
#[test]
fn review_threads_can_be_replied_to_resolved_and_a_review_submitted() {
let (_tmp, root, f, log, stdin, gh) = review_fixture();
let mut app = review_app(&root, &f, &gh);
app.load_review_threads();
crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "the threads", || {
app.drain_review_ops();
app.review_boxes.is_some()
});
let threads = app.review_boxes.as_ref().map(|(_, t)| t.clone()).unwrap();
assert_eq!(threads.len(), 1);
assert!(!threads[0].resolved);
assert_eq!(app.review_nodes.get(&5).map(String::as_str), Some("PRRT_1"));
let wait_for = |app: &mut App, what: &str, done: &dyn Fn(&App) -> bool| {
crate::test_budget::await_spawned(std::time::Duration::from_secs(5), what, || {
app.drain_review_ops();
done(app)
});
};
app.editor.cursor_row = 0;
app.toggle_review_thread_resolved();
wait_for(&mut app, "the resolve", &|a| {
a.review_boxes.as_ref().is_some_and(|(_, t)| t[0].resolved)
});
assert!(app.reply_to_review_thread(5, "done"));
wait_for(&mut app, "the reply", &|a| {
a.review_boxes
.as_ref()
.is_some_and(|(_, t)| t[0].body.ends_with("you: done"))
});
app.editor.cursor_row = 1;
app.open_review_comment_prompt();
let rel = app.prompt.as_ref().unwrap().target_dir.clone();
app.prompt = None;
app.add_pending_review_comment("add a test", rel);
app.review_verdict = Some(crate::review_threads::ReviewEvent::RequestChanges);
app.submit_review(String::from("Close."));
wait_for(&mut app, "the review", &|a| a.review_pending.is_empty());
let sent: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&stdin).unwrap()).unwrap();
assert_eq!(sent["event"], "REQUEST_CHANGES");
assert_eq!(sent["comments"][0]["path"], "a.rs");
assert_eq!(sent["comments"][0]["line"], 2);
let calls = std::fs::read_to_string(&log).unwrap();
assert!(
calls.contains("pulls/7/comments/5/replies -f body=done"),
"{calls}"
);
assert!(calls.contains("resolveReviewThread"), "{calls}");
}
/// Pending comments belong to the PR they were written on: once the
/// branch's PR changes, they neither post there nor mix with new ones, and
/// a failed export settles none of the notes it carried.
#[test]
fn pending_comments_stay_with_their_pull_request() {
let (_tmp, root, f, _log, stdin, gh) = review_fixture();
let mut app = review_app(&root, &f, &gh);
app.editor.cursor_row = 0;
app.open_review_comment_prompt();
let rel = app.prompt.take().unwrap().target_dir;
app.add_pending_review_comment("on seven", rel.clone());
assert_eq!(app.review_pending.len(), 1);
// The branch now has another PR.
app.review_pr = Some((root.clone(), String::from("8")));
app.add_pending_review_comment("on eight", rel);
assert_eq!(app.review_pending.len(), 1, "not mixed in");
assert!(app.status.contains("PR #7"), "{}", app.status);
app.submit_review(String::from("LGTM"));
assert!(!stdin.exists(), "nothing posted to #8");
// A failed export keeps the navigator notes it carried.
app.review_pending.clear();
app.navigator_notes
.insert(String::from("a.rs"), vec![(1, 1, String::from("n"))]);
app.drain_review_ops();
app.review_tx
.send(crate::review_ops::Outcome::Failed(String::from("nope")))
.unwrap();
app.drain_review_ops();
app.review_tx
.send(crate::review_ops::Outcome::Submitted {
inline: 0,
folded: 0,
settles: crate::review_ops::Settles::default(),
})
.unwrap();
app.drain_review_ops();
assert_eq!(app.navigator_notes["a.rs"].len(), 1);
}
/// A failed reply or thread load while a review is being submitted does not
/// end the submission: only the submission's own answer does.
#[test]
fn only_the_submissions_own_failure_ends_it() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.review_submitting = true;
app.review_tx
.send(crate::review_ops::Outcome::Failed(String::from(
"Reply failed",
)))
.unwrap();
app.drain_review_ops();
assert!(app.review_submitting);
app.review_tx
.send(crate::review_ops::Outcome::SubmitFailed(String::from("no")))
.unwrap();
app.drain_review_ops();
assert!(!app.review_submitting);
}
/// #368: the navigator's notes and pending comments are previewed, then
/// posted as one review with the navigator's marked as AI-authored; a note
/// off the diff lands in the summary, and posted notes leave the editor.
#[test]
fn comments_export_to_the_pull_request_after_a_preview() {
let (_tmp, root, f, log, stdin, gh) = review_fixture();
let mut app = review_app(&root, &f, &gh);
app.navigator_notes.insert(
String::from("a.rs"),
vec![
(1, 1, String::from("b is unused")),
(2, 40, String::from("far")),
],
);
app.review_pending
.push(crate::review_threads::PendingComment {
path: String::from("a.rs"),
line: 0,
body: String::from("mine"),
});
app.open_export_comments();
crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "the preview", || {
app.drain_review_ops();
app.list_picker.is_some()
});
let picker = app.list_picker.as_ref().expect("the preview is shown");
assert_eq!(
picker.rows[0].label,
"Post to PR #7: 2 inline, 1 in the summary"
);
assert_eq!(picker.rows.len(), 4);
// A thread load answering for another PR meanwhile does not redirect
// the post away from the PR the preview named.
app.review_pr = Some((root.clone(), String::from("8")));
app.post_exported_comments();
crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "the post", || {
app.drain_review_ops();
app.navigator_notes.get("a.rs").is_some_and(Vec::is_empty)
});
let sent: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&stdin).unwrap()).unwrap();
assert_eq!(sent["event"], "COMMENT");
let bodies: Vec<&str> = sent["comments"]
.as_array()
.unwrap()
.iter()
.map(|c| c["body"].as_str().unwrap())
.collect();
assert_eq!(bodies, vec!["mine", "[AI, croft navigator] b is unused"]);
assert!(
sent["body"]
.as_str()
.unwrap()
.contains("`a.rs:41`: [AI, croft navigator] far")
);
assert!(app.review_pending.is_empty());
let log = std::fs::read_to_string(&log).unwrap();
assert!(
log.contains("pulls/7/reviews") && !log.contains("pulls/8/"),
"{log}"
);
}
/// #367: a sticky note hangs under its line as a box, follows the line when
/// lines are added above, takes replies, resolves from its ✕, is counted in
/// the Explorer while open, and is reached by F4.
#[test]
fn a_sticky_note_is_a_box_that_follows_its_line_and_takes_replies() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("a.rs");
std::fs::write(&f, "fn a() {}\nfn b() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.editor.cursor_row = 1;
app.open_sticky_note_prompt();
assert!(matches!(
app.prompt.as_ref().map(|p| &p.kind),
Some(PromptKind::StickyNote)
));
app.prompt = None;
app.add_sticky_note("why b?");
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|fr| app.render(fr)).unwrap();
let b = app
.editor
.comment_boxes
.iter()
.find(|b| b.body == "why b?")
.cloned()
.expect("the note is drawn as a box");
assert_eq!(b.line, 1);
assert_eq!(
app.tree.note_counts.get(&f).copied(),
Some(1),
"the Explorer counts it"
);
// Two lines land above it: the box follows fn b.
app.editor.lines.insert(0, String::from("// one"));
app.editor.lines.insert(0, String::from("// two"));
term.draw(|fr| app.render(fr)).unwrap();
let moved = app
.editor
.comment_boxes
.iter()
.find(|x| x.id == b.id)
.unwrap();
assert_eq!(moved.line, 3);
app.editor.cursor_row = 0;
assert_eq!(app.next_comment_from_caret().map(|(id, _)| id), Some(b.id));
app.editor.comment_focus = Some(crate::widgets::editor::CommentFocus {
id: b.id,
reply: String::from("it is used"),
cursor: 0,
});
app.submit_comment_reply();
app.ignore_comment_box(b.id);
term.draw(|fr| app.render(fr)).unwrap();
let after = app
.editor
.comment_boxes
.iter()
.find(|x| x.id == b.id)
.unwrap();
assert!(after.body.ends_with(": it is used"), "{}", after.body);
assert!(after.author.ends_with("resolved"));
assert!(
app.tree.note_counts.is_empty(),
"a resolved note isn't counted"
);
app.editor.comment_focus = None;
app.editor.cursor_row = 0;
app.delete_sticky_note_here();
term.draw(|fr| app.render(fr)).unwrap();
assert!(!app.editor.comment_boxes.iter().any(|x| x.id == b.id));
}
/// A test-built App never reads the developer's own settings layers: a
/// preference in the real `config.json` (say, the TIMELINE hidden) must not
/// steer app tests. Workspace layers under the test root still load.
#[test]
fn a_test_built_app_reads_no_user_settings_layer() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let user_dir = crate::prefs::config_dir();
// At startup and again on a live settings reload.
for when in ["startup", "reload"] {
if when == "reload" {
app.remerge_settings();
}
let leaked: Vec<_> = app
.settings_chain
.iter()
.filter(|p| p.starts_with(&user_dir))
.collect();
assert!(
leaked.is_empty(),
"{when}: user layers read under test: {leaked:?}"
);
assert!(
app.settings_chain
.contains(&crate::config_layers::workspace_config_path(tmp.path())),
"{when}: the workspace layer must still load: {:?}",
app.settings_chain
);
assert!(
app.settings_provenance.values().all(|k| !matches!(
k,
crate::config_layers::LayerKind::User | crate::config_layers::LayerKind::UserLocal
)),
"{when}: a setting came from a user layer: {:?}",
app.settings_provenance
);
}
}
/// #624 review: the tool trust gate refuses a changed tool definition with
/// the recovery it names, and lets the first and the unchanged one through.
#[test]
fn the_mcp_tool_gate_refuses_a_changed_definition() {
let tmp = tempfile::tempdir().unwrap();
assert_eq!(mcp_tool_trust(tmp.path(), "ext.go", "go", "fp1"), Ok(()));
assert_eq!(mcp_tool_trust(tmp.path(), "ext.go", "go", "fp1"), Ok(()));
let err = mcp_tool_trust(tmp.path(), "ext.go", "go", "fp2").unwrap_err();
assert!(err.starts_with("refusing to run: the 'go' tool"), "{err}");
assert!(err.contains("toggle the extension off and on"), "{err}");
}
/// #624 review: toggling an extension off and on re-approves its tools, as
/// the refusal says: turning it off forgets the fingerprints of the
/// commands it declares, and only those, so the next run trusts afresh.
#[test]
fn toggling_an_extension_off_forgets_its_tool_fingerprints() {
const EXT: &str = r#"
id = "tfp"
name = "tfp"
api_version = 1
[[mcp_servers]]
id = "srv"
command = "/bin/false"
[[commands]]
id = "tfp.go"
title = "tfp: go"
server = "srv"
tool = "go"
"#;
let other = EXT.replace("tfp", "oth");
let (_scratch, croft) = scratch_config(&[("tfp", EXT), ("oth", &other)]);
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.config_dir = croft.clone();
// The panel lists the real user dir; seat the scratch extension's row.
// A toggle refreshes the panel from that dir, so re-seat before each.
let toggle_tfp = |app: &mut App| {
app.extensions
.set_items(crate::widgets::extensions::items_from_summaries(
crate::lsp::manifest::summaries(&[EXT]),
&app.disabled_extensions,
));
let visible = app.extensions.visible_indices();
let pos = visible
.iter()
.position(|&i| app.extensions.items()[i].id == "tfp")
.expect("the tfp row is visible");
app.extensions.select(pos);
app.toggle_selected_extension();
};
assert!(crate::prefs::trust_mcp_tool_in(&croft, "tfp.go", "fp1"));
assert!(crate::prefs::trust_mcp_tool_in(&croft, "oth.go", "o1"));
toggle_tfp(&mut app);
assert!(app.disabled_extensions.contains("tfp"), "{}", app.status);
assert!(
crate::prefs::trust_mcp_tool_in(&croft, "tfp.go", "fp2"),
"the changed tool is approved afresh"
);
assert!(
!crate::prefs::trust_mcp_tool_in(&croft, "oth.go", "o2"),
"another extension's record stays"
);
// Turning it back on keeps the new record: a further change is refused.
toggle_tfp(&mut app);
assert!(!app.disabled_extensions.contains("tfp"), "{}", app.status);
assert!(!crate::prefs::trust_mcp_tool_in(&croft, "tfp.go", "fp3"));
}
/// Uninstalling an extension forgets its tools' fingerprints, so a re-added
/// newer version approves its tools afresh instead of being refused.
#[test]
fn uninstalling_an_extension_forgets_its_tool_fingerprints() {
// Only a catalog entry uninstalls, so the fixture is the bundled Time
// sidecar beside a hand-added extension whose record must stay.
const TIME: &str = include_str!("../../assets/catalog/mcp-time/extension.toml");
const OTH: &str = r#"
id = "oth"
name = "oth"
api_version = 1
[[mcp_servers]]
id = "srv"
command = "/bin/false"
[[commands]]
id = "oth.go"
title = "oth: go"
server = "srv"
tool = "go"
"#;
let (_scratch, croft) = scratch_config(&[("mcp-time", TIME), ("oth", OTH)]);
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.config_dir = croft.clone();
assert!(crate::prefs::trust_mcp_tool_in(&croft, "time.now", "fp1"));
assert!(crate::prefs::trust_mcp_tool_in(&croft, "oth.go", "o1"));
app.perform_extension_uninstall("mcp-time");
assert!(app.status.starts_with("Uninstalled"), "{}", app.status);
assert!(
crate::prefs::trust_mcp_tool_in(&croft, "time.now", "fp2"),
"the re-added tool is approved afresh"
);
assert!(
!crate::prefs::trust_mcp_tool_in(&croft, "oth.go", "o2"),
"another extension's record stays"
);
}
#[test]
fn a_homebrew_install_is_offered_brew_upgrade_not_a_self_update() {
// The cache-dir override is process-global; serialize with the
// other tests that redirect it.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
// #375: a binary inside Homebrew's Cellar must not be rebuilt or swapped
// by croft: the popup names `brew upgrade croft` and has no Update.
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.install_source = crate::update_check::InstallSource::Homebrew;
app.update_check = Some(crate::update_check::UpdateCheck::preloaded(Some(
"9.9.9".into(),
)));
assert!(app.poll_update_watch());
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 50)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buttons = app.update_toast.as_ref().unwrap().buttons.clone();
assert!(
!buttons
.iter()
.any(|(_, a)| matches!(a, super::UpdateToastAction::Update)),
"no Update button on a Homebrew install"
);
assert!(
buttons
.iter()
.any(|(_, a)| matches!(a, super::UpdateToastAction::Later)),
"Later still dismisses the offer"
);
let buf = term.backend().buffer();
let mut screen = String::new();
for y in 0..buf.area.height {
for x in 0..buf.area.width {
screen.push_str(buf[(x, y)].symbol());
}
}
assert!(
screen.contains("brew upgrade croft"),
"the popup names the command to run"
);
// Even a direct request cannot stage a build over the Cellar.
app.start_staged_update("9.9.9".into());
assert!(app.staged_install.is_none(), "nothing staged");
assert!(app.status.contains("brew upgrade croft"), "{}", app.status);
});
}
#[test]
fn a_self_managed_install_still_offers_update() {
// The cache-dir override is process-global; serialize with the
// other tests that redirect it.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
assert_eq!(
app.install_source,
crate::update_check::InstallSource::SelfManaged,
"a test binary under target/ is not Homebrew-owned"
);
});
}
const EXITED_EVENT: &str = r#"{"seq":1,"type":"event","event":"exited","body":{"exitCode":0}}"#;
const TERMINATED_EVENT: &str = r#"{"seq":2,"type":"event","event":"terminated"}"#;
/// Adapters send `exited` and then `terminated`, both of which end a member.
/// Arriving in one poll they named the member twice, and the second removal
/// took a live sibling with it.
#[test]
fn a_member_that_exits_and_terminates_in_one_poll_is_removed_once() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.debug_sessions
.push("A", stub_emitting(&[EXITED_EVENT, TERMINATED_EVENT]));
app.debug_sessions.push("B", stub_member(false));
app.debug_sessions.push("C", stub_member(false));
app.debug_sessions.focus(2);
// Both messages are written before the first poll reads them.
std::thread::sleep(std::time::Duration::from_millis(300));
poll_until(&mut app, |a| {
!a.debug_sessions.names().contains(&String::from("A"))
});
assert_eq!(
app.debug_sessions.names(),
vec![String::from("B"), String::from("C")]
);
app.debug_stop();
}
/// The focused member ending in the same poll a background member stops: the
/// view used to move to the stopped member first, carrying the ending with it
/// into the old member's backlog, so the ended member was never removed.
#[test]
fn a_focused_member_that_ends_as_another_stops_is_still_removed() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.debug_sessions
.push("S", stub_emitting(&[STOPPED_EVENT]));
app.debug_sessions
.push("F", stub_emitting(&[TERMINATED_EVENT]));
app.debug_sessions.focus(1);
std::thread::sleep(std::time::Duration::from_millis(300));
poll_until(&mut app, |a| {
a.debug_sessions.names() == vec![String::from("S")]
});
assert_eq!(
app.debug_sessions.names(),
vec![String::from("S")],
"F ended and must go"
);
app.debug_stop();
}
/// #679: outside a persistent session there is nothing to detach from,
/// and saying so beats a chord that silently does nothing.
#[test]
fn session_detach_outside_a_session_says_there_is_nothing_to_detach_from() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.session_channel = None;
app.run_command(crate::widgets::command_palette::Command::SessionDetach);
assert_eq!(
app.status,
"Not attached to a persistent session: nothing to detach from"
);
}
/// #678: Claude Code (or tmux, nvim) copying a selection through OSC 52 in
/// a croft pane must land where croft's own copy lands. Dropping it broke
/// copy on a remote box, where OSC 52 is the program's only clipboard.
#[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");
// "Y29waWVk" is "copied"; the empty store first is a program clearing
// the clipboard at startup and must not wipe it.
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");
// The empty store has no visible output to wait on, so give it the
// same budget the real copy gets and require that nothing changed.
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
);
}
/// #682: the fingerprint under an image changes with any write ratatui
/// makes inside it, and ignores writes outside it.
#[test]
fn the_cells_under_an_image_fingerprint_writes_inside_it_only() {
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 10));
let before = super::cells_fingerprint(&buf, 2, 2, 5, 3);
buf[(15, 8)].set_symbol("x");
assert_eq!(super::cells_fingerprint(&buf, 2, 2, 5, 3), before);
buf[(3, 3)].set_symbol("x");
assert_ne!(super::cells_fingerprint(&buf, 2, 2, 5, 3), before);
// A rectangle past the edge is clamped, not a panic.
let _ = super::cells_fingerprint(&buf, 18, 8, 10, 10);
}
/// On Kitty an image lives on its own layer, so text redrawn beneath it
/// never makes croft resend it; on iTerm2 it does.
#[test]
fn only_cell_buffer_protocols_resend_an_image_when_text_beneath_changes() {
use crate::iterm2_inline::InlineImageProtocol;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.terminal_image.set(
String::from("img"),
super::TerminalImageLayout {
cell_x: 1,
cell_y: 1,
cell_w: 4,
cell_h: 2,
seq: 0,
pane: 0,
},
);
let quiet = Buffer::empty(Rect::new(0, 0, 10, 5));
let mut busy = quiet.clone();
busy[(2, 1)].set_symbol("x");
app.inline_protocol = InlineImageProtocol::ITerm2;
assert_ne!(
app.image_underlays(&quiet).terminal,
app.image_underlays(&busy).terminal
);
app.inline_protocol = InlineImageProtocol::Kitty;
assert_eq!(
app.image_underlays(&quiet).terminal,
app.image_underlays(&busy).terminal
);
}
/// #682: typing re-bakes the minimap at most every `MINIMAP_EDIT_REBAKE`,
/// and the deferred bake still lands once the wait is over.
#[test]
fn minimap_rebakes_for_typing_at_most_every_few_hundred_ms() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.cell_pixel = Some((8, 16));
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
app.editor.lines = (0..80).map(|i| format!("line {i}")).collect();
let strip = ratatui::layout::Rect {
x: 100,
y: 1,
width: 6,
height: 40,
};
app.update_minimap_overlay(strip);
let first = app.minimap_image_payload().map(|(o, _)| o.to_string());
assert!(first.is_some());
app.editor.lines[0] = String::from("changed");
app.editor.edit_seq += 1;
app.update_minimap_overlay(strip);
assert_eq!(
app.minimap_image_payload().map(|(o, _)| o.to_string()),
first,
"a keystroke right after a bake waits"
);
assert!(!app.tick_minimap(), "not due yet");
app.minimap_baked_at = Some(std::time::Instant::now() - super::MINIMAP_EDIT_REBAKE);
assert!(app.tick_minimap(), "the wait is over: redraw");
assert!(
!app.tick_minimap(),
"one redraw per deferred bake, even if the minimap is gone by then"
);
app.update_minimap_overlay(strip);
assert_ne!(
app.minimap_image_payload().map(|(o, _)| o.to_string()),
first,
"the deferred edit is baked"
);
assert!(!app.tick_minimap());
// Scrolling is not held back.
app.editor.scroll = 5;
let before = app.minimap_image_payload().map(|(o, _)| o.to_string());
app.update_minimap_overlay(strip);
assert_ne!(
app.minimap_image_payload().map(|(o, _)| o.to_string()),
before
);
}
/// #682: only iTerm2 needs the idle icon keepalive.
#[test]
fn only_iterm2_keeps_the_activity_icons_alive() {
use crate::iterm2_inline::InlineImageProtocol;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for (p, want) in [
(InlineImageProtocol::ITerm2, true),
(InlineImageProtocol::Kitty, false),
(InlineImageProtocol::Sixel, false),
] {
app.inline_protocol = p;
assert_eq!(app.activity_keepalive_allowed(), want, "{p:?}");
}
}
/// #682: the minimap PNG is compressed hard; a typical strip encodes to a
/// fraction of its default size.
#[test]
fn the_minimap_png_is_small() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.lines = (0..400)
.map(|i| format!(" let value_{i} = compute(a, b, {i}); // note"))
.collect();
let (w, h) = (6 * 9, 45 * 18);
let rgba = app
.editor
.minimap_rgba(w, h, h, (30, 30, 30), (200, 200, 200));
let png = super::rgba_to_png(rgba, w, h).unwrap();
assert!(png.len() < 1500, "{} bytes", png.len());
assert!(image::load_from_memory(&png).is_ok());
}
/// #682: small chrome images go out when new, changed, moved, back from
/// hiding, or (iTerm2) repainted around; not on every frame.
#[test]
fn a_chrome_image_is_sent_only_when_it_could_be_missing() {
use crate::iterm2_inline::InlineImageProtocol;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let at = Rect::new(2, 2, 3, 1);
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 10));
app.drawn_buffer = Some(buf.clone());
app.inline_protocol = InlineImageProtocol::ITerm2;
assert!(app.chrome_image_due("k", "img", at), "new");
app.end_chrome_flush();
assert!(!app.chrome_image_due("k", "img", at), "unchanged frame");
app.end_chrome_flush();
assert!(app.chrome_image_due("k", "img2", at), "changed");
assert!(
app.chrome_image_due("k", "img2", Rect::new(3, 2, 3, 1)),
"moved"
);
app.end_chrome_flush();
buf[(2, 2)].set_symbol("x");
app.drawn_buffer = Some(buf.clone());
assert!(
app.chrome_image_due("k", "img2", Rect::new(3, 2, 3, 1)),
"a neighbour repainted on iTerm2"
);
app.end_chrome_flush();
app.end_chrome_flush();
assert!(
app.chrome_image_due("k", "img2", Rect::new(3, 2, 3, 1)),
"back after a frame hidden"
);
app.end_chrome_flush();
app.inline_protocol = InlineImageProtocol::Kitty;
assert!(app.chrome_image_due("k", "img2", Rect::new(3, 2, 3, 1)));
app.end_chrome_flush();
buf[(2, 3)].set_symbol("y");
app.drawn_buffer = Some(buf);
assert!(
!app.chrome_image_due("k", "img2", Rect::new(3, 2, 3, 1)),
"Kitty ignores neighbours"
);
}
/// A PROBLEMS count that goes to zero clears the screen only if a badge was
/// drawn: start-up and graphics re-inits no longer wipe the screen.
#[test]
fn a_zero_problem_count_clears_nothing_when_no_badge_was_drawn() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays
.activity
.set_images(super::ActivityBarImages::default());
app.problems_badge_count = usize::MAX;
app.refresh_problems_badge();
assert!(!app.consume_problems_badge_image_clear());
}
/// A comment written while a review is being submitted stays pending, and a
/// second submit while the first runs is refused rather than posted twice.
#[test]
fn a_submit_in_flight_keeps_new_comments_and_refuses_a_second_submit() {
let (_tmp, root, f, _log, _stdin, gh) = review_fixture();
let mut app = review_app(&root, &f, &gh);
app.editor.cursor_row = 0;
app.open_review_comment_prompt();
let rel = app.prompt.take().unwrap().target_dir;
app.add_pending_review_comment("first", rel.clone());
app.submit_review(String::from("Looks good"));
assert!(app.review_submitting);
app.editor.cursor_row = 1;
app.add_pending_review_comment("written meanwhile", rel);
app.submit_review(String::from("again"));
assert!(app.status.contains("already"), "{}", app.status);
crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "the submit", || {
app.drain_review_ops();
!app.review_submitting
});
let left: Vec<_> = app.review_pending.iter().map(|c| c.body.clone()).collect();
assert_eq!(left, vec![String::from("written meanwhile")]);
}
/// Queue an agent's `Edit` of `file` (`old` -> `new`) through the hook
/// socket, as Claude Code's hook would; the returned stream is the hook's
/// end, kept open for the answer.
fn queue_edit_proposal(
app: &mut App,
dir: &Path,
file: &Path,
old: &str,
new: &str,
) -> std::os::unix::net::UnixStream {
use std::io::Write;
let sock = dir.join("hook.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
listener.set_nonblocking(true).unwrap();
app.hook_listener = Some(listener);
let mut hook = std::os::unix::net::UnixStream::connect(&sock).unwrap();
let req = crate::agent_hook::EditRequest {
agent: "claude-code".into(),
tool: "Edit".into(),
input: serde_json::json!({"file_path": file, "old_string": old, "new_string": new}),
cwd: dir.into(),
};
writeln!(hook, "{}", serde_json::to_string(&req).unwrap()).unwrap();
assert!(app.drain_hook_requests());
hook
}
fn popup_screen(app: &mut App, w: u16, h: u16) -> String {
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(w, h)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let mut screen = String::new();
for y in 0..h {
for x in 0..w {
screen.push_str(term.backend().buffer()[(x, y)].symbol());
}
screen.push('\n');
}
screen
}
/// #347: what the language server says about a proposal's file while it is
/// checked goes to the popup, against the proposed row it names, and not to
/// the buffer's diagnostics; answering the proposal ends the check.
#[test]
fn a_proposals_diagnostics_show_in_the_popup_not_the_buffer() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("a.py");
std::fs::write(&file, "x = 1\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.lsp = None;
let _hook = queue_edit_proposal(&mut app, tmp.path(), &file, "1", "nope_undefined");
app.sync_approval_check();
assert!(
app.approval_check.is_none(),
"no server, nothing to check with"
);
// As a server would once the proposal's text was sent as the file's.
app.approval_check = Some(crate::agent_approval::ProposalCheck {
arrived: app.approvals[0].arrived,
started: std::time::Instant::now(),
path: file.clone(),
opened: true,
by_server: Default::default(),
});
let screen = popup_screen(&mut app, 110, 30);
assert!(screen.contains("Checking the proposed file"), "{screen}");
app.apply_diagnostics_updates(vec![crate::lsp::manager::DiagnosticsUpdate {
path: file.clone(),
server: "ruff".into(),
diagnostics: vec![crate::lsp::manager::Diagnostic {
start_line: 0,
start_char: 4,
end_line: 0,
end_char: 18,
severity: crate::lsp::manager::DiagnosticSeverity::Error,
message: "Undefined name `nope_undefined`".into(),
}],
}]);
assert!(
!app.lsp_diagnostics.contains_key(&file),
"the buffer's diagnostics are the buffer's"
);
let screen = popup_screen(&mut app, 110, 30);
assert!(
screen.contains("1 error, 0 warnings in the proposed file"),
"{screen}"
);
assert!(
screen
.lines()
.any(|l| l.contains("+ x = nope_undefined") && l.contains("\u{25c0} Undefined name")),
"the proposed row carries it: {screen}"
);
// Answered: the check ends with the proposal.
app.approval_ui.as_mut().unwrap().shown_at -= crate::agent_approval::ARM_DELAY;
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(app.approvals.is_empty());
app.sync_approval_check();
assert!(app.approval_check.is_none());
}
/// #347's criterion against a real server: a proposal that uses an
/// undefined name shows the server's diagnostic in the popup before it is
/// approved. Ignored by default: it needs a Python language server that
/// publishes diagnostics for an open buffer (run it with `--ignored` where
/// one does); `a_proposals_diagnostics_show_in_the_popup_not_the_buffer`
/// covers the routing and rendering without one.
#[test]
#[ignore]
fn a_real_server_flags_the_proposal_before_approval() {
if !["ruff", "pyright-langserver", "basedpyright-langserver"]
.iter()
.any(|b| crate::lsp::manager::is_on_path(b))
{
eprintln!("SKIPPED: no Python language server on PATH");
return;
}
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("a.py");
std::fs::write(&file, "x = 1\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
if app.lsp.is_none() {
eprintln!("SKIPPED: no language server manager");
return;
}
let _hook = queue_edit_proposal(&mut app, tmp.path(), &file, "1", "nope_undefined");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
loop {
app.sync_approval_check();
app.drain_lsp_diagnostics();
let found = app.approval_check.as_ref().is_some_and(|c| {
c.diagnostics()
.iter()
.any(|d| d.message.contains("nope_undefined"))
});
if found {
break;
}
assert!(
std::time::Instant::now() < deadline,
"no server flagged the proposal: {:?}",
app.approval_check
);
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert!(!app.lsp_diagnostics.contains_key(&file));
}
/// An agent's edit proposal, end to end through the App: the hook's
/// request opens the popup over everything, keys go to the popup and not
/// to the editor under it, and the answer reaches the hook's connection.
#[test]
fn an_agent_edit_proposal_opens_the_popup_and_enter_answers_the_hook() {
use std::io::{BufRead, Write};
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("a.rs");
std::fs::write(&file, "let x = 1;\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let sock = tmp.path().join("hook.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
listener.set_nonblocking(true).unwrap();
app.hook_listener = Some(listener);
assert!(!app.drain_hook_requests());
assert!(app.approval_ui.is_none());
let mut hook = std::os::unix::net::UnixStream::connect(&sock).unwrap();
let req = crate::agent_hook::EditRequest {
agent: "claude-code".into(),
tool: "Edit".into(),
input: serde_json::json!({"file_path": file, "old_string": "1", "new_string": "2"}),
cwd: tmp.path().into(),
};
writeln!(hook, "{}", serde_json::to_string(&req).unwrap()).unwrap();
assert!(app.drain_hook_requests());
assert!(app.modal_overlay_open());
// A proposal the hook has stopped waiting for leaves with the popup.
app.approvals[0].arrived -= crate::agent_hook::ANSWER_WINDOW;
assert!(app.drain_hook_requests());
assert!(app.approval_ui.is_none() && app.approvals.is_empty());
let mut hook = std::os::unix::net::UnixStream::connect(&sock).unwrap();
writeln!(hook, "{}", serde_json::to_string(&req).unwrap()).unwrap();
assert!(app.drain_hook_requests());
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let mut screen = String::new();
for y in 0..30 {
for x in 0..100 {
screen.push_str(term.backend().buffer()[(x, y)].symbol());
}
}
assert!(
screen.contains("claude-code wants to edit a.rs"),
"{screen}"
);
assert!(screen.contains("+ let x = 2;") && screen.contains("- let x = 1;"));
// Too soon after it appeared: the Enter is swallowed, not an approval.
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(app.approval_ui.is_some());
app.approval_ui.as_mut().unwrap().shown_at -= crate::agent_approval::ARM_DELAY;
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(app.approval_ui.is_none() && app.approvals.is_empty());
let mut line = String::new();
std::io::BufReader::new(hook).read_line(&mut line).unwrap();
assert_eq!(
serde_json::from_str::<crate::agent_hook::Decision>(line.trim()).unwrap(),
crate::agent_hook::Decision::Allow
);
// Approving answers the agent; croft itself does not write the file.
assert_eq!(std::fs::read_to_string(&file).unwrap(), "let x = 1;\n");
}
/// #345: the AGENT LANE rows are each agent then its files, unreviewed
/// first, labelled relative to the workspace root.
#[test]
fn agent_lane_rows_list_each_agent_then_its_files_unreviewed_first() {
use crate::widgets::agent_lane::LaneRow;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::create_dir_all(root.join("src")).unwrap();
let a = root.join("src/a.rs");
let b = root.join("src/b.rs");
std::fs::write(&a, "a").unwrap();
std::fs::write(&b, "b").unwrap();
let mut app = App::new(root.clone()).unwrap();
assert!(
app.agent_lane_panel_rows().is_empty(),
"nothing to show before any agent wrote"
);
let working = vec![String::from("claude")];
app.agent_ledger.record_write(&a, 1, &working);
app.agent_ledger.record_write(&b, 2, &working);
app.agent_ledger.mark_reviewed("claude", &a, 1, None);
let rows = app.agent_lane_panel_rows();
assert_eq!(
rows[0],
LaneRow::Agent {
name: String::from("claude"),
unreviewed: 1
}
);
let files: Vec<(String, bool)> = rows[1..]
.iter()
.map(|r| match r {
LaneRow::File {
label, unreviewed, ..
} => (label.clone(), *unreviewed),
other => panic!("expected a file row, got {other:?}"),
})
.collect();
assert_eq!(
files,
vec![
(String::from("src/b.rs"), true),
(String::from("src/a.rs"), false)
]
);
}
/// #345: "Agents: Open Agent Lane" shows the section, open, even after it
/// was hidden from the ⋯ menu; with no agent activity it says so instead.
#[test]
fn agents_open_agent_lane_shows_the_section_open() {
use crate::widgets::command_palette::Command;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let f = root.join("x.rs");
std::fs::write(&f, "x").unwrap();
let mut app = App::new(root).unwrap();
app.run_command(Command::OpenAgentLaneSection);
assert!(app.status.contains("no agent"), "status: {}", app.status);
app.agent_ledger
.record_write(&f, 1, &[String::from("claude")]);
if app.explorer_views.is_visible(ExplorerView::AgentLane) {
app.toggle_explorer_view(ExplorerView::AgentLane);
}
assert!(app.agent_lane_panel.collapsed);
app.run_command(Command::OpenAgentLaneSection);
assert!(app.explorer_views.is_visible(ExplorerView::AgentLane));
assert!(!app.agent_lane_panel.collapsed);
assert_eq!(app.sidebar_view, SidebarView::Explorer);
}
#[test]
fn provisioning_outcomes_are_logged_to_the_remote_output_channel() {
// The cache-dir override is process-global; serialize with the
// other tests that redirect it.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
// #364: a host that gets croft through provisioning says so in OUTPUT >
// Remote, success and failure alike, with the reason on failure.
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.note_provisioning_failed("zz364-a.example", "no space left on device");
app.note_provisioning_succeeded("zz364-b.example");
let lines = crate::output::snapshot(crate::output::CHANNEL_REMOTE)
.expect("the Remote channel exists");
let failed = lines
.iter()
.find(|l| l.text.contains("zz364-a.example"))
.expect("the failure is logged");
assert!(
failed.text.contains("no space left on device"),
"{}",
failed.text
);
assert_eq!(failed.level, crate::output::OutputLevel::Error);
assert!(
lines.iter().any(|l| l.text.contains("zz364-b.example")
&& l.level != crate::output::OutputLevel::Error),
"the success is logged"
);
});
}
/// A repo whose `a.txt` grows by one line per commit: v1, then v1+v2, then
/// v1+v2+v3.
fn scrub_repo() -> tempfile::TempDir {
let tmp = tempfile::tempdir().unwrap();
let git = |args: &[&str]| {
let ok = std::process::Command::new("git")
.arg("-C")
.arg(tmp.path())
.args(args)
.output()
.unwrap()
.status
.success();
assert!(ok, "git {args:?}");
};
git(&["init", "-q", "-b", "main"]);
git(&["config", "user.email", "a@b"]);
git(&["config", "user.name", "a"]);
let mut text = String::new();
for v in ["v1", "v2", "v3"] {
text.push_str(v);
text.push('\n');
std::fs::write(tmp.path().join("a.txt"), &text).unwrap();
git(&["add", "a.txt"]);
git(&["commit", "-q", "-m", v]);
}
tmp
}
/// Wait for the OUTLINE to show the scrubbed commit's own symbols (#371),
/// which the builder parses on its own thread with the finished view.
fn settle_scrub_outline(app: &mut App) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
loop {
app.drain_scrub_views();
app.sync_outline();
let commit = app
.scrubber
.as_ref()
.and_then(|s| s.commit())
.map(|c| c.hash.clone());
if commit.is_some() && app.outline_scrub_key.as_ref().map(|(_, c)| c.clone()) == commit {
return;
}
assert!(
std::time::Instant::now() < deadline,
"the scrubbed commit's outline was never built"
);
std::thread::sleep(std::time::Duration::from_millis(5));
}
}
/// Wait for the history scrubber's finished view of where it stands to
/// replace the plain stand-in (#371); the builder runs on its own thread.
fn settle_scrub_view(app: &mut App) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while !matches!(app.scrub_view_key, Some((_, true))) {
assert!(
std::time::Instant::now() < deadline,
"the scrubber's view was never built"
);
app.drain_scrub_views();
std::thread::sleep(std::time::Duration::from_millis(5));
}
}
#[test]
fn stepping_back_to_a_finished_scrub_view_reuses_it() {
// #371: a step never waits on highlighting, and a commit whose view was
// already built shows it at once rather than building it again.
let repo = scrub_repo();
let mut app = App::new(repo.path().to_path_buf()).unwrap();
app.editor.open(&repo.path().join("a.txt")).unwrap();
app.scrub_history();
assert!(app.handle_scrubber_key(KeyCode::Left), "to HEAD");
settle_scrub_view(&mut app);
assert!(app.handle_scrubber_key(KeyCode::Left), "one older");
settle_scrub_view(&mut app);
assert!(app.handle_scrubber_key(KeyCode::Right), "back to HEAD");
assert!(
matches!(app.scrub_view_key, Some((_, true))),
"HEAD's finished view was kept"
);
assert_eq!(
app.scrub_view.as_ref().unwrap().lines,
vec!["v1", "v2", "v3"]
);
// Home drops the view; Esc drops the kept ones with the builder.
assert!(app.handle_scrubber_key(KeyCode::Home));
assert!(app.scrub_view.is_none() && app.scrub_view_key.is_none());
assert!(app.handle_scrubber_key(KeyCode::Esc));
assert!(app.scrub_views.is_empty() && app.scrub_builder.is_none());
}
#[test]
fn scrubbing_shows_the_file_at_each_commit_and_its_changes() {
// #371: at each position the editor shows the file at that commit, and
// the git gutter shows that commit's own change.
let repo = scrub_repo();
let mut app = App::new(repo.path().to_path_buf()).unwrap();
app.editor.open(&repo.path().join("a.txt")).unwrap();
app.scrub_history();
assert!(app.handle_scrubber_key(KeyCode::Left), "to HEAD");
settle_scrub_view(&mut app);
let view = app.scrub_view.as_mut().expect("a historical view at HEAD");
assert_eq!(view.lines, vec!["v1", "v2", "v3"]);
assert_eq!(
view.git_mark_at(2),
Some(crate::widgets::editor::GitMark::Added)
);
assert_eq!(view.git_mark_at(1), None, "unchanged in that commit");
assert!(app.handle_scrubber_key(KeyCode::Left), "one older");
settle_scrub_view(&mut app);
let view = app.scrub_view.as_mut().unwrap();
assert_eq!(view.lines, vec!["v1", "v2"]);
assert_eq!(
view.git_mark_at(1),
Some(crate::widgets::editor::GitMark::Added)
);
assert!(app.handle_scrubber_key(KeyCode::Left), "the root commit");
settle_scrub_view(&mut app);
let view = app.scrub_view.as_mut().unwrap();
assert_eq!(view.lines, vec!["v1"]);
assert_eq!(
view.git_mark_at(0),
Some(crate::widgets::editor::GitMark::Added),
"a root commit adds every line"
);
// Painted in place of the live buffer.
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let mut screen = String::new();
for y in 0..buf.area.height {
for x in 0..buf.area.width {
screen.push_str(buf[(x, y)].symbol());
}
screen.push('\n');
}
// Look at editor lines only (`N ┃text`): the explorer shows the temp
// dir's random name, which can itself contain "v2".
assert!(
screen.contains("┃v1") && !screen.contains("┃v2"),
"only the root commit's text shows:\n{screen}"
);
}
#[test]
fn leaving_the_scrubber_restores_the_live_buffer_with_its_unsaved_edits() {
let repo = scrub_repo();
let mut app = App::new(repo.path().to_path_buf()).unwrap();
app.editor.open(&repo.path().join("a.txt")).unwrap();
app.editor.lines.push(String::from("UNSAVED LIVE EDIT"));
app.editor.dirty = true;
let live = app.editor.lines.clone();
app.scrub_history();
app.handle_scrubber_key(KeyCode::Left);
app.handle_scrubber_key(KeyCode::Left);
app.focus_pane(Pane::Editor);
// Typing while looking at history must not reach the hidden buffer.
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines, live, "the live buffer took no keystroke");
assert!(app.status.contains("history"), "{}", app.status);
app.handle_scrubber_key(KeyCode::Esc);
assert!(app.scrub_view.is_none(), "the historical view is gone");
assert_eq!(app.editor.lines, live);
assert!(app.editor.dirty, "dirty state untouched");
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let mut screen = String::new();
for y in 0..buf.area.height {
for x in 0..buf.area.width {
screen.push_str(buf[(x, y)].symbol());
}
}
assert!(
screen.contains("UNSAVED LIVE EDIT"),
"the live buffer is painted again"
);
}
#[test]
fn a_file_that_did_not_exist_yet_says_so() {
let repo = scrub_repo();
std::fs::write(repo.path().join("new.txt"), "fresh\n").unwrap();
let mut app = App::new(repo.path().to_path_buf()).unwrap();
app.editor.open(&repo.path().join("new.txt")).unwrap();
app.scrub_history();
app.handle_scrubber_key(KeyCode::Left);
let view = app
.scrub_view
.as_ref()
.expect("a view even for a missing file");
assert!(view.lines[0].contains("did not exist"), "{:?}", view.lines);
}
#[test]
fn the_explorer_dims_files_missing_from_the_scrubbed_commit() {
// #371: at a commit, a file its tree lacks dims; the working tree and
// closing the scrubber clear it.
let repo = scrub_repo();
std::fs::write(repo.path().join("new.txt"), "fresh\n").unwrap();
let mut app = App::new(repo.path().to_path_buf()).unwrap();
let new = repo.path().join("new.txt");
let old = repo.path().join("a.txt");
app.scrub_history();
assert!(app.tree.scrub_tree.is_none(), "opening parks at the tree");
app.handle_scrubber_key(KeyCode::Left);
assert!(app.tree.is_absent_at_scrub(&new), "new.txt is not in HEAD");
assert!(!app.tree.is_absent_at_scrub(&old), "a.txt is");
app.handle_scrubber_key(KeyCode::Home);
assert!(
!app.tree.is_absent_at_scrub(&new),
"Home clears the dimming"
);
app.handle_scrubber_key(KeyCode::Left);
assert!(app.tree.is_absent_at_scrub(&new));
app.handle_scrubber_key(KeyCode::Right);
assert!(
!app.tree.is_absent_at_scrub(&new),
"stepping to the working tree clears it"
);
app.handle_scrubber_key(KeyCode::Left);
app.handle_scrubber_key(KeyCode::Esc);
assert!(app.tree.scrub_tree.is_none(), "closing clears it");
}
#[test]
fn fleet_output_shows_each_hosts_time_and_the_lines_that_differ() {
// #363: a DIFFERS row says what differs, line by line, not just that
// something did; every row says how long the host took.
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let r = |host: &str, out: &str, ms: u64| crate::fleet::HostResult {
host: String::from(host),
output: String::from(out),
exit: Some(0),
elapsed: std::time::Duration::from_millis(ms),
};
app.fleet_running = true;
app.fleet_tx
.send(vec![
r("zz363-a", "Linux\n6.8.0-45", 120),
r("zz363-b", "Linux\n6.8.0-45", 80),
r("zz363-odd", "Linux\n6.8.0-31", 1500),
])
.unwrap();
assert!(app.drain_fleet_results());
let lines: Vec<String> = crate::output::snapshot(crate::output::CHANNEL_FLEET)
.unwrap()
.into_iter()
.map(|l| l.text)
.collect();
let odd = lines
.iter()
.position(|l| l.starts_with("zz363-odd"))
.expect("the odd host has a row");
assert!(
lines[odd].contains("[DIFFERS]") && lines[odd].contains("1.5s"),
"{}",
lines[odd]
);
assert_eq!(
lines[odd + 1..odd + 3],
[" - 6.8.0-45", " + 6.8.0-31"],
"the reference's line and the host's, alone"
);
let a = lines.iter().find(|l| l.starts_with("zz363-a")).unwrap();
assert!(a.contains("0.1s"), "{a}");
assert!(
!lines
.iter()
.any(|l| l.ends_with(" Linux") && l.starts_with(" ")),
"an equal line is not marked"
);
}
const NOTEBOOK_355: &str = "{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"id\": \"c1\",\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n \"print(1+1)\"\n ]\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"Python 3\",\n \"language\": \"python\",\n \"name\": \"python3\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n";
/// Click a notebook cell's run glyph where it is drawn.
fn click_first_cell_glyph(
app: &mut App,
term: &mut ratatui::Terminal<ratatui::backend::TestBackend>,
) {
term.draw(|f| app.render(f)).unwrap();
let md = app
.editor
.markdown_preview
.as_ref()
.expect("notebook preview open");
let (x, y) = (
md.last_area.x,
md.last_area.y + (md.run_rows[0] - md.scroll as usize) as u16,
);
app.handle_mouse(MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column: x,
row: y,
modifiers: KeyModifiers::NONE,
});
}
/// A notebook cell's run glyph, end to end through the App with the test
/// standing in for the kernel: the click sends the cell's code, the cell
/// shows `In [*]` while it runs, and the kernel's output and count land in
/// the buffer as an edit.
#[test]
fn clicking_a_cells_run_glyph_runs_it_and_writes_the_output_into_the_notebook() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("t.ipynb");
// A previous run's output, which this run must replace.
let stale = NOTEBOOK_355.replace(
"\"outputs\": [],",
"\"outputs\": [{\"output_type\": \"stream\", \"name\": \"stdout\", \"text\": [\"stale\\n\"]}],",
);
assert_ne!(stale, NOTEBOOK_355);
std::fs::write(&path, stale).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&path).unwrap();
let (run, kernel, requests) = crate::notebook_kernel::NotebookRun::for_test();
app.notebook_kernels.insert(path.clone(), run);
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
click_first_cell_glyph(&mut app, &mut term);
let sent: Vec<_> = requests.try_iter().collect();
let id = match sent.as_slice() {
[crate::notebook_kernel::Request::Execute { id, code }] => {
assert_eq!(code, "print(1+1)");
id.clone()
}
other => panic!("expected one execute, got {other:?}"),
};
assert_eq!(app.editor.notebook_running, vec![0]);
assert!(
!app.editor.lines.join("\n").contains("stale"),
"the run clears the old output"
);
term.draw(|f| app.render(f)).unwrap();
let md = app.editor.markdown_preview.as_ref().unwrap();
let frame = &md.lines[md.runnables[0].first_line];
assert_eq!(frame.spans[1].content.as_ref(), "In [*]:");
kernel
.send(crate::notebook_kernel::Event::Output {
id: id.clone(),
output: serde_json::json!({"output_type": "stream", "name": "stdout", "text": "2\n"}),
})
.unwrap();
kernel
.send(crate::notebook_kernel::Event::Done {
id,
execution_count: Some(1),
status: "ok".into(),
})
.unwrap();
assert!(app.poll_notebook_kernels());
let doc: serde_json::Value = serde_json::from_str(&app.editor.lines.join("\n")).unwrap();
assert_eq!(doc["cells"][0]["execution_count"], 1);
assert_eq!(doc["cells"][0]["outputs"][0]["text"][0], "2\n");
assert!(app.editor.notebook_running.is_empty());
assert!(app.editor.dirty, "outputs are an edit; Save writes them");
}
/// Acceptance for #355 against a real kernel: `print(1+1)` shows `2`, and
/// after Save the file holds the output in the standard format. Set
/// `CROFT_TEST_JUPYTER_PYTHON` to a venv python with ipykernel.
#[test]
#[ignore = "needs a Python with ipykernel; set CROFT_TEST_JUPYTER_PYTHON"]
fn a_real_kernel_runs_a_cell_and_save_persists_the_output() {
let python = std::path::PathBuf::from(std::env::var("CROFT_TEST_JUPYTER_PYTHON").unwrap());
let tmp = tempfile::tempdir().unwrap();
let venv = python.parent().and_then(Path::parent).unwrap();
std::os::unix::fs::symlink(venv, tmp.path().join(".venv")).unwrap();
let path = tmp.path().join("t.ipynb");
std::fs::write(&path, NOTEBOOK_355).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&path).unwrap();
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
click_first_cell_glyph(&mut app, &mut term);
let end = std::time::Instant::now() + std::time::Duration::from_secs(60);
while !app
.editor
.lines
.join("\n")
.contains("\"execution_count\": 1")
{
assert!(std::time::Instant::now() < end, "status: {}", app.status);
app.poll_notebook_kernels();
std::thread::sleep(std::time::Duration::from_millis(50));
}
app.save();
let saved: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
assert_eq!(saved["cells"][0]["outputs"][0]["output_type"], "stream");
assert_eq!(saved["cells"][0]["outputs"][0]["text"][0], "2\n");
}
/// Acceptance for #355's figure criterion against a real kernel: a
/// matplotlib plot arrives as an `image/png` display, is saved in the file,
/// and the preview places it as an image block, the path Kitty and iTerm2
/// hosts draw. Needs matplotlib next to ipykernel.
#[test]
#[ignore = "needs a Python with ipykernel and matplotlib; set CROFT_TEST_JUPYTER_PYTHON"]
fn a_real_kernel_matplotlib_figure_becomes_an_inline_image() {
let python = std::path::PathBuf::from(std::env::var("CROFT_TEST_JUPYTER_PYTHON").unwrap());
let tmp = tempfile::tempdir().unwrap();
let venv = python.parent().and_then(Path::parent).unwrap();
std::os::unix::fs::symlink(venv, tmp.path().join(".venv")).unwrap();
let path = tmp.path().join("plot.ipynb");
std::fs::write(
&path,
NOTEBOOK_355.replace(
"\"print(1+1)\"",
"\"import matplotlib.pyplot as plt\\n\", \"plt.plot([1, 3, 2])\\n\", \"plt.show()\"",
),
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&path).unwrap();
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 40)).unwrap();
click_first_cell_glyph(&mut app, &mut term);
let end = std::time::Instant::now() + std::time::Duration::from_secs(120);
while !app
.editor
.lines
.join("\n")
.contains("\"execution_count\": 1")
{
assert!(std::time::Instant::now() < end, "status: {}", app.status);
app.poll_notebook_kernels();
std::thread::sleep(std::time::Duration::from_millis(50));
}
term.draw(|f| app.render(f)).unwrap();
let images = &app.editor.markdown_preview.as_ref().unwrap().images;
assert_eq!(images.len(), 1, "the figure is one image block");
let bytes = std::fs::read(&images[0].path).unwrap();
assert!(bytes.starts_with(b"\x89PNG"), "a PNG in scratch");
app.save();
let saved: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
let outputs = saved["cells"][0]["outputs"].as_array().unwrap();
assert!(
outputs
.iter()
.any(|o| o["output_type"] == "display_data" && o["data"]["image/png"].is_string()),
"{outputs:?}"
);
}
fn pr_screen(app: &mut App) -> String {
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(150, 32)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let mut s = String::new();
for y in 0..buf.area.height {
for x in 0..buf.area.width {
s.push_str(buf[(x, y)].symbol());
}
s.push('\n');
}
s
}
#[test]
fn a_pr_review_tab_lists_files_checks_and_a_summary() {
// The cache-dir override is process-global; serialize with the
// other tests that redirect it.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
// #365: the PULL REQUEST tab shows every changed file with +n -m, the
// checks, and a summary line.
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
assert!(app.editor.pr_review.is_some(), "the PR tab is active");
let screen = pr_screen(&mut app);
for want in [
"PR #579",
"feat(sarif): model",
"src/sarif/view.rs",
"+1048",
"0 of 2 viewed",
"docs",
] {
assert!(screen.contains(want), "{want:?} on screen:\n{screen}");
}
});
}
#[test]
fn space_marks_a_file_viewed_and_it_persists() {
// The cache-dir override is process-global; serialize with the
// other tests that redirect it.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
app.handle_pr_review_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
let view = app.editor.pr_review.as_ref().unwrap();
assert!(view.viewed.contains("src/sarif/view.rs"));
assert!(pr_screen(&mut app).contains("1 of 2 viewed"));
// A new session sees the mark.
let mut again = App::new(tmp.path().to_path_buf()).unwrap();
again.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
assert!(
again
.editor
.pr_review
.as_ref()
.unwrap()
.viewed
.contains("src/sarif/view.rs"),
"viewed marks persist"
);
});
}
#[test]
fn enter_opens_the_files_diff_and_esc_leaves_review() {
// The cache-dir override is process-global; serialize with the
// other tests that redirect it.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
let patch = "diff --git a/src/sarif/view.rs b/src/sarif/view.rs\nnew file mode 100644\n--- /dev/null\n+++ b/src/sarif/view.rs\n@@ -0,0 +1,2 @@\n+fn a() {}\n+fn b() {}\n";
app.editor.pr_review.as_mut().unwrap().diff =
Some(crate::pr_review::split_diff_by_file(patch));
let pr_tab = app.editor.active_index();
app.handle_pr_review_key(key(KeyCode::Enter, KeyModifiers::NONE));
assert!(
app.editor.diff.is_some(),
"a diff tab opened: {}",
app.status
);
assert_ne!(app.editor.active_index(), pr_tab, "in its own tab");
app.editor.select(pr_tab);
app.handle_pr_review_key(key(KeyCode::Esc, KeyModifiers::NONE));
assert!(
(0..app.editor.tab_count()).all(|i| {
app.editor.select(i);
app.editor.pr_review.is_none()
}),
"Esc leaves review: the PR tab is closed"
);
});
}
#[test]
fn review_pull_request_is_a_palette_command_with_a_number_prompt() {
use crate::widgets::command_palette::Command;
assert_eq!(
Command::from_id("review_pull_request"),
Some(Command::ReviewPullRequest)
);
assert_eq!(
Command::ReviewPullRequest.title(),
"Source Control: Review Pull Request"
);
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.submit_pr_number("not a number");
assert!(
app.status.contains("not a pull request number"),
"{}",
app.status
);
}
#[test]
fn the_demo_tour_runs_in_a_scratch_project_and_esc_cleans_up() {
// #377: the tour never runs in the user's workspace, and Esc leaves a
// normal croft with no scratch files behind.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.start_demo();
let scratch = app.workspace_root().to_path_buf();
assert_ne!(scratch, tmp.path(), "not the user's workspace");
assert!(scratch.join(crate::tour::SCRATCH_MARKER).is_file());
assert_eq!(
app.editor.path.as_deref(),
Some(scratch.join("src/main.rs").as_path())
);
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 36)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let mut screen = String::new();
for y in 0..buf.area.height {
for x in 0..buf.area.width {
screen.push_str(buf[(x, y)].symbol());
}
}
assert!(
screen.contains("1/8"),
"the caption chip shows progress:\n{screen}"
);
// Enter advances the tour instead of typing into the file.
let lines = app.editor.lines.clone();
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.tour.as_ref().unwrap().tour.index, 1);
assert_eq!(app.editor.lines, lines, "no newline typed into the sample");
app.close_all_modals_for_test();
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(app.tour.is_none(), "Esc leaves the tour");
assert_eq!(
app.workspace_root(),
tmp.path(),
"back in the original workspace"
);
assert!(!scratch.exists(), "the sample project is gone");
});
}
#[test]
fn walking_the_whole_tour_ends_it_and_cleans_up() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.start_demo();
let scratch = app.workspace_root().to_path_buf();
let mut steps = 0;
while app.tour.is_some() && steps < 40 {
app.close_all_modals_for_test();
app.advance_tour();
steps += 1;
}
assert!(app.tour.is_none(), "the tour ends");
assert_eq!(steps, 8, "one advance per step");
assert_eq!(app.workspace_root(), tmp.path());
assert!(!scratch.exists());
});
}
#[test]
fn the_welcome_tour_button_starts_the_tour_and_goes_away_once_done() {
// #377: shown until the first completed or skipped tour, persisted.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.config_dir = tmp.path().join("config");
app.tour_done = false;
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 40)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let button = app.welcome_tour_button;
assert!(button.width > 0, "the welcome panel offers the tour");
left_click(&mut app, button.x + 1, button.y);
assert!(app.tour.is_some(), "clicking starts it: {}", app.status);
app.close_all_modals_for_test();
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(app.tour_done, "a skipped tour counts as done");
let saved = crate::prefs::Prefs::load(&tmp.path().join("config").join("config.json"))
.unwrap_or_default();
assert!(saved.tour_done, "persisted in prefs");
// Back on the welcome screen, the button is gone.
while app.editor.tab_count() > 1 {
app.editor.close_active();
}
app.editor.close_active();
term.draw(|f| app.render(f)).unwrap();
assert_eq!(app.welcome_tour_button.width, 0, "not offered again");
});
}
#[test]
fn take_the_tour_is_a_palette_command() {
use crate::widgets::command_palette::Command;
assert_eq!(
Command::from_id("help_take_the_tour"),
Some(Command::TakeTheTour)
);
assert_eq!(Command::TakeTheTour.title(), "Help: Take the Tour");
}
/// Coverage (#263) through the App, from a report arriving the way the
/// worker's drain delivers it: the active file's lines are marked in the
/// gutter lane, the status readout carries its percentage, an edit dims
/// the marks, a missing tool offers its install, and Clear hands the lane
/// back.
#[test]
fn a_coverage_report_marks_the_gutter_and_dims_after_an_edit() {
use crate::testing::coverage::{Coverage, LineCov};
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let file = root.join("f.rs");
std::fs::write(&file, "fn a() {}\nfn b() {}\n").unwrap();
let mut app = App::new(root.clone()).unwrap();
app.editor.open(&file).unwrap();
app.testing.on_coverage(Ok(Coverage::from_lcov(
"SF:f.rs\nDA:1,3\nDA:2,0\nend_of_record\n",
&root,
)));
assert!(app.sync_coverage());
let lens = app
.editor
.coverage
.clone()
.expect("the open file is covered");
assert_eq!(lens.lines.get(&0), Some(&LineCov::Covered));
assert_eq!(lens.lines.get(&1), Some(&LineCov::Uncovered));
assert!(!lens.stale);
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let bar_x = app.editor.last_inner.x + app.editor.last_gutter_width;
let y = app.editor.last_inner.y;
let buf = term.backend().buffer();
assert_eq!(buf[(bar_x, y)].symbol(), "\u{258c}");
assert_ne!(
buf[(bar_x, y)].fg,
buf[(bar_x, y + 1)].fg,
"covered and uncovered differ"
);
let status_row: String = (0..120).map(|x| buf[(x, 29)].symbol()).collect();
assert!(status_row.contains("50% covered"), "{status_row}");
app.editor.insert_char('x');
app.sync_coverage();
assert!(
app.editor.coverage.as_ref().unwrap().stale,
"an edit dims the marks"
);
app.testing
.on_coverage(Err(crate::testing::worker::CoverageError::Missing {
tool: "cargo-llvm-cov",
install: String::from("cargo install cargo-llvm-cov"),
}));
app.sync_coverage();
assert!(app.status.contains("cargo-llvm-cov"), "{}", app.status);
assert_eq!(
app.coverage_install.as_deref(),
Some("cargo install cargo-llvm-cov")
);
app.run_command(crate::widgets::command_palette::Command::CoverageClear);
assert!(app.editor.coverage.is_none() && app.testing.coverage.is_none());
}
/// Acceptance for #263 against real pytest-cov: "Run All Tests with
/// Coverage" on a pytest project marks the tested file's lines, uncovered
/// branch-free lines red, and reports a percentage. Set
/// `CROFT_TEST_PYTEST_COV_PYTHON` to a venv python with pytest and
/// pytest-cov; the test links that venv in as the project's `.venv`.
#[test]
#[ignore = "needs pytest and pytest-cov; set CROFT_TEST_PYTEST_COV_PYTHON"]
fn a_real_pytest_cov_run_marks_the_covered_file() {
use crate::testing::coverage::LineCov;
let python = std::path::PathBuf::from(std::env::var("CROFT_TEST_PYTEST_COV_PYTHON").unwrap());
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::os::unix::fs::symlink(
python.parent().and_then(Path::parent).unwrap(),
root.join(".venv"),
)
.unwrap();
std::fs::write(
root.join("pyproject.toml"),
"[project]\nname = \"t\"\nversion = \"0\"\n",
)
.unwrap();
std::fs::write(
root.join("calc.py"),
"def add(a, b):\n return a + b\n\n\ndef unused():\n return 0\n",
)
.unwrap();
std::fs::write(
root.join("test_calc.py"),
"from calc import add\n\n\ndef test_add():\n assert add(1, 2) == 3\n",
)
.unwrap();
let mut app = App::new(root.clone()).unwrap();
app.editor.open(&root.join("calc.py")).unwrap();
app.run_all_tests_with_coverage();
let end = std::time::Instant::now() + std::time::Duration::from_secs(120);
while app.editor.coverage.is_none() {
assert!(std::time::Instant::now() < end, "status: {}", app.status);
let _ = app.test_worker.drain(&mut app.testing);
app.sync_coverage();
std::thread::sleep(std::time::Duration::from_millis(100));
}
let lens = app.editor.coverage.clone().unwrap();
assert_eq!(
lens.lines.get(&1),
Some(&LineCov::Covered),
"`return a + b` ran"
);
assert_eq!(
lens.lines.get(&5),
Some(&LineCov::Uncovered),
"`return 0` never ran"
);
assert!(
lens.percent.is_some_and(|p| p > 0.0 && p < 100.0),
"{:?}",
lens.percent
);
}
/// #263: the Testing tree's coverage glyphs run their row with coverage,
/// marking just that scope as running, as a plain run of it would.
#[test]
fn a_rows_coverage_glyph_runs_that_scope_with_coverage() {
use crate::testing::model::{TestCase, TestStatus};
use crate::widgets::testing::RowHit;
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("Cargo.toml"),
"[package]\nname = \"t\"\nversion = \"0.0.0\"\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for n in ["parse::a", "parse::b", "other::c"] {
app.testing.apply_case(TestCase {
name: n.into(),
status: TestStatus::Passed,
});
}
app.set_sidebar_view(SidebarView::Testing);
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let area = app.testing.last_area;
let x = area.x + area.width - 5;
let click = |app: &mut App, want: RowHit| {
let y = (area.y..area.y + area.height)
.find(|&y| app.testing.hit_at(x, y) == Some(want.clone()))
.unwrap_or_else(|| panic!("no {want:?} glyph"));
app.handle_mouse(MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column: x,
row: y,
modifiers: KeyModifiers::NONE,
});
};
click(&mut app, RowHit::CoverSuite("parse".into()));
assert_eq!(app.status, "Running suite parse with coverage");
assert_eq!(app.testing.status_of("parse::a"), Some(TestStatus::Running));
assert_eq!(app.testing.status_of("parse::b"), Some(TestStatus::Running));
assert_eq!(app.testing.status_of("other::c"), Some(TestStatus::Passed));
app.testing.on_finished(Some(true));
click(&mut app, RowHit::CoverCase("other::c".into()));
assert_eq!(app.status, "Running test other::c with coverage");
assert_eq!(app.testing.status_of("other::c"), Some(TestStatus::Running));
app.testing.on_finished(Some(true));
// The header's glyph runs everything with coverage.
let all = app.testing.last_cover_all;
app.handle_mouse(MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column: all.x,
row: all.y,
modifiers: KeyModifiers::NONE,
});
assert_eq!(app.status, "Running tests with coverage");
}
/// Watch mode (#263) end to end through the App: the eye on a test's row
/// watches it, a save anywhere under the runner's root reruns exactly that
/// test once the debounce passes, without moving the sidebar, and a rerun
/// that turns red says which test failed.
#[test]
fn watching_a_test_reruns_it_after_a_save_and_reports_it_turning_red() {
use crate::testing::model::{TestCase, TestStatus};
use crate::testing::watch::WatchScope;
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("Cargo.toml"),
"[package]\nname = \"t\"\nversion = \"0.0.0\"\n",
)
.unwrap();
let src = tmp.path().join("lib.rs");
std::fs::write(&src, "fn a() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for n in ["parse::a", "parse::b"] {
app.testing.apply_case(TestCase {
name: n.into(),
status: TestStatus::Passed,
});
}
app.set_sidebar_view(SidebarView::Testing);
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
// Find parse::a's eye where it is drawn, and click it.
let area = app.testing.last_area;
let x = area.x + area.width - 3;
let y = (area.y..area.y + area.height)
.find(|&y| {
app.testing.hit_at(x, y)
== Some(crate::widgets::testing::RowHit::ToggleWatch(
WatchScope::Test("parse::a".into()),
))
})
.expect("parse::a has an eye");
assert_eq!(term.backend().buffer()[(x, y)].symbol(), "\u{ea70}");
app.handle_mouse(MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column: x,
row: y,
modifiers: KeyModifiers::NONE,
});
assert!(
app.testing
.watch
.is_watching(&WatchScope::Test("parse::a".into()))
);
// The user goes back to the files and saves one.
app.set_sidebar_view(SidebarView::Explorer);
app.editor.open(&src).unwrap();
app.editor.insert_char('x');
app.save();
assert!(!app.tick_test_watch(), "not before the debounce");
std::thread::sleep(crate::testing::watch::DEBOUNCE + std::time::Duration::from_millis(50));
assert!(app.tick_test_watch());
assert_eq!(app.testing.status_of("parse::a"), Some(TestStatus::Running));
assert_eq!(app.testing.status_of("parse::b"), Some(TestStatus::Passed));
assert_eq!(
app.sidebar_view,
SidebarView::Explorer,
"a rerun never moves the sidebar"
);
// The rerun ends red: the status says which test, once.
app.testing.apply_case(TestCase {
name: "parse::a".into(),
status: TestStatus::Failed,
});
app.testing.on_finished(Some(false));
app.tick_test_watch();
assert!(
app.status.contains("Watched tests failed: parse::a"),
"{}",
app.status
);
}
/// A workspace with one source file and a SARIF log pointing into it.
fn sarif_fixture() -> (tempfile::TempDir, std::path::PathBuf) {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
std::fs::write(
tmp.path().join("src/a.rs"),
"fn main() {\n let q = format!(\"{}\", id);\n}\n",
)
.unwrap();
let log = tmp.path().join("results.sarif");
std::fs::write(
&log,
r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"lint","rules":[{"id":"R1","name":"Taint"}]}},
"results":[{"ruleId":"R1","level":"error","message":{"text":"Query built from user input."},
"locations":[{"physicalLocation":{"artifactLocation":{"uri":"src/a.rs"},
"region":{"startLine":2,"startColumn":9}}}]}]}]}"#,
)
.unwrap();
(tmp, log)
}
fn screen_text(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> String {
let buf = term.backend().buffer();
let mut all = String::new();
for y in 0..buf.area.height {
for x in 0..buf.area.width {
all.push_str(buf[(x, y)].symbol());
}
all.push('\n');
}
all
}
#[test]
fn sarif_log_opens_as_the_results_viewer() {
let (tmp, log) = sarif_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
let view = app
.editor
.sarif
.as_ref()
.expect(".sarif opens in the viewer");
assert_eq!(view.entries.len(), 1);
assert_eq!(view.entries[0].file, "src/a.rs");
assert!(
app.editor.has_non_text_view(),
"a save must not write the stub"
);
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let screen = screen_text(&term);
assert!(
screen.contains("src/a.rs"),
"group header painted:\n{screen}"
);
assert!(
screen.contains("Query built from user input."),
"result row painted:\n{screen}"
);
assert!(screen.contains("Locations"), "tab strip painted:\n{screen}");
// The first result starts selected, so its details are already showing.
assert!(
screen.contains("R1 · Taint"),
"details pane shows the first result:\n{screen}"
);
}
#[test]
fn sarif_enter_opens_the_location_and_keeps_the_viewer_tab() {
let (tmp, log) = sarif_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_preview(&log).unwrap();
let tabs_before = app.editor.tab_count();
app.handle_sarif_key(key(KeyCode::Down, KeyModifiers::NONE));
app.handle_sarif_key(key(KeyCode::Enter, KeyModifiers::NONE));
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("src/a.rs").as_path()),
"the location opened: {}",
app.status
);
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 8));
assert_eq!(
app.editor.tab_count(),
tabs_before + 1,
"the viewer was pinned, not replaced by the preview open"
);
}
#[test]
fn sarif_space_previews_the_code_around_the_result_without_leaving_the_list() {
// #577: Space shows the lines around the selected result in the
// details pane; the viewer keeps the keys and Space again hides it.
let (tmp, log) = sarif_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_preview(&log).unwrap();
app.handle_sarif_key(key(KeyCode::Down, KeyModifiers::NONE));
app.handle_sarif_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
app.refresh_sarif_preview();
let view = app.editor.sarif.as_ref().expect("still on the viewer");
let p = view.current_preview().expect("a preview").clone();
assert!(p.title.ends_with("a.rs"), "{}", p.title);
assert_eq!((p.first, p.target), (1, 2));
assert_eq!(p.lines[1], " let q = format!(\"{}\", id);");
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let screen = screen_text(&term);
assert!(screen.contains("Preview · "), "{screen}");
assert!(screen.contains("2 let q = format!"), "{screen}");
// On a group row there is no result to preview.
app.handle_sarif_key(key(KeyCode::Up, KeyModifiers::NONE));
app.refresh_sarif_preview();
assert!(
app.editor
.sarif
.as_ref()
.unwrap()
.current_preview()
.is_none()
);
// Back on the result it comes back; Space turns it off.
app.handle_sarif_key(key(KeyCode::Down, KeyModifiers::NONE));
app.refresh_sarif_preview();
assert!(
app.editor
.sarif
.as_ref()
.unwrap()
.current_preview()
.is_some()
);
app.handle_sarif_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
app.refresh_sarif_preview();
let view = app.editor.sarif.as_ref().unwrap();
assert!(!view.previewing && view.current_preview().is_none());
}
#[test]
fn a_sarif_result_whose_file_is_only_in_the_log_opens_the_logs_copy() {
// #577: `artifacts[].contents` is the file when it is not on this
// machine: text opens read-only at the result, binary in the hex viewer.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let log = tmp.path().join("embedded.sarif");
std::fs::write(
&log,
r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"T"}},
"artifacts":[
{"location":{"uri":"file:///build/gen/query.c"},"contents":{"text":"line one\nline two\nint bad;\n"}},
{"location":{"uri":"file:///build/blob.bin"},"contents":{"binary":"AAEC/w=="}}],
"results":[
{"ruleId":"R1","message":{"text":"text"},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"file:///build/gen/query.c","index":0},"region":{"startLine":3,"startColumn":5}}}]},
{"ruleId":"R2","message":{"text":"bin"},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"file:///build/blob.bin","index":1}}}]}]}]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_preview(&log).unwrap();
let select = |app: &mut App, rule: &str| {
let view = app.editor.sarif.as_mut().unwrap();
let rows = view.rows();
view.selected = rows
.iter()
.position(|r| matches!(r, crate::sarif::view::Row::Item { entry } if view.entries[*entry].rule_id == rule))
.unwrap();
};
select(&mut app, "R1");
app.open_selected_sarif_result();
let opened = app.editor.path.clone().expect("a copy opened");
assert!(
opened.starts_with(croft_cache_dir()),
"{opened:?}: {}",
app.status
);
assert_eq!(opened.file_name().unwrap(), "query.c");
assert_eq!(app.editor.lines[2], "int bad;");
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (2, 4));
assert!(app.status.contains("read-only"), "{}", app.status);
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&opened).unwrap().permissions().mode() & 0o222,
0
);
app.editor.open_preview(&log).unwrap();
select(&mut app, "R2");
app.open_selected_sarif_result();
let opened = app.editor.path.clone().expect("a copy opened");
assert_eq!(std::fs::read(&opened).unwrap(), [0, 1, 2, 255]);
assert!(
app.editor.has_non_text_view(),
"binary opens in the hex viewer"
);
});
}
#[test]
fn a_sarif_log_rewritten_on_disk_keeps_the_readers_place() {
// #577: a rebuild that rewrites the log (a scan re-run) used to reopen
// the viewer from scratch, losing the selection, filter, folds and any
// log added with `o`.
let tmp = tempfile::tempdir().unwrap();
let result = |rule: &str, line: u32| {
format!(
r#"{{"ruleId":"{rule}","level":"warning","message":{{"text":"{rule} here"}},"locations":[{{"physicalLocation":{{"artifactLocation":{{"uri":"src/{rule}.rs"}},"region":{{"startLine":{line}}}}}}}]}}"#
)
};
let log_of = |results: &[String]| {
format!(
r#"{{"version":"2.1.0","runs":[{{"tool":{{"driver":{{"name":"lint"}}}},"results":[{}]}}]}}"#,
results.join(",")
)
};
let main = tmp.path().join("main.sarif");
let extra = tmp.path().join("extra.sarif");
std::fs::write(&main, log_of(&[result("Aa", 1), result("Bb", 2)])).unwrap();
std::fs::write(&extra, log_of(&[result("Cc", 3)])).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&main).unwrap();
{
let view = app.editor.sarif.as_mut().unwrap();
let log = crate::sarif::load::parse_log(&std::fs::read_to_string(&extra).unwrap()).unwrap();
assert!(view.add_log(&extra, log));
view.query_text = String::from("-Cc");
view.filters
.hidden_levels
.insert(crate::sarif::semantics::Level::Note);
view.collapsed.insert(String::from("some-group"));
let rows = view.rows();
view.selected = rows
.iter()
.position(|r| matches!(r, crate::sarif::view::Row::Item { entry } if view.entries[*entry].rule_id == "Bb"))
.unwrap();
}
// The scan runs again: a new result lands first, shifting the others.
std::fs::write(
&main,
log_of(&[result("Zz", 9), result("Aa", 1), result("Bb", 2)]),
)
.unwrap();
app.editor.revert_to_disk().unwrap();
let view = app.editor.sarif.as_ref().unwrap();
assert_eq!(view.logs.len(), 2, "the added log is still there");
assert_eq!(view.query_text, "-Cc");
assert!(
view.filters
.hidden_levels
.contains(&crate::sarif::semantics::Level::Note)
);
assert!(view.collapsed.contains("some-group"));
assert_eq!(view.entries.len(), 4, "the rewritten log was read");
assert_eq!(
view.selected_entry().map(|e| e.rule_id.as_str()),
Some("Bb"),
"the same result stays selected though it moved"
);
}
#[test]
fn sarif_columns_are_chosen_with_c_shown_on_rows_and_remembered() {
// #577: optional columns between a row's position and its message.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let (tmp, log) = sarif_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
assert!(
app.editor.sarif.as_ref().unwrap().columns.is_empty(),
"none by default"
);
let draw = |app: &mut App| {
let mut term =
ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
screen_text(&term)
};
let row = |screen: &str| {
screen
.lines()
.find(|l| l.contains("Query built from user input."))
.and_then(|l| {
// The list part only: the detail pane shares the line.
let end = l.find("input.")? + "input.".len();
Some(l[..end].to_string())
})
.unwrap_or_default()
};
assert!(
!row(&draw(&mut app)).contains("R1 "),
"{}",
row(&draw(&mut app))
);
// An unknown name is refused and names the choices.
app.handle_sarif_key(key(KeyCode::Char('C'), KeyModifiers::NONE));
app.input_prompt.as_mut().unwrap().value = String::from("rule, colour");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(
app.status.contains("No column \"colour\""),
"{}",
app.status
);
assert!(app.status.contains("rule, level, kind"), "{}", app.status);
app.handle_sarif_key(key(KeyCode::Char('C'), KeyModifiers::NONE));
app.input_prompt.as_mut().unwrap().value = String::from("rule, baseline");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.status, "SARIF columns: rule, baseline");
let shown = row(&draw(&mut app));
let (rule, base, msg) = (
shown.find("R1").expect(&shown),
shown.find("no baseline").expect(&shown),
shown.find("Query built").unwrap(),
);
assert!(rule < base && base < msg, "in the chosen order: {shown}");
// Remembered: the next viewer opens with them, and C offers them.
let mut again = App::new(tmp.path().to_path_buf()).unwrap();
again.editor.open(&log).unwrap();
assert_eq!(
again.editor.sarif.as_ref().unwrap().columns,
[
crate::sarif::view::ExtraColumn::Rule,
crate::sarif::view::ExtraColumn::Baseline
]
);
again.handle_sarif_key(key(KeyCode::Char('C'), KeyModifiers::NONE));
assert_eq!(again.input_prompt.as_ref().unwrap().value, "rule,baseline");
});
}
#[test]
fn sarif_filter_words_are_highlighted_in_the_results() {
// Its own cache: the saved column choice (another test's) would push
// the message out of the row.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
// #577: the filter's words are marked where a result's message shows them.
let (tmp, log) = sarif_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
app.editor.sarif.as_mut().unwrap().set_query("user");
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer().clone();
let (y, line) = (0..buf.area.height)
.map(|y| {
let s: String = (0..buf.area.width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect();
(y, s)
})
.find(|(_, s)| s.contains("Query built from user input."))
.expect("the row is drawn");
let at = line[..line.find("user input").unwrap()].chars().count() as u16;
let marked = |x: u16| {
buf[(x, y)]
.modifier
.contains(ratatui::style::Modifier::UNDERLINED)
};
assert!((at..at + 4).all(marked), "\"user\" is marked");
assert!(!marked(at + 4) && !marked(at - 2), "and nothing around it");
});
}
#[test]
fn a_sarif_results_steps_are_drawn_in_their_own_files_only() {
// #577: the selected result's analysis steps appear after their lines,
// in the file each step is in and no other.
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
std::fs::write(
tmp.path().join("src/a.rs"),
"fn a() {\n let x = input();\n sink(x);\n}\n",
)
.unwrap();
std::fs::write(
tmp.path().join("src/b.rs"),
"fn input() -> String {\n read()\n}\n",
)
.unwrap();
let step = |uri: &str, line: u32, msg: &str| {
format!(
r#"{{"location":{{"message":{{"text":"{msg}"}},"physicalLocation":{{"artifactLocation":{{"uri":"{uri}"}},"region":{{"startLine":{line}}}}}}}}}"#
)
};
let log = tmp.path().join("flow.sarif");
std::fs::write(
&log,
format!(
r#"{{"version":"2.1.0","runs":[{{"tool":{{"driver":{{"name":"t"}}}},"results":[{{"ruleId":"R1","message":{{"text":"tainted"}},
"locations":[{{"physicalLocation":{{"artifactLocation":{{"uri":"src/a.rs"}},"region":{{"startLine":3}}}}}}],
"codeFlows":[{{"threadFlows":[{{"locations":[{},{},{}]}}]}}]}}]}}]}}"#,
step("src/b.rs", 2, "source"),
step("src/a.rs", 2, "assigned"),
step("src/a.rs", 3, "sink")
),
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_preview(&log).unwrap();
app.open_selected_sarif_result();
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("src/a.rs").as_path())
);
app.sync_sarif_step_marks();
let labels = |app: &App, line: usize| -> Vec<String> {
app.editor
.inlay_spans_for_test(line)
.iter()
.map(|(_, l, _)| l.trim().to_string())
.collect()
};
assert_eq!(labels(&app, 1), ["\u{25c2} step 2: assigned"]);
assert_eq!(labels(&app, 2), ["\u{25c2} step 3: sink"]);
assert!(
labels(&app, 0).is_empty(),
"b.rs's step is not drawn in a.rs"
);
// The mark sits after the line's text.
let (col, _, _) = &app.editor.inlay_spans_for_test(1)[0];
assert_eq!(*col, " let x = input();".chars().count());
}
#[test]
fn sarif_filter_typing_narrows_the_list() {
let (tmp, log) = sarif_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
app.handle_sarif_key(key(KeyCode::Char('/'), KeyModifiers::NONE));
for c in "nomatch".chars() {
app.handle_sarif_key(key(KeyCode::Char(c), KeyModifiers::NONE));
}
let view = app.editor.sarif.as_ref().unwrap();
assert_eq!(view.query_text, "nomatch");
assert!(view.rows().is_empty());
// Esc leaves the filter box and clears it.
app.handle_sarif_key(key(KeyCode::Esc, KeyModifiers::NONE));
let view = app.editor.sarif.as_ref().unwrap();
assert_eq!(view.query_text, "");
assert_eq!(view.rows().len(), 2);
}
#[test]
fn sarif_that_does_not_load_opens_as_text_and_says_why() {
let tmp = tempfile::tempdir().unwrap();
let bad = tmp.path().join("bad.sarif");
std::fs::write(&bad, "{\n \"version\": \"2.1.0\",\n oops\n}\n").unwrap();
let old = tmp.path().join("old.sarif");
std::fs::write(&old, r#"{"version":"1.0.0","runs":[]}"#).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&bad).unwrap();
assert!(app.editor.sarif.is_none());
assert_eq!(app.editor.lines[2], " oops");
assert!(
app.editor.status.contains("invalid JSON at 3:"),
"status names the position: {}",
app.editor.status
);
app.editor.open(&old).unwrap();
assert!(app.editor.sarif.is_none());
assert!(
app.editor.status.contains("1.0.0"),
"status names the version: {}",
app.editor.status
);
}
fn screen_lower(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> String {
let buf = term.backend().buffer();
let mut all = String::new();
for y in 0..buf.area.height {
for x in 0..buf.area.width {
all.push_str(buf[(x, y)].symbol());
}
all.push('\n');
}
all.to_lowercase()
}
#[test]
fn codeql_icon_sits_below_testing_and_opens_the_codeql_side_bar() {
// #578: VS Code's CodeQL extension adds a QL entry to the activity bar;
// croft's sits directly below Testing and opens the CodeQL side bar.
// Opening the CodeQL view reads croft's cache, whose test override is
// process-global: without the lock and a cache of its own, this test
// reads whatever another CodeQL test has there at the time.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 40)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let ql = app.sidebar_areas.codeql_icon;
let testing = app.sidebar_areas.testing_icon;
assert!(ql.width > 0, "the QL icon lays out on a tall bar");
assert_eq!(ql.y, testing.y + testing.height, "directly below Testing");
left_click(&mut app, ql.x, ql.y);
assert_eq!(app.sidebar_view, SidebarView::CodeQL);
term.draw(|f| app.render(f)).unwrap();
let screen = screen_lower(&term);
for section in [
"language",
"databases",
"queries",
"variant analysis",
"query history",
"ast viewer",
"method modeling",
] {
assert!(
screen.contains(section),
"section {section:?} listed:\n{screen}"
);
}
// The Databases welcome offers VS Code's four ways to add one.
for action in [
"from a folder",
"from an archive",
"from a url",
"from github",
] {
assert!(screen.contains(action), "{action:?} offered:\n{screen}");
}
});
}
#[test]
fn codeql_view_label_round_trips_for_session_restore() {
// Opening the CodeQL view reads croft's cache, whose test override is
// process-global: without the lock and a cache of its own, this test
// reads whatever another CodeQL test has there at the time.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
assert_eq!(sidebar_view_label(SidebarView::CodeQL), "CodeQL");
assert_eq!(sidebar_view_from_label("CodeQL"), Some(SidebarView::CodeQL));
});
}
#[test]
fn codeql_is_a_built_in_extensions_row_and_a_palette_command() {
// Opening the CodeQL view reads croft's cache, whose test override is
// process-global: without the lock and a cache of its own, this test
// reads whatever another CodeQL test has there at the time.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let summaries = crate::lsp::manifest::summaries(crate::lsp::manifest::BUNDLED_MANIFESTS);
assert!(
summaries.iter().any(|s| s.id == "codeql"),
"a built-in CodeQL row in the Extensions panel"
);
use crate::widgets::command_palette::Command;
assert_eq!(Command::from_id("show_codeql"), Some(Command::ShowCodeQL));
assert_eq!(Command::ShowCodeQL.title(), "View: Show CodeQL");
});
}
#[test]
fn codeql_focus_side_bar_and_open_results_directory_are_palette_commands() {
// #578: VS Code's "CodeQL: Focus Side Bar", and the results directory
// of the selected run (else the newest) without the side bar's `o`.
use crate::codeql_query::RunStatus;
use crate::widgets::command_palette::Command;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.config_dir = tmp.path().join("config");
assert_eq!(
Command::from_id("codeql_focus_side_bar"),
Some(Command::CodeqlFocusSideBar)
);
assert_eq!(
Command::CodeqlFocusSideBar.title(),
"CodeQL: Focus Side Bar"
);
app.run_command(Command::CodeqlOpenResultsDirectory);
assert_eq!(app.status, "No CodeQL query has run yet");
let newer = App::codeql_results_dir().join("200-a/results.csv");
let older = App::codeql_results_dir().join("100-b/results.csv");
seed_codeql_history(
tmp.path(),
&[
("b.ql", 100, RunStatus::Succeeded, older.clone()),
("a.ql", 200, RunStatus::Succeeded, newer.clone()),
],
);
app.focus = Pane::Editor;
app.run_command(Command::CodeqlFocusSideBar);
assert_eq!(app.sidebar_view, SidebarView::CodeQL);
assert!(app.focus == Pane::Tree, "the side bar takes the keys");
// Nothing selected in Query History: the newest run.
app.run_command(Command::CodeqlOpenResultsDirectory);
assert_eq!(app.editor.path.as_deref(), Some(newer.as_path()));
// A selected run: that one.
app.codeql.select_history(1);
app.run_command(Command::CodeqlOpenResultsDirectory);
assert_eq!(
app.editor.path.as_deref(),
Some(older.as_path()),
"{}",
app.status
);
});
}
#[test]
fn disabling_codeql_hides_its_icon_and_leaves_its_view() {
// Opening the CodeQL view reads croft's cache, whose test override is
// process-global: without the lock and a cache of its own, this test
// reads whatever another CodeQL test has there at the time.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Never write the developer's real ~/.config/croft from a test.
app.config_dir = tmp.path().join("config");
app.open_codeql_view();
assert_eq!(app.sidebar_view, SidebarView::CodeQL);
app.set_extension_enabled("codeql", false);
assert_eq!(
app.sidebar_view,
SidebarView::Explorer,
"a disabled feature's view does not stay open"
);
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 40)).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert_eq!(app.sidebar_areas.codeql_icon.width, 0, "the icon is gone");
assert!(
app.sidebar_areas.settings_icon.width > 0,
"the gear still lays out"
);
app.open_codeql_view();
assert_ne!(
app.sidebar_view,
SidebarView::CodeQL,
"cannot open while disabled"
);
assert!(app.status.contains("disabled"), "{}", app.status);
app.set_extension_enabled("codeql", true);
term.draw(|f| app.render(f)).unwrap();
assert!(
app.sidebar_areas.codeql_icon.width > 0,
"re-enabling restores it"
);
});
}
fn make_codeql_db(root: &std::path::Path, name: &str, lang: &str) -> std::path::PathBuf {
let dir = root.join(name);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("codeql-database.yml"),
format!("primaryLanguage: \"{lang}\"\n"),
)
.unwrap();
dir
}
#[test]
fn adding_a_codeql_database_from_a_folder_lists_and_persists_it() {
// The cache-dir override is process-global; serialize with the
// other tests that redirect it.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
// #578: Databases > From a folder.
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let db = make_codeql_db(tmp.path(), "flask-db", "python");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.submit_codeql_database(
crate::widgets::input_prompt::CodeqlDbSource::Folder,
&db.display().to_string(),
);
assert!(
app.status.contains("Added CodeQL database flask-db"),
"{}",
app.status
);
assert_eq!(app.codeql.databases.len(), 1);
assert_eq!(app.codeql.current_db, Some(0));
// A new session lists it too.
let mut again = App::new(tmp.path().to_path_buf()).unwrap();
again.open_codeql_view();
assert_eq!(again.codeql.databases.len(), 1, "the list persists");
assert_eq!(
again.codeql.databases[0].language.as_deref(),
Some("python")
);
});
}
#[test]
fn adding_a_codeql_database_from_an_archive_extracts_it_first() {
// The cache-dir override is process-global; serialize with the
// other tests that redirect it.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use std::io::Write as _;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let zp = tmp.path().join("kafka-db.zip");
let mut z = zip::ZipWriter::new(std::fs::File::create(&zp).unwrap());
let opts = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Stored);
z.start_file("java/codeql-database.yml", opts).unwrap();
z.write_all(b"primaryLanguage: \"java\"\n").unwrap();
z.finish().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.submit_codeql_database(
crate::widgets::input_prompt::CodeqlDbSource::Archive,
&zp.display().to_string(),
);
assert_eq!(app.codeql.databases.len(), 1, "{}", app.status);
let entry = &app.codeql.databases[0];
assert_eq!(entry.language.as_deref(), Some("java"));
assert!(
entry.path.starts_with(home.path()),
"extracted under croft's cache, not beside the archive: {}",
entry.path.display()
);
});
}
#[test]
fn a_folder_without_a_codeql_database_is_refused_and_selection_persists() {
// The cache-dir override is process-global; serialize with the
// other tests that redirect it.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.submit_codeql_database(
crate::widgets::input_prompt::CodeqlDbSource::Folder,
&tmp.path().display().to_string(),
);
assert!(
app.status.contains("not a CodeQL database"),
"{}",
app.status
);
assert!(app.codeql.databases.is_empty());
let a = make_codeql_db(tmp.path(), "a-db", "python");
let b = make_codeql_db(tmp.path(), "b-db", "go");
for db in [&a, &b] {
app.submit_codeql_database(
crate::widgets::input_prompt::CodeqlDbSource::Folder,
&db.display().to_string(),
);
}
assert_eq!(app.codeql.current_db, Some(1));
app.activate_codeql(crate::widgets::codeql::Hit::Action(
crate::widgets::codeql::Action::SelectDatabase(0),
));
assert_eq!(app.codeql.current_db, Some(0));
let mut again = App::new(tmp.path().to_path_buf()).unwrap();
again.open_codeql_view();
assert_eq!(again.codeql.current_db, Some(0), "the selection persists");
});
}
#[test]
fn codeql_databases_are_renamed_sorted_revealed_and_removed_from_the_side_bar() {
// The cache-dir override is process-global; serialize with the
// other tests that redirect it.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
// #578: VS Code's Databases view renames, sorts, shows the folder of
// and removes a database; removing deletes only what croft downloaded.
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mine = make_codeql_db(tmp.path(), "flask-db", "python");
let cached_root = App::codeql_db_cache_dir().join("kafka");
let cached = make_codeql_db(&cached_root, "java", "java");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for db in [&mine, &cached] {
app.submit_codeql_database(
crate::widgets::input_prompt::CodeqlDbSource::Folder,
&db.display().to_string(),
);
}
app.open_codeql_view();
app.focus = Pane::Tree;
let press = |app: &mut App, code: KeyCode| {
app.handle_key(key(code, KeyModifiers::NONE)).unwrap();
};
// F2 renames, starting from the current name.
app.codeql.select_database(0);
press(&mut app, KeyCode::F(2));
assert_eq!(app.input_prompt.as_ref().unwrap().value, "flask-db");
for _ in 0.."flask-db".len() {
press(&mut app, KeyCode::Backspace);
}
for c in "web".chars() {
press(&mut app, KeyCode::Char(c));
}
press(&mut app, KeyCode::Enter);
assert_eq!(app.codeql.databases[0].name, "web", "{}", app.status);
assert_eq!(
crate::codeql_db::DatabaseStore::load(&App::codeql_db_store_path()).databases[0].name,
"web",
"saved"
);
// `s` sorts by name; the current database and the selection follow.
press(&mut app, KeyCode::Char('s'));
let names: Vec<_> = app
.codeql
.databases
.iter()
.map(|d| d.name.as_str())
.collect();
assert_eq!(names, ["java", "web"]);
assert_eq!(app.codeql.current_db, Some(0), "kafka's is still current");
assert_eq!(app.codeql.selected_database(), Some(1), "still on web");
// `e` shows its folder in the Explorer.
press(&mut app, KeyCode::Char('e'));
assert_eq!(app.sidebar_view, SidebarView::Explorer);
assert_eq!(app.tree.nodes[app.tree.selected].path, mine);
app.open_codeql_view();
app.focus = Pane::Tree;
// Delete asks first; Esc keeps it.
app.codeql.select_database(1);
press(&mut app, KeyCode::Delete);
assert!(
app.input_prompt
.as_ref()
.unwrap()
.title
.contains("folder stays"),
"the user's own folder is only forgotten"
);
press(&mut app, KeyCode::Esc);
assert_eq!(app.codeql.databases.len(), 2, "Esc keeps it");
press(&mut app, KeyCode::Delete);
press(&mut app, KeyCode::Enter);
assert_eq!(app.codeql.databases.len(), 1, "{}", app.status);
assert!(mine.is_dir(), "not croft's to delete");
assert_eq!(app.codeql.selected_database(), Some(0), "stays in the list");
// The downloaded copy goes with its files.
press(&mut app, KeyCode::Delete);
assert!(
app.input_prompt
.as_ref()
.unwrap()
.title
.contains("files are deleted"),
"{}",
app.input_prompt.as_ref().unwrap().title
);
press(&mut app, KeyCode::Enter);
assert!(app.codeql.databases.is_empty(), "{}", app.status);
assert!(!cached_root.exists(), "the whole cached copy is gone");
assert_eq!(app.codeql.current_db, None);
});
}
#[test]
fn codeql_database_palette_commands_act_on_the_current_database() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(Command::CodeqlRemoveDatabase);
assert!(
app.status.contains("Select a CodeQL database"),
"{}",
app.status
);
assert!(app.input_prompt.is_none());
let db = make_codeql_db(tmp.path(), "flask-db", "python");
app.submit_codeql_database(
crate::widgets::input_prompt::CodeqlDbSource::Folder,
&db.display().to_string(),
);
app.run_command(Command::CodeqlRenameDatabase);
assert_eq!(
app.input_prompt.as_ref().map(|p| &p.purpose),
Some(
&crate::widgets::input_prompt::InputPurpose::CodeqlRenameDatabase {
path: db.clone()
}
)
);
app.close_input_prompt();
app.run_command(Command::CodeqlSortDatabases);
assert_eq!(app.codeql.db_sort, Some(crate::codeql_db::DbSort::Name));
assert_eq!(
Command::from_id("codeql_reveal_database"),
Some(Command::CodeqlRevealDatabase)
);
assert_eq!(
Command::CodeqlRemoveDatabase.title(),
"CodeQL: Remove Database"
);
});
}
/// Save a query history of `(query, started, status, output)` runs, with
/// each output file written, for the history management tests.
fn seed_codeql_history(
tmp: &std::path::Path,
runs: &[(&str, u64, crate::codeql_query::RunStatus, PathBuf)],
) {
let mut history = crate::codeql_query::History::default();
for (query, started, status, output) in runs {
std::fs::write(tmp.join(query), "select 1").unwrap();
std::fs::create_dir_all(output.parent().unwrap()).unwrap();
std::fs::write(output, "col0\n1\n").unwrap();
history.push(crate::codeql_query::HistoryEntry {
query: tmp.join(query),
database: String::from("app"),
database_path: None,
started: *started,
seconds: 3,
status: status.clone(),
output: output.clone(),
name: None,
results: None,
});
}
history.save(&App::codeql_history_path()).unwrap();
}
#[test]
fn codeql_query_history_is_renamed_sorted_opened_and_removed_from_the_side_bar() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
// #578: VS Code's Query History view renames, sorts, views the query
// of, opens the results directory of and removes a run; removing
// deletes only results in croft's own cache.
use crate::codeql_query::RunStatus;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let cached = App::codeql_results_dir().join("200-a");
let elsewhere = tmp.path().join("elsewhere");
seed_codeql_history(
tmp.path(),
&[
(
"c.ql",
50,
RunStatus::Running,
App::codeql_results_dir().join("50-c/results.csv"),
),
(
"b.ql",
100,
RunStatus::Succeeded,
elsewhere.join("results.csv"),
),
(
"a.ql",
200,
RunStatus::Succeeded,
cached.join("results.csv"),
),
],
);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_codeql_view();
app.focus = Pane::Tree;
let press = |app: &mut App, code: KeyCode| {
app.handle_key(key(code, KeyModifiers::NONE)).unwrap();
};
assert_eq!(app.codeql.history.len(), 3);
assert!(app.codeql.history[0].contains("a.ql"), "newest first");
// F2 renames, starting from the query's name.
app.codeql.select_history(0);
press(&mut app, KeyCode::F(2));
assert_eq!(app.input_prompt.as_ref().unwrap().value, "a.ql");
for _ in 0.."a.ql".len() {
press(&mut app, KeyCode::Backspace);
}
for c in "zeta".chars() {
press(&mut app, KeyCode::Char(c));
}
press(&mut app, KeyCode::Enter);
assert_eq!(app.codeql.history[0], "\u{2713} zeta", "{}", app.status);
// `s` on a history row sorts the history, not the databases.
press(&mut app, KeyCode::Char('s'));
assert_eq!(app.codeql.history_sort, crate::codeql_query::HistSort::Name);
assert_eq!(app.codeql.db_sort, None, "databases untouched");
assert!(app.codeql.history[0].contains("b.ql"));
assert_eq!(app.codeql.selected_history(), Some(2), "still on zeta");
assert_eq!(
crate::codeql_query::History::load(&App::codeql_history_path()).sort_by,
crate::codeql_query::HistSort::Name,
"the order is saved"
);
// `v` opens the query; `o` the results in their cache folder.
press(&mut app, KeyCode::Char('v'));
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("a.ql").as_path())
);
press(&mut app, KeyCode::Char('o'));
assert_eq!(
app.editor.path.as_deref(),
Some(cached.join("results.csv").as_path())
);
assert!(app.status.contains("Results directory"), "{}", app.status);
// A run in flight is not removed.
app.codeql.select_history(1);
press(&mut app, KeyCode::Delete);
assert!(app.input_prompt.is_none());
assert!(app.status.contains("still running"), "{}", app.status);
// Delete asks first; Esc keeps it; results outside the cache stay.
app.codeql.select_history(0);
press(&mut app, KeyCode::Delete);
assert!(
app.input_prompt
.as_ref()
.unwrap()
.title
.contains("stay on disk"),
"{}",
app.input_prompt.as_ref().unwrap().title
);
press(&mut app, KeyCode::Esc);
assert_eq!(app.codeql.history.len(), 3, "Esc keeps it");
press(&mut app, KeyCode::Delete);
press(&mut app, KeyCode::Enter);
assert_eq!(app.codeql.history.len(), 2, "{}", app.status);
assert!(
elsewhere.join("results.csv").is_file(),
"not croft's to delete"
);
assert_eq!(app.codeql.selected_history(), Some(0), "stays in the list");
// Croft's own results folder goes with its entry.
app.codeql.select_history(1);
press(&mut app, KeyCode::Delete);
assert!(
app.input_prompt
.as_ref()
.unwrap()
.title
.contains("results are deleted"),
"{}",
app.input_prompt.as_ref().unwrap().title
);
press(&mut app, KeyCode::Enter);
assert_eq!(app.codeql.history.len(), 1, "{}", app.status);
assert!(!cached.exists(), "the run's folder is gone");
assert!(
App::codeql_results_dir().join("50-c").is_dir(),
"only that run's folder"
);
});
}
#[cfg(unix)]
#[test]
fn a_codeql_runs_evaluator_log_opens_raw_or_summarised() {
// #578: every run writes an evaluator log beside its results. "Show
// Evaluator Log (Raw JSON)" opens it; "(Summary Text)" runs `codeql
// generate log-summary` once and opens the text it wrote.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::codeql_query::RunStatus;
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let out = App::codeql_results_dir().join("1-q").join("results.csv");
seed_codeql_history(
tmp.path(),
&[("q.ql", 1, RunStatus::Succeeded, out.clone())],
);
app.run_command(Command::CodeqlShowEvaluatorLog);
assert_eq!(app.status, "q.ql has no evaluator log");
let log = crate::codeql_query::evaluator_log(&out);
std::fs::create_dir_all(log.parent().unwrap()).unwrap();
std::fs::write(&log, "{\"type\":\"LOG_HEADER\"}\n").unwrap();
app.run_command(Command::CodeqlShowEvaluatorLog);
assert_eq!(app.editor.path.as_deref(), Some(log.as_path()));
// The fake CLI writes its reply to the path after the log.
app.codeql_program = fake_codeql(bin.path(), "", 0, "");
let script = std::fs::read_to_string(&app.codeql_program).unwrap();
std::fs::write(
&app.codeql_program,
script.replace(
"exit 0",
"[ \"$1\" = generate ] && echo 'Summary' > \"$5\"\nexit 0",
),
)
.unwrap();
app.run_command(Command::CodeqlShowEvaluatorLogSummary);
assert_eq!(app.status, "Summarising the evaluator log\u{2026}");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_codeql_log_summary() {
assert!(
std::time::Instant::now() < deadline,
"the summary never finished"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
let summary = crate::codeql_query::evaluator_log_summary(&out);
assert_eq!(app.status, "Opened the evaluator log summary");
assert_eq!(app.editor.path.as_deref(), Some(summary.as_path()));
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert_eq!(
calls.trim(),
format!(
"generate log-summary --format=text {} {}",
log.display(),
summary.display()
)
);
// Made once: the second request opens the file without the CLI.
app.run_command(Command::CodeqlShowEvaluatorLogSummary);
assert!(app.codeql_log_summary.is_none());
assert_eq!(app.editor.path.as_deref(), Some(summary.as_path()));
assert_eq!(
Command::from_id("codeql_show_evaluator_log_summary"),
Some(Command::CodeqlShowEvaluatorLogSummary)
);
});
}
#[cfg(unix)]
#[test]
fn a_codeql_runs_query_log_opens_the_newest_log_in_its_logs_folder() {
// #578: VS Code's "Show Query Log". Every run passes `--logdir` so
// `codeql` writes its log beside the results; the newest one opens.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::codeql_query::RunStatus;
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let out = App::codeql_results_dir().join("1-q").join("results.csv");
seed_codeql_history(
tmp.path(),
&[("q.ql", 1, RunStatus::Succeeded, out.clone())],
);
// A run from before croft kept query logs.
app.run_command(Command::CodeqlShowQueryLog);
assert_eq!(app.status, "q.ql has no query log");
let logs = crate::codeql_query::query_log_dir(&out);
std::fs::create_dir_all(&logs).unwrap();
let at = |secs| std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs);
for (name, secs) in [
("execute-new.log", 20),
("execute-old.log", 10),
("x.txt", 30),
] {
let f = std::fs::File::create(logs.join(name)).unwrap();
f.set_modified(at(secs)).unwrap();
}
app.run_command(Command::CodeqlShowQueryLog);
assert_eq!(
app.editor.path.as_deref(),
Some(logs.join("execute-new.log").as_path())
);
assert_eq!(
Command::from_id("codeql_show_query_log"),
Some(Command::CodeqlShowQueryLog)
);
// A real run asks `codeql` for a log in its own folder.
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "import rust\nselect 1");
app.codeql_program = fake_codeql(bin.path(), "", 0, "");
app.run_command(Command::CodeqlRunQuery);
wait_for_codeql(&mut app);
let history = crate::codeql_query::History::load(&App::codeql_history_path());
let run = &history.entries[history.newest().unwrap()];
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
let logdir = format!(
"--logdir={}",
crate::codeql_query::query_log_dir(&run.output).display()
);
assert!(calls.starts_with("query run "), "{calls}");
assert!(calls.contains(&logdir), "{calls}");
});
}
#[cfg(unix)]
#[test]
fn a_codeql_runs_evaluator_log_viewer_shows_a_folded_predicate_tree() {
// #578: "Show Evaluator Log (Viewer)" runs `codeql generate log-summary
// --format=predicates` once, keeps the file beside the log, and shows
// its predicates slowest first as a tree folded to one line each.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::codeql_query::RunStatus;
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let out = App::codeql_results_dir().join("1-q").join("results.csv");
seed_codeql_history(
tmp.path(),
&[("q.ql", 1, RunStatus::Succeeded, out.clone())],
);
app.run_command(Command::CodeqlShowEvaluatorLogViewer);
assert_eq!(app.status, "q.ql has no evaluator log");
assert!(app.codeql_log_viewer.is_none());
let log = crate::codeql_query::evaluator_log(&out);
std::fs::create_dir_all(log.parent().unwrap()).unwrap();
std::fs::write(&log, "{\"type\":\"LOG_HEADER\"}\n").unwrap();
let sample = concat!(
r#"{"summaryLogVersion":"0.4.0"}"#,
"\n",
r#"{"predicateName":"Foo::fast#a","evaluationStrategy":"COMPUTE_SIMPLE","millis":7,"resultSize":2,"dependencies":{"files":"h"},"ra":{"pipeline":["{1} r1 = SCAN files","return r1"]},"pipelineRuns":[{"raReference":"pipeline"}]}"#,
"\n",
r#"{"predicateName":"Foo::slow#b","evaluationStrategy":"COMPUTE_RECURSIVE","millis":1500,"resultSize":1234,"predicateIterationMillis":[500,1000],"ra":{"base":["return r1"],"standard":["return r2"]}}"#,
"\n",
);
let reply = tmp.path().join("reply.jsonl");
std::fs::write(&reply, sample).unwrap();
// The fake CLI copies its reply to the path after the log.
app.codeql_program = fake_codeql(bin.path(), "", 0, "");
let script = std::fs::read_to_string(&app.codeql_program).unwrap();
std::fs::write(
&app.codeql_program,
script.replace(
"exit 0",
&format!(
"[ \"$1\" = generate ] && cp '{}' \"$5\"\nexit 0",
reply.display()
),
),
)
.unwrap();
let wait = |app: &mut App| {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_codeql_log_viewer() {
assert!(
std::time::Instant::now() < deadline,
"the viewer never finished"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
};
app.run_command(Command::CodeqlShowEvaluatorLogViewer);
assert_eq!(app.status, "Reading the evaluator log\u{2026}");
wait(&mut app);
assert_eq!(app.status, "Opened the evaluator log viewer");
assert_eq!(
app.editor.path.as_deref(),
Some(std::path::Path::new("Evaluator Log (q.ql)"))
);
assert_eq!(
app.editor.lines[2],
"\u{25b8} 1,500 ms 1,234 rows Foo::slow#b (COMPUTE_RECURSIVE), 2 iterations"
);
assert!(
app.editor
.lines
.iter()
.any(|l| l.starts_with("\u{25b8} 7 ms 2 rows Foo::fast#a")),
"{:?}",
app.editor.lines
);
assert!(app.editor.lines.iter().any(|l| l == " files"));
assert!(app.editor.is_line_hidden(3), "predicates start folded");
// The side bar's Evaluator Log Viewer section holds the same tree.
{
use crate::widgets::codeql::{Action, Hit, Line};
let rows = |app: &App| -> Vec<(Action, String)> {
app.codeql
.lines()
.into_iter()
.filter_map(|l| match l {
Line::Action(
a @ (Action::EvalPredicate(_)
| Action::EvalDependency(_)
| Action::ClearEvalLog),
t,
) => Some((a, t)),
_ => None,
})
.collect()
};
let folded = rows(&app);
assert_eq!(folded.len(), 3, "{folded:?}");
assert_eq!(folded[0].1, "Clear \u{b7} q.ql");
assert!(folded[1].1.contains("Foo::slow#b"), "slowest first");
assert!(folded[2].1.contains("Foo::fast#a"));
app.activate_codeql(Hit::Action(Action::EvalPredicate(1)));
let open = rows(&app);
assert!(open[2].1.starts_with("\u{25be}"), "{open:?}");
assert!(
open.iter().any(|(_, t)| t == " Pipeline pipeline"),
"{open:?}"
);
let dep = open
.iter()
.find(|(a, _)| matches!(a, Action::EvalDependency(_)))
.expect("the dependency row");
assert_eq!(dep.1, " \u{2192} files");
app.activate_codeql(Hit::Action(dep.0));
assert!(app.status.contains("not in this log"), "{}", app.status);
app.activate_codeql(Hit::Action(Action::ClearEvalLog));
assert!(app.codeql.evallog.is_none());
}
let predicates = crate::codeql_query::evaluator_log_predicates(&out);
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert_eq!(
calls.trim(),
format!(
"generate log-summary --format=predicates {} {}",
log.display(),
predicates.display()
)
);
// Made once: the second request reads the kept file without the CLI.
app.run_command(Command::CodeqlShowEvaluatorLogViewer);
wait(&mut app);
assert_eq!(app.status, "Opened the evaluator log viewer");
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert_eq!(calls.trim().lines().count(), 1, "{calls}");
assert_eq!(
Command::from_id("codeql_show_evaluator_log_viewer"),
Some(Command::CodeqlShowEvaluatorLogViewer)
);
// A CLI failure says why.
std::fs::remove_file(&predicates).unwrap();
app.codeql_program = fake_codeql(bin.path(), "", 2, "no such log");
app.run_command(Command::CodeqlShowEvaluatorLogViewer);
wait(&mut app);
assert_eq!(app.status, "Could not read the evaluator log: no such log");
});
}
#[cfg(unix)]
#[test]
fn comparing_codeql_performance_sets_two_runs_predicate_timings_side_by_side() {
// #578: VS Code's "Compare Performance". The newest run's evaluator
// log is set against the previous successful run of the same query,
// whatever its kind of results; a predicate summary either run lacks
// is made once by the CLI, as the log viewer makes it.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::codeql_query::RunStatus;
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let old_out = App::codeql_results_dir().join("1-q").join("results.sarif");
let new_out = App::codeql_results_dir().join("2-q").join("results.csv");
seed_codeql_history(
tmp.path(),
&[("q.ql", 2, RunStatus::Succeeded, new_out.clone())],
);
app.run_command(Command::CodeqlComparePerformance);
assert_eq!(app.status, "q.ql has no evaluator log");
let new_log = crate::codeql_query::evaluator_log(&new_out);
std::fs::write(&new_log, "{}\n").unwrap();
app.run_command(Command::CodeqlComparePerformance);
assert_eq!(
app.status,
"There is no earlier successful run of q.ql to compare with"
);
seed_codeql_history(
tmp.path(),
&[
("q.ql", 1, RunStatus::Succeeded, old_out.clone()),
("q.ql", 2, RunStatus::Succeeded, new_out.clone()),
],
);
app.run_command(Command::CodeqlComparePerformance);
assert_eq!(app.status, "q.ql has no evaluator log", "the earlier run's");
assert!(app.codeql_perf_compare.is_none());
// The earlier run's summary is already kept; the later one's is not.
std::fs::write(crate::codeql_query::evaluator_log(&old_out), "{}\n").unwrap();
std::fs::write(
crate::codeql_query::evaluator_log_predicates(&old_out),
concat!(
r#"{"predicateName":"Foo::bar#abc","evaluationStrategy":"COMPUTE_SIMPLE","millis":3400,"resultSize":12}"#,
"\n",
r#"{"predicateName":"Gone::p#1","evaluationStrategy":"COMPUTE_SIMPLE","millis":500,"resultSize":4}"#,
"\n",
),
)
.unwrap();
let reply = tmp.path().join("reply.jsonl");
std::fs::write(
&reply,
concat!(
r#"{"predicateName":"Foo::bar#def","evaluationStrategy":"COMPUTE_SIMPLE","millis":4600,"resultSize":15}"#,
"\n",
r#"{"predicateName":"Added::r#2","evaluationStrategy":"COMPUTE_SIMPLE","millis":90,"resultSize":7}"#,
"\n",
),
)
.unwrap();
app.codeql_program = fake_codeql(bin.path(), "", 0, "");
let script = std::fs::read_to_string(&app.codeql_program).unwrap();
std::fs::write(
&app.codeql_program,
script.replace(
"exit 0",
&format!(
"[ \"$1\" = generate ] && cp '{}' \"$5\"\nexit 0",
reply.display()
),
),
)
.unwrap();
let wait = |app: &mut App| {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_codeql_perf_compare() {
assert!(
std::time::Instant::now() < deadline,
"the comparison never finished"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
};
app.run_command(Command::CodeqlComparePerformance);
assert_eq!(app.status, "Comparing the evaluator logs\u{2026}");
wait(&mut app);
assert_eq!(app.status, "Opened the performance comparison");
assert_eq!(
app.editor.path.as_deref(),
Some(std::path::Path::new("Performance (q.ql)"))
);
assert_eq!(
app.editor.lines[..6],
[
"Performance: earlier (app) \u{2192} later (app)",
"3,900 \u{2192} 4,690 ms in all (+790 ms), 3 predicates: 1 in both, 1 only before, 1 only after",
"",
"+1,200 ms 3,400 \u{2192} 4,600 ms 12 \u{2192} 15 rows Foo::bar#def",
" -500 ms 500 \u{2192} \u{2013} ms 4 \u{2192} \u{2013} rows Gone::p#1",
" +90 ms \u{2013} \u{2192} 90 ms \u{2013} \u{2192} 7 rows Added::r#2",
]
);
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert_eq!(
calls.trim(),
format!(
"generate log-summary --format=predicates {} {}",
new_log.display(),
crate::codeql_query::evaluator_log_predicates(&new_out).display()
)
);
assert_eq!(
Command::from_id("codeql_compare_performance"),
Some(Command::CodeqlComparePerformance)
);
});
}
#[test]
fn codeql_results_are_exported_to_a_new_file_only() {
// #578: VS Code's "Export Results" copies the newest successful run's
// results (a failed run later on is passed over) to a file the user
// names, suggesting one in the workspace, and never overwrites.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::codeql_query::RunStatus;
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(Command::CodeqlExportResults);
assert_eq!(
app.status,
"There is no successful CodeQL query run to export"
);
assert!(app.input_prompt.is_none());
seed_codeql_history(
tmp.path(),
&[
(
"q.ql",
2,
RunStatus::Succeeded,
App::codeql_results_dir().join("2-q/results.csv"),
),
(
"r.ql",
5,
RunStatus::Failed(String::from("x")),
App::codeql_results_dir().join("5-r/results.sarif"),
),
],
);
app.run_command(Command::CodeqlExportResults);
let dest = app.workspace_root().join("q-results.csv");
assert_eq!(
app.input_prompt.as_ref().expect("the prompt opens").value,
dest.display().to_string()
);
app.submit_input_prompt();
assert_eq!(
app.status,
format!("Exported results to {}", dest.display())
);
assert_eq!(std::fs::read_to_string(&dest).unwrap(), "col0\n1\n");
std::fs::write(&dest, "mine").unwrap();
app.run_command(Command::CodeqlExportResults);
app.submit_input_prompt();
assert_eq!(
app.status,
format!(
"{} already exists; export the results to a new file",
dest.display()
)
);
assert_eq!(std::fs::read_to_string(&dest).unwrap(), "mine");
// A dangling symlink is refused too, not followed and written.
#[cfg(unix)]
{
let link = app.workspace_root().join("link.csv");
let target = app.workspace_root().join("nowhere.csv");
std::os::unix::fs::symlink(&target, &link).unwrap();
app.run_command(Command::CodeqlExportResults);
app.input_prompt.as_mut().unwrap().value = link.display().to_string();
app.submit_input_prompt();
assert!(app.status.contains("already exists"), "{}", app.status);
assert!(!target.exists(), "the link's target was not created");
}
// Results gone while the prompt was open: nothing is created at
// the destination.
let fresh = app.workspace_root().join("fresh.csv");
app.run_command(Command::CodeqlExportResults);
app.input_prompt.as_mut().unwrap().value = fresh.display().to_string();
std::fs::remove_file(App::codeql_results_dir().join("2-q/results.csv")).unwrap();
app.submit_input_prompt();
assert!(
app.status.starts_with("Could not read the results at "),
"{}",
app.status
);
assert!(!fresh.exists(), "no file was created for a failed export");
assert_eq!(
Command::from_id("codeql_export_results"),
Some(Command::CodeqlExportResults)
);
});
}
#[cfg(unix)]
#[test]
fn a_codeql_query_suite_runs_through_database_analyze_into_sarif() {
// #578: VS Code's "CodeQL: Run Query Suite" runs the open .qls on the
// selected database; a suite only runs through `database analyze`, so
// its results are SARIF whatever its queries' kinds.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "select 1");
app.codeql_program = fake_codeql(bin.path(), r#"{"version":"2.1.0","runs":[]}"#, 0, "");
// `resolve queries` answers with the suite's queries: one alert
// query, listed in a file the test can switch to a table query.
let alert = tmp.path().join("Alert.ql");
std::fs::write(&alert, "/** @kind problem */ select 1").unwrap();
let listed = bin.path().join("resolved.json");
std::fs::write(&listed, format!("[\"{}\"]", alert.display())).unwrap();
let script = std::fs::read_to_string(&app.codeql_program).unwrap();
std::fs::write(
&app.codeql_program,
script.replacen(
"\n",
&format!(
"\n[ \"$1\" = resolve ] && {{ cat '{}'; exit 0; }}\n",
listed.display()
),
1,
),
)
.unwrap();
app.run_command(Command::CodeqlRunQuerySuite);
assert_eq!(app.status, "Open a .qls query suite to run it");
assert!(app.codeql_run.is_none());
let suite = tmp.path().join("s.qls");
std::fs::write(&suite, "- queries: .\n").unwrap();
app.editor.open(&suite).unwrap();
// The CLI reads the saved suite, so unsaved edits are refused.
app.editor.dirty = true;
app.run_command(Command::CodeqlRunQuerySuite);
assert_eq!(
app.status,
"Save s.qls before running it: CodeQL reads it from disk"
);
assert!(app.codeql_run.is_none());
app.editor.dirty = false;
app.run_command(Command::CodeqlRunQuerySuite);
assert!(
app.status.contains("Running s.qls on app"),
"{}",
app.status
);
wait_for_codeql(&mut app);
let opened = app.editor.path.clone().expect("the results open");
assert_eq!(opened.extension().and_then(|e| e.to_str()), Some("sarif"));
assert!(
app.codeql.history[0].starts_with("\u{2713} s.qls \u{b7} app"),
"{:?}",
app.codeql.history
);
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert!(
calls.contains(&format!(
"database analyze {} {} --format=sarif-latest ",
tmp.path().join("dbs/app").display(),
suite.display()
)),
"{calls}"
);
// A suite selecting a table query is refused before the analysis:
// `database analyze` cannot produce its results.
let table = tmp.path().join("Table.ql");
std::fs::write(&table, "select 1").unwrap();
std::fs::write(
&listed,
format!("[\"{}\",\"{}\"]", alert.display(), table.display()),
)
.unwrap();
app.editor.open(&suite).unwrap();
app.run_command(Command::CodeqlRunQuerySuite);
wait_for_codeql(&mut app);
assert!(
app.codeql.history[0].contains("Table.ql"),
"the refusal names the table query: {:?}",
app.codeql.history
);
// "Run Query on Selected Database" takes a suite too.
app.editor.open(&suite).unwrap();
app.run_command(Command::CodeqlRunQuery);
assert!(
app.status.contains("Running s.qls on app"),
"{}",
app.status
);
wait_for_codeql(&mut app);
assert_eq!(
Command::from_id("codeql_run_query_suite"),
Some(Command::CodeqlRunQuerySuite)
);
});
}
#[cfg(unix)]
#[test]
fn codeql_query_help_is_previewed_as_markdown_or_reported_missing() {
// #578: VS Code's "CodeQL: Preview Query Help" renders the open
// query's help with `codeql generate query-help` off the UI thread and
// shows it in the Markdown preview; with no .ql open it takes the
// query of the newest history entry.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "select 1");
let wait = |app: &mut App| {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_codeql_query_help() {
assert!(
std::time::Instant::now() < deadline,
"the query help never landed"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
};
app.codeql_program = fake_codeql(bin.path(), "# Q\n\nFinds things.\n", 0, "");
app.run_command(Command::CodeqlPreviewQueryHelp);
assert_eq!(app.status, "Rendering the help of q.ql\u{2026}");
wait(&mut app);
assert_eq!(app.status, "Query help for q.ql");
let help = croft_cache_dir().join("codeql/help/q.md");
assert_eq!(app.editor.path.as_deref(), Some(help.as_path()));
assert!(app.editor.markdown_preview.is_some());
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert_eq!(
calls.trim(),
format!(
"generate query-help --format=markdown --output={} {}",
help.display(),
tmp.path().join("q.ql").display()
)
);
// No help beside the query: the CLI writes nothing.
seed_codeql_history(
tmp.path(),
&[(
"h.ql",
5,
crate::codeql_query::RunStatus::Succeeded,
App::codeql_results_dir().join("5-h/results.csv"),
)],
);
app.codeql_program = fake_codeql(bin.path(), "", 0, "");
app.run_command(Command::CodeqlPreviewQueryHelp);
assert_eq!(app.status, "Rendering the help of h.ql\u{2026}");
wait(&mut app);
assert_eq!(
app.status,
"h.ql has no query help (no .qhelp or .md beside it)"
);
app.editor.open(&tmp.path().join("q.ql")).unwrap();
app.codeql_program = fake_codeql(bin.path(), "", 2, "ERROR: no help");
app.run_command(Command::CodeqlPreviewQueryHelp);
wait(&mut app);
assert_eq!(app.status, "q.ql has no query help: ERROR: no help");
assert_eq!(
Command::from_id("codeql_preview_query_help"),
Some(Command::CodeqlPreviewQueryHelp)
);
});
}
#[cfg(unix)]
#[test]
fn codeql_pack_commands_install_dependencies_and_download_packs() {
// #578: "Install Pack Dependencies" runs `codeql pack install` on the
// selected pack's folder; "Download Packs" asks which packs and runs
// `codeql pack download` on them. Both off the UI thread.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("pack")).unwrap();
std::fs::write(tmp.path().join("pack/qlpack.yml"), "name: acme/rust\n").unwrap();
std::fs::write(tmp.path().join("pack/a.ql"), "select 1").unwrap();
let mut app = codeql_query_fixture(tmp.path(), "select 1");
app.codeql_program = fake_codeql(bin.path(), "", 0, "");
app.open_codeql_view();
app.run_command(Command::CodeqlInstallPackDependencies);
assert_eq!(
app.status,
"Select a query pack or one of its queries in the CodeQL side bar first"
);
let row = app
.codeql
.lines()
.iter()
.position(|l| {
matches!(
l,
crate::widgets::codeql::Line::Action(
crate::widgets::codeql::Action::RunQuery(0, 0),
_
)
)
})
.expect("a.ql is listed");
app.codeql.selected = row;
app.run_command(Command::CodeqlInstallPackDependencies);
assert_eq!(
app.status,
"Installing the dependencies of acme/rust\u{2026}"
);
app.run_command(Command::CodeqlInstallPackDependencies);
assert_eq!(
app.status,
"A CodeQL pack install or download is already running"
);
let wait = |app: &mut App| {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_codeql_pack_job() {
assert!(
std::time::Instant::now() < deadline,
"the pack job never finished"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
};
wait(&mut app);
assert_eq!(app.status, "Installed the dependencies of acme/rust");
app.run_command(Command::CodeqlDownloadPacks);
for c in "codeql/java-queries codeql/python-all@1.0.0".chars() {
app.input_prompt.as_mut().unwrap().push_char(c);
}
app.submit_input_prompt();
wait(&mut app);
assert_eq!(
app.status,
"Downloaded codeql/java-queries, codeql/python-all@1.0.0"
);
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert_eq!(
calls.lines().collect::<Vec<_>>(),
vec![
format!("pack install {}", tmp.path().join("pack").display()),
String::from("pack download codeql/java-queries codeql/python-all@1.0.0"),
]
);
app.codeql_program = fake_codeql(bin.path(), "", 1, "ERROR: no such pack");
app.run_command(Command::CodeqlDownloadPacks);
for c in "acme/missing".chars() {
app.input_prompt.as_mut().unwrap().push_char(c);
}
app.submit_input_prompt();
wait(&mut app);
assert_eq!(
app.status,
"Could not download acme/missing: ERROR: no such pack"
);
});
}
#[cfg(unix)]
#[test]
fn a_codeql_quick_query_opens_for_the_databases_language() {
// #578: VS Code's "CodeQL: Quick Query". The first time, croft writes
// a scratch pack for the selected database's language and installs its
// library; later it reopens the same file, edits and all.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "select 1");
app.codeql_program = fake_codeql(bin.path(), "", 0, "");
app.run_command(Command::CodeqlQuickQuery);
let query = app.editor.path.clone().expect("the quick query is open");
assert!(
query.ends_with("quick-query/rust/quick-query.ql"),
"{}",
query.display()
);
assert!(app.editor.lines.iter().any(|l| l == "import rust"));
let dir = query.parent().unwrap().to_path_buf();
assert!(
std::fs::read_to_string(dir.join("qlpack.yml"))
.unwrap()
.contains("codeql/rust-all")
);
assert_eq!(
app.status,
"Installing codeql/rust-all for the quick query\u{2026}"
);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_codeql_pack_job() {
assert!(
std::time::Instant::now() < deadline,
"the install never finished"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert_eq!(
app.status,
"Quick query ready: codeql/rust-all is installed"
);
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert_eq!(calls.trim(), format!("pack install {}", dir.display()));
// A real install leaves a lock file, which says it is done.
std::fs::write(dir.join("codeql-pack.lock.yml"), "lockVersion: 1.0.0\n").unwrap();
std::fs::write(&query, "import rust\nselect 2\n").unwrap();
app.run_command(Command::CodeqlQuickQuery);
assert_eq!(app.status, "Opened the rust quick query");
assert!(app.editor.lines.iter().any(|l| l == "select 2"));
assert!(app.codeql_pack_job.is_none(), "no second install");
});
}
#[test]
fn comparing_codeql_results_opens_the_rows_one_run_has_alone() {
// #578: VS Code's "Compare Results". The newest run's table is set
// against the previous run of the same query; the rows only one of
// them has open as a CSV beside the newer results.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::codeql_query::RunStatus;
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let out = |n: &str| App::codeql_results_dir().join(n).join("results.csv");
seed_codeql_history(tmp.path(), &[("q.ql", 1, RunStatus::Succeeded, out("1-q"))]);
app.run_command(Command::CodeqlCompareResults);
assert_eq!(
app.status,
"There is no earlier successful run of q.ql to compare with"
);
seed_codeql_history(
tmp.path(),
&[
("q.ql", 1, RunStatus::Succeeded, out("1-q")),
("q.ql", 2, RunStatus::Succeeded, out("2-q")),
],
);
for (dir, body) in [("1-q", "f\na\nb\n"), ("2-q", "f\nb\nc\n")] {
std::fs::create_dir_all(out(dir).parent().unwrap()).unwrap();
std::fs::write(out(dir), body).unwrap();
}
app.run_command(Command::CodeqlCompareResults);
assert_eq!(app.status, "2 rows differ between the runs");
let compared = out("2-q").with_file_name("compare-1.csv");
assert_eq!(app.editor.path.as_deref(), Some(compared.as_path()));
let text = std::fs::read_to_string(&compared).unwrap();
assert!(text.starts_with("run,f\n"), "{text}");
assert!(text.contains(",a\n") && text.contains(",c\n"), "{text}");
});
}
#[test]
fn codeql_query_history_palette_commands_act_on_the_selected_or_newest_run() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::codeql_query::RunStatus;
use crate::widgets::command_palette::Command;
use crate::widgets::input_prompt::InputPurpose;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(Command::CodeqlRemoveHistory);
assert!(
app.status.contains("no CodeQL query history"),
"{}",
app.status
);
assert!(app.input_prompt.is_none());
let out = |n: &str| App::codeql_results_dir().join(n).join("results.csv");
seed_codeql_history(
tmp.path(),
&[
("a-old.ql", 1, RunStatus::Succeeded, out("1-old")),
("b-new.ql", 2, RunStatus::Succeeded, out("2-new")),
],
);
// Sorted by name, the newest run is no longer on top; it is still
// the one the commands pick.
app.run_command(Command::CodeqlSortHistory);
assert_eq!(app.codeql.history_sort, crate::codeql_query::HistSort::Name);
app.run_command(Command::CodeqlRenameHistory);
assert_eq!(
app.input_prompt.as_ref().map(|p| &p.purpose),
Some(&InputPurpose::CodeqlRenameHistory {
output: out("2-new")
})
);
app.close_input_prompt();
app.run_command(Command::CodeqlViewQuery);
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("b-new.ql").as_path())
);
// A selected row wins over the newest.
app.open_codeql_view();
app.codeql.select_history(0);
app.run_command(Command::CodeqlViewQuery);
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("a-old.ql").as_path())
);
assert_eq!(
Command::from_id("codeql_remove_history"),
Some(Command::CodeqlRemoveHistory)
);
assert_eq!(Command::CodeqlViewQuery.title(), "CodeQL: View Query");
});
}
/// A stand-in `codeql`: logs its arguments, writes `body` to the path its
/// `--output=` names, and exits with `code` (printing `err` on stderr).
#[cfg(unix)]
fn fake_codeql(dir: &std::path::Path, body: &str, code: i32, err: &str) -> std::path::PathBuf {
use std::os::unix::fs::PermissionsExt;
let reply = dir.join("codeql-reply");
std::fs::write(&reply, body).unwrap();
let script = format!(
"#!/bin/sh\necho \"$*\" >> '{log}'\nfor a in \"$@\"; do case \"$a\" in --output=*) cp '{reply}' \"${{a#--output=}}\" ;; esac; done\n[ -n '{err}' ] && echo '{err}' >&2\nexit {code}\n",
log = dir.join("codeql-calls.log").display(),
reply = reply.display(),
);
let bin = dir.join("codeql");
std::fs::write(&bin, script).unwrap();
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
bin
}
/// Drain the query run until it lands, or fail after a few seconds.
fn wait_for_codeql(app: &mut App) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while app.codeql_run.is_some() {
app.drain_codeql_run();
assert!(
std::time::Instant::now() < deadline,
"the query run never finished"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
#[cfg(unix)]
#[test]
fn a_published_codeql_pack_is_downloaded_and_run_on_the_database() {
// #578: "Run Queries in Published Pack": download the pack, analyze
// the database with it (or the part after `:`), open its SARIF.
use crate::widgets::command_palette::Command;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "select 1");
app.codeql_program = fake_codeql(bin.path(), r#"{"runs":[{"results":[{}]}]}"#, 0, "");
app.run_command(Command::CodeqlRunPublishedPack);
let prompt = app.input_prompt.as_mut().expect("which pack");
prompt.value = String::from("python-queries");
app.submit_input_prompt();
assert_eq!(
app.status,
"\"python-queries\" is not a pack: write scope/name"
);
assert!(app.codeql_run.is_none());
app.run_command(Command::CodeqlRunPublishedPack);
app.input_prompt.as_mut().unwrap().value =
String::from("codeql/python-queries@1.8.11:Security/CWE-078");
app.submit_input_prompt();
assert_eq!(
app.status,
"Running codeql/python-queries@1.8.11:Security/CWE-078 on app\u{2026}"
);
wait_for_codeql(&mut app);
assert!(
app.status
.starts_with("codeql/python-queries@1.8.11:Security/CWE-078 finished in "),
"{}",
app.status
);
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
let calls: Vec<&str> = calls.lines().collect();
assert_eq!(calls[0], "pack download codeql/python-queries@1.8.11");
assert!(
calls[1].starts_with(&format!(
"database analyze {} codeql/python-queries@1.8.11:Security/CWE-078 --format=sarif-latest",
tmp.path().join("dbs/app").display()
)),
"{}",
calls[1]
);
let history = crate::codeql_query::History::load(&App::codeql_history_path());
let entry = &history.entries[history.newest().unwrap()];
assert_eq!(entry.status, crate::codeql_query::RunStatus::Succeeded);
assert_eq!(entry.results, Some(1));
assert_eq!(
app.editor.path.as_ref(),
Some(&entry.output),
"its SARIF is open"
);
// A failed download stops before the analysis.
let bin = tempfile::tempdir().unwrap();
app.codeql_program = fake_codeql(bin.path(), "", 2, "A fatal error occurred: no such pack");
app.run_command(Command::CodeqlRunPublishedPack);
app.input_prompt.as_mut().unwrap().value = String::from("acme/missing");
app.submit_input_prompt();
wait_for_codeql(&mut app);
assert!(
app.status.starts_with("acme/missing failed: "),
"{}",
app.status
);
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert_eq!(calls, "pack download acme/missing\n");
});
}
/// Run a published pack's command-injection query through croft against the
/// real CLI and registry (#578), on a Flask app that runs a request argument.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and the pack registry; set CROFT_TEST_CODEQL"]
fn real_published_pack_runs_on_the_selected_database() {
let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(
src.join("app.py"),
"import os\nfrom flask import Flask, request\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef index():\n os.system(request.args[\"cmd\"])\n return \"\"\n",
)
.unwrap();
let db = tmp.path().join("db");
let made = std::process::Command::new(&codeql)
.args(["database", "create", "--language=python", "--source-root"])
.arg(&src)
.arg(&db)
.output()
.unwrap();
assert!(
made.status.success(),
"{}",
String::from_utf8_lossy(&made.stderr)
);
crate::codeql_db::DatabaseStore {
databases: vec![crate::codeql_db::DbEntry {
name: String::from("flask"),
path: db,
language: Some(String::from("python")),
added: 0,
former_names: Vec::new(),
}],
current: Some(0),
sort_by: None,
}
.save(&App::codeql_db_store_path())
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.codeql_program = codeql;
app.run_codeql_published_pack("codeql/python-queries:Security/CWE-078/CommandInjection.ql");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(900);
while app.codeql_run.is_some() {
app.drain_codeql_run();
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(50));
}
let history = crate::codeql_query::History::load(&App::codeql_history_path());
let entry = &history.entries[history.newest().unwrap()];
assert_eq!(
entry.status,
crate::codeql_query::RunStatus::Succeeded,
"{}",
app.status
);
let sarif = std::fs::read_to_string(&entry.output).unwrap();
assert!(
sarif.contains("\"ruleId\":\"py/command-line-injection\""),
"{sarif}"
);
assert_eq!(entry.results, Some(1));
});
}
/// A workspace with `q.ql` open and database "app" current.
fn codeql_query_fixture(tmp: &std::path::Path, source: &str) -> App {
let db = tmp.join("dbs/app");
std::fs::create_dir_all(&db).unwrap();
let store = crate::codeql_db::DatabaseStore {
databases: vec![crate::codeql_db::DbEntry {
name: String::from("app"),
path: db,
language: Some(String::from("rust")),
added: 0,
former_names: Vec::new(),
}],
current: Some(0),
sort_by: None,
};
store.save(&App::codeql_db_store_path()).unwrap();
let q = tmp.join("q.ql");
std::fs::write(&q, source).unwrap();
let mut app = App::new(tmp.to_path_buf()).unwrap();
app.editor.open(&q).unwrap();
app
}
/// Wait for the AST Viewer's read to land, or fail after `secs`.
fn wait_for_codeql_ast(app: &mut App, secs: u64) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(secs);
while !app.drain_codeql_ast() {
assert!(
std::time::Instant::now() < deadline,
"the AST read never finished"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
#[cfg(unix)]
#[test]
fn the_ast_viewer_shows_the_open_files_tree_and_goes_to_its_code() {
// #578: the AST of a source file from the selected database, with
// go-to-code and clear, through a stand-in for the CLI.
use crate::widgets::codeql::{Action, Line};
use std::os::unix::fs::PermissionsExt;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "select 1");
let src = tmp.path().join("app.py");
std::fs::write(&src, "import os\n\ndef run(cmd):\n os.system(cmd)\n").unwrap();
let pack = bin.path().join("rust-all");
std::fs::create_dir_all(&pack).unwrap();
std::fs::write(pack.join("qlpack.yml"), "name: codeql/rust-all\n").unwrap();
let query = pack.join("printAst.ql");
std::fs::write(&query, "select 1").unwrap();
let file = src.display().to_string();
let graph = format!(
r#"{{"nodes": {{"tuples": [
[{{"id": 0, "label": "[Import] import os", "url": {{"uri": "file://{file}", "startLine": 1, "startColumn": 1}}}}, "semmle.order", "1"],
[{{"id": 1, "label": "[FunctionDef] run", "url": {{"uri": "file://{file}", "startLine": 3, "startColumn": 1}}}}, "semmle.order", "2"],
[{{"id": 2, "label": "[Call] os.system(cmd)", "url": {{"uri": "file://{file}", "startLine": 4, "startColumn": 5}}}}, "semmle.label", "[Call] os.system(cmd)"]]}},
"edges": {{"tuples": [
[{{"id": 1}}, {{"id": 2}}, "semmle.label", "body"]]}}}}"#
);
std::fs::write(bin.path().join("graph.json"), graph).unwrap();
let script = format!(
"#!/bin/sh\necho \"$*\" >> '{log}'\ncase \"$1 $2\" in 'resolve queries') echo '[\"{query}\"]'; exit 0 ;; esac\nfor a in \"$@\"; do case \"$a\" in --output=*) cp '{graph}' \"${{a#--output=}}\" ;; --external=selectedSourceFile=*) cp \"${{a#--external=selectedSourceFile=}}\" '{sel}' ;; esac; done\nexit 0\n",
log = bin.path().join("calls.log").display(),
query = query.display(),
graph = bin.path().join("graph.json").display(),
sel = bin.path().join("selected.csv").display(),
);
let program = bin.path().join("codeql");
std::fs::write(&program, script).unwrap();
std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
app.codeql_program = program;
app.editor.open(&src).unwrap();
app.run_command(crate::widgets::command_palette::Command::CodeqlViewAst);
assert_eq!(app.status, "Reading the AST of app.py from app\u{2026}");
wait_for_codeql_ast(&mut app, 10);
assert_eq!(app.status, "AST of app.py: 3 nodes");
let calls = std::fs::read_to_string(bin.path().join("calls.log")).unwrap();
let calls: Vec<&str> = calls.lines().collect();
assert!(
calls[0].starts_with("resolve queries --format=json "),
"{calls:?}"
);
assert_eq!(calls[1], format!("pack install {}", pack.display()));
assert!(calls[2].starts_with("query run --database="), "{calls:?}");
assert!(
calls[3].starts_with("bqrs decode --format=json"),
"{calls:?}"
);
assert_eq!(
std::fs::read_to_string(bin.path().join("selected.csv")).unwrap(),
format!("\"{file}\"\n"),
"the file is named as the source archive names it"
);
app.open_codeql_view();
let rows: Vec<String> = app
.codeql
.lines()
.iter()
.filter_map(|l| match l {
Line::Action(Action::AstNode(_) | Action::ClearAst, text) => Some(text.clone()),
_ => None,
})
.collect();
assert_eq!(
rows,
[
"Clear \u{b7} app.py in app",
" [Import] import os 1:1",
"\u{25b8} [FunctionDef] run 3:1"
]
);
// Enter on the function unfolds it and goes to its code.
let row = app
.codeql
.lines()
.iter()
.position(|l| matches!(l, Line::Action(Action::AstNode(1), _)))
.unwrap();
app.codeql.selected = row;
app.focus = Pane::Tree;
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.path.as_deref(), Some(src.as_path()));
assert_eq!(app.editor.cursor_row, 2);
assert!(app.codeql.lines().iter().any(|l| matches!(
l,
Line::Action(Action::AstNode(2), t) if t == " body: [Call] os.system(cmd) 4:5"
)));
// Clear forgets it.
app.activate_codeql(crate::widgets::codeql::Hit::Action(Action::ClearAst));
assert!(app.codeql.ast.is_none());
});
}
#[cfg(unix)]
#[test]
fn view_cfg_opens_the_control_flow_at_the_cursor_as_a_document() {
// #578: View CFG runs the language pack's print-cfg query for the
// cursor's position and opens the graph as a read-only document.
use std::os::unix::fs::PermissionsExt;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "select 1");
let src = tmp.path().join("app.py");
std::fs::write(&src, "import os\n\ndef run(cmd):\n os.system(cmd)\n").unwrap();
let query = bin.path().join("printCfg.ql");
std::fs::write(&query, "select 1").unwrap();
let reply = serde_json::json!({"mermaid": {"tuples": [[
"flowchart TD\n1[\"Entry\"]\n2[\"Exit\"]\n3[\"os.system(cmd)\"]\n1 --> 3\n3 --> 2"
]]}});
std::fs::write(bin.path().join("cfg.json"), reply.to_string()).unwrap();
let script = format!(
"#!/bin/sh\necho \"$*\" >> '{log}'\ncase \"$1 $2\" in 'resolve queries') echo '[\"{query}\"]'; exit 0 ;; esac\nfor a in \"$@\"; do case \"$a\" in --output=*) cp '{reply}' \"${{a#--output=}}\" ;; --external=selectedSourceLine=*) cp \"${{a#--external=selectedSourceLine=}}\" '{line}' ;; esac; done\nexit 0\n",
log = bin.path().join("calls.log").display(),
query = query.display(),
reply = bin.path().join("cfg.json").display(),
line = bin.path().join("line.csv").display(),
);
let program = bin.path().join("codeql");
std::fs::write(&program, script).unwrap();
std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
app.codeql_program = program;
app.editor.open(&src).unwrap();
app.editor.cursor_row = 2;
app.run_command(crate::widgets::command_palette::Command::CodeqlViewCfg);
assert_eq!(
app.status,
"Reading the control flow graph at app.py:3\u{2026}"
);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_codeql_doc() {
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert_eq!(app.status, "Control flow graph");
let doc = app.editor.path.clone().unwrap();
assert!(doc.starts_with(croft_cache_dir()), "{doc:?}");
let text = app.editor.lines.join("\n");
assert!(
text.starts_with("# Control flow graph of app.py:3:1 in app"),
"{text}"
);
assert!(text.contains("- Entry \u{2192} os.system(cmd)"), "{text}");
assert!(text.contains("```mermaid"), "{text}");
assert_eq!(
std::fs::read_to_string(bin.path().join("line.csv")).unwrap(),
"3\n"
);
let calls = std::fs::read_to_string(bin.path().join("calls.log")).unwrap();
assert!(calls.contains("print-cfg.qls"), "{calls}");
});
}
/// #578's View CFG against the real CLI: the control flow of a Python
/// function, read with the cursor on its definition.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-all; set CROFT_TEST_CODEQL"]
fn view_cfg_reads_a_real_functions_control_flow() {
let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
std::fs::create_dir_all(&src).unwrap();
let file = src.join("app.py");
std::fs::write(&file, "import os\n\ndef run(cmd):\n os.system(cmd)\n").unwrap();
let db = tmp.path().join("db");
let made = std::process::Command::new(&codeql)
.args(["database", "create", "--language=python", "--source-root"])
.arg(&src)
.arg(&db)
.output()
.unwrap();
assert!(
made.status.success(),
"{}",
String::from_utf8_lossy(&made.stderr)
);
crate::codeql_db::DatabaseStore {
databases: vec![crate::codeql_db::DbEntry {
name: String::from("py"),
path: db,
language: Some(String::from("python")),
added: 0,
former_names: Vec::new(),
}],
current: Some(0),
sort_by: None,
}
.save(&App::codeql_db_store_path())
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.codeql_program = codeql;
app.editor.open(&file).unwrap();
app.editor.cursor_row = 2;
app.run_command(crate::widgets::command_palette::Command::CodeqlViewCfg);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(600);
while !app.drain_codeql_doc() {
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert_eq!(app.status, "Control flow graph");
let text = app.editor.lines.join("\n");
assert!(text.contains("- Entry \u{2192} "), "{text}");
assert!(text.contains("Exit"), "{text}");
});
}
#[test]
fn walking_a_codeql_results_table_opens_each_results_code() {
// #578: `codeQLQueryResults` up/down/left/right. The walk moves the
// table's cursor and opens the cell's entity; it goes on after the
// code has the focus, and a sorted table still leads to the right row.
use crate::codeql_query::{CellLoc, RowLocs};
use crate::widgets::command_palette::Command;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("app.py");
std::fs::write(&src, "a = 1\nb = 2\ndef f():\n pass\n").unwrap();
let csv = tmp.path().join("results.csv");
std::fs::write(
&csv,
"\"x\",\"n\"\n\"Name b\",\"2\"\n\"Function f\",\"3\"\n\"plain\",\"9\"\n",
)
.unwrap();
let at = |line: u32, column: u32| {
Some(CellLoc {
path: src.clone(),
line,
column,
})
};
let rows = vec![
RowLocs {
cells: vec!["Name b".into(), "2".into()],
locs: vec![at(2, 1), None],
},
RowLocs {
cells: vec!["Function f".into(), "3".into()],
locs: vec![at(3, 5), None],
},
RowLocs {
cells: vec!["plain".into(), "9".into()],
locs: vec![None, None],
},
];
std::fs::write(
crate::codeql_query::locations_path(&csv),
serde_json::to_string(&rows).unwrap(),
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(Command::CodeqlResultsDown);
assert_eq!(app.status, "Open a CodeQL results table first");
app.editor.open(&csv).unwrap();
// Down from the first row: row 2, "Function f" at 3:5.
app.run_command(Command::CodeqlResultsDown);
assert_eq!(
app.editor.path.as_deref(),
Some(src.as_path()),
"{}",
app.status
);
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (2, 4));
// The code has the focus; the walk goes on in the table: back up.
app.run_command(Command::CodeqlResultsUp);
assert_eq!(app.editor.cursor_row, 1, "{}", app.status);
// Right onto the number column: no location there, so the row's
// entity.
app.run_command(Command::CodeqlResultsRight);
assert_eq!(app.editor.cursor_row, 1, "{}", app.status);
// A row with no entity says so.
app.run_command(Command::CodeqlResultsDown);
app.run_command(Command::CodeqlResultsDown);
assert_eq!(app.status, "Result 3 has no location");
// Sorted by the name column (descending: plain, Name b, Function
// f), the first row still leads to its own code.
app.editor.open(&csv).unwrap();
let data = &mut app.editor.sheet.as_mut().unwrap().sheets[0];
data.cur_col = 0;
data.sort_by_column(0);
data.sort_by_column(0);
data.cur_row = 0;
app.run_command(Command::CodeqlResultsDown);
assert_eq!(
app.editor.path.as_deref(),
Some(src.as_path()),
"{}",
app.status
);
assert_eq!(app.editor.cursor_row, 1, "Name b is on line 2");
});
}
#[test]
fn a_csv_sheet_sorts_by_the_cursors_column_from_the_palette() {
// #578: raw results as a sortable table. Any CSV sheet sorts.
use crate::widgets::command_palette::Command;
let tmp = tempfile::tempdir().unwrap();
let csv = tmp.path().join("results.csv");
std::fs::write(&csv, "name,count\nb,10\nA,9\nc,100\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(Command::SheetSortByColumn);
assert_eq!(app.status, "Open a CSV or TSV file to sort it");
app.editor.open(&csv).unwrap();
let sheet = app.editor.sheet.as_mut().expect("a CSV opens as a sheet");
sheet.sheets[0].cur_col = 1;
app.run_command(Command::SheetSortByColumn);
assert_eq!(app.status, "Sorted by count, ascending");
let rows = |app: &App| -> Vec<String> {
app.editor.sheet.as_ref().unwrap().sheets[0]
.rows
.iter()
.map(|r| r[1].clone())
.collect()
};
assert_eq!(rows(&app), ["9", "10", "100"]);
assert!(app.editor.dirty, "a reorder is an edit");
app.run_command(Command::SheetSortByColumn);
assert_eq!(app.status, "Sorted by count, descending");
assert_eq!(rows(&app), ["100", "10", "9"]);
}
#[test]
fn a_runs_result_sets_are_picked_from_a_list() {
// #578: raw results with a result-set picker. Each set is its own CSV.
use crate::codeql_query::RunStatus;
use crate::widgets::command_palette::Command;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(Command::CodeqlShowResultSet);
assert_eq!(app.status, "No CodeQL query has run yet");
let out = App::codeql_results_dir().join("5-q/results.csv");
seed_codeql_history(
tmp.path(),
&[("q.ql", 5, RunStatus::Succeeded, out.clone())],
);
app.run_command(Command::CodeqlShowResultSet);
assert_eq!(app.status, "q.ql has one result set");
let calls = out.with_file_name("results-calls.csv");
std::fs::write(&calls, "c,s\nx,y\n").unwrap();
app.run_command(Command::CodeqlShowResultSet);
let picker = app.list_picker.as_ref().expect("the picker opens");
assert_eq!(picker.title, "Result sets of q.ql");
let labels: Vec<&str> = picker.rows.iter().map(|r| r.label.as_str()).collect();
assert_eq!(labels, ["#select", "calls"]);
app.list_picker.as_mut().unwrap().selected = 1;
app.confirm_list_picker();
assert_eq!(app.editor.path.as_deref(), Some(calls.as_path()));
assert_eq!(app.status, "Result set calls");
});
}
/// #578's result sets against the real CLI: a query with a `query
/// predicate` beside its `select` gets one CSV per set, not both tables
/// run together in one file.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-all; set CROFT_TEST_CODEQL"]
fn a_real_query_with_two_result_sets_decodes_each_to_its_own_csv() {
let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(
src.join("app.py"),
"def run(cmd):\n print(cmd)\n\nrun(input())\n",
)
.unwrap();
let db = tmp.path().join("db");
let made = std::process::Command::new(&codeql)
.args(["database", "create", "--language=python", "--source-root"])
.arg(&src)
.arg(&db)
.output()
.unwrap();
assert!(
made.status.success(),
"{}",
String::from_utf8_lossy(&made.stderr)
);
crate::codeql_db::DatabaseStore {
databases: vec![crate::codeql_db::DbEntry {
name: String::from("py"),
path: db,
language: Some(String::from("python")),
added: 0,
former_names: Vec::new(),
}],
current: Some(0),
sort_by: None,
}
.save(&App::codeql_db_store_path())
.unwrap();
let pack = tmp.path().join("q");
std::fs::create_dir_all(&pack).unwrap();
std::fs::write(
pack.join("qlpack.yml"),
"name: me/q\nversion: 0.0.1\ndependencies:\n codeql/python-all: \"*\"\n",
)
.unwrap();
let installed = std::process::Command::new(&codeql)
.args(["pack", "install"])
.arg(&pack)
.output()
.unwrap();
assert!(
installed.status.success(),
"{}",
String::from_utf8_lossy(&installed.stderr)
);
let query = pack.join("Two.ql");
std::fs::write(
&query,
"import python\nquery predicate calls(Call c, string s) { s = c.toString() }\nfrom Function f\nselect f, f.getName()\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.codeql_program = codeql;
app.editor.open(&query).unwrap();
app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(600);
while app.codeql_run.is_some() {
app.drain_codeql_run();
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert!(app.status.contains("2 result sets"), "{}", app.status);
let output = app.editor.path.clone().unwrap();
let main = std::fs::read_to_string(&output).unwrap();
assert_eq!(main.lines().next(), Some("\"f\",\"col1\""), "{main}");
assert!(
!main.contains("\"c\",\"s\""),
"only #select in the main CSV: {main}"
);
let calls = std::fs::read_to_string(output.with_file_name("results-calls.csv")).unwrap();
assert_eq!(calls.lines().next(), Some("\"c\",\"s\""), "{calls}");
assert_eq!(calls.lines().count(), 4, "{calls}");
});
}
#[cfg(unix)]
#[test]
fn an_alert_runs_alerts_and_raw_results_open_as_csv_or_sarif_text() {
// #578: Query History's "View Alerts (CSV)", "View Alerts (SARIF)" and
// "View Results (CSV)".
use crate::codeql_query::RunStatus;
use crate::widgets::command_palette::Command;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "select 1");
app.codeql_program = fake_codeql(
bin.path(),
"\"Calls\",,\"warning\",\"A call.\",\"/app.py\",\"4\",\"5\",\"4\",\"18\"\n",
0,
"",
);
let wait = |app: &mut App| {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_codeql_doc() {
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(20));
}
};
let table = App::codeql_results_dir().join("1-t/results.csv");
let alerts = App::codeql_results_dir().join("2-a/results.sarif");
seed_codeql_history(
tmp.path(),
&[
("t.ql", 1, RunStatus::Succeeded, table.clone()),
("Alert.ql", 2, RunStatus::Succeeded, alerts.clone()),
],
);
std::fs::write(&alerts, r#"{"version":"2.1.0","runs":[]}"#).unwrap();
// The newest run is the alert one.
app.run_command(Command::CodeqlViewAlertsSarif);
assert_eq!(app.status, "Alerts of Alert.ql (SARIF)");
assert_eq!(app.editor.path.as_deref(), Some(alerts.as_path()));
assert!(app.editor.sarif.is_none(), "the JSON, not the viewer");
assert_eq!(app.editor.lines[0], r#"{"version":"2.1.0","runs":[]}"#);
app.run_command(Command::CodeqlViewAlertsCsv);
wait(&mut app);
assert_eq!(app.status, "Alerts of Alert.ql (CSV)");
let csv = alerts.with_file_name("alerts.csv");
assert_eq!(app.editor.path.as_deref(), Some(csv.as_path()));
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert_eq!(
calls.lines().last().unwrap(),
format!(
"database interpret-results --format=csv --output={} {} {}",
csv.display(),
tmp.path().join("dbs/app").display(),
tmp.path().join("Alert.ql").display()
)
);
// Raw results come from the BQRS the database keeps.
app.run_command(Command::CodeqlViewResultsCsv);
assert_eq!(
app.status,
"The database no longer keeps the results of Alert.ql"
);
let kept = tmp.path().join("dbs/app/results/me/q/Alert.bqrs");
std::fs::create_dir_all(kept.parent().unwrap()).unwrap();
std::fs::write(&kept, "").unwrap();
app.run_command(Command::CodeqlViewResultsCsv);
wait(&mut app);
assert_eq!(app.status, "Results of Alert.ql (CSV)");
assert_eq!(
app.editor.path.as_deref(),
Some(alerts.with_file_name("raw-results.csv").as_path())
);
// A table run has no alerts; its results are its table.
app.open_codeql_view();
app.codeql.select_history(1);
app.run_command(Command::CodeqlViewAlertsCsv);
assert_eq!(
app.status,
"t.ql did not produce alerts; its results are a table"
);
app.run_command(Command::CodeqlViewResultsCsv);
assert_eq!(app.editor.path.as_deref(), Some(table.as_path()));
});
}
/// #578's alert views against the real CLI: after an alert query runs,
/// its alerts are written as CSV and its raw results decoded, both from
/// what the database keeps.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-all; set CROFT_TEST_CODEQL"]
fn a_real_alert_runs_alerts_and_raw_results_are_viewed_as_csv() {
use crate::widgets::command_palette::Command;
let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(
src.join("app.py"),
"def run(cmd):\n print(cmd)\n\nrun(input())\n",
)
.unwrap();
let db = tmp.path().join("db");
let made = std::process::Command::new(&codeql)
.args(["database", "create", "--language=python", "--source-root"])
.arg(&src)
.arg(&db)
.output()
.unwrap();
assert!(
made.status.success(),
"{}",
String::from_utf8_lossy(&made.stderr)
);
crate::codeql_db::DatabaseStore {
databases: vec![crate::codeql_db::DbEntry {
name: String::from("py"),
path: db,
language: Some(String::from("python")),
added: 0,
former_names: Vec::new(),
}],
current: Some(0),
sort_by: None,
}
.save(&App::codeql_db_store_path())
.unwrap();
let pack = tmp.path().join("q");
std::fs::create_dir_all(&pack).unwrap();
std::fs::write(
pack.join("qlpack.yml"),
"name: me/q\nversion: 0.0.1\ndependencies:\n codeql/python-all: \"*\"\n",
)
.unwrap();
let installed = std::process::Command::new(&codeql)
.args(["pack", "install"])
.arg(&pack)
.output()
.unwrap();
assert!(
installed.status.success(),
"{}",
String::from_utf8_lossy(&installed.stderr)
);
let query = pack.join("Alert.ql");
std::fs::write(
&query,
"/**\n * @name Calls\n * @kind problem\n * @id me/calls\n * @problem.severity warning\n */\nimport python\nfrom Call c\nselect c, \"A call.\"\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.codeql_program = codeql;
app.editor.open(&query).unwrap();
app.run_command(Command::CodeqlRunQuery);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(900);
while app.codeql_run.is_some() {
app.drain_codeql_run();
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert!(app.status.contains("finished"), "{}", app.status);
let wait = |app: &mut App| {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(600);
while !app.drain_codeql_doc() {
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(50));
}
};
app.run_command(Command::CodeqlViewAlertsCsv);
wait(&mut app);
assert_eq!(app.status, "Alerts of Alert.ql (CSV)");
// A CSV opens in the table view; its text is the file's.
let text = std::fs::read_to_string(app.editor.path.as_ref().unwrap()).unwrap();
assert_eq!(text.matches("\"A call.\"").count(), 3, "{text}");
app.run_command(Command::CodeqlViewResultsCsv);
wait(&mut app);
assert_eq!(app.status, "Results of Alert.ql (CSV)");
let text = std::fs::read_to_string(app.editor.path.as_ref().unwrap()).unwrap();
assert!(text.contains("A call."), "{text}");
assert_eq!(text.lines().count(), 4, "a header and three calls: {text}");
});
}
#[cfg(unix)]
#[test]
fn a_qlref_opens_the_query_it_references() {
// #578: "open a referenced file" from a .qlref test file.
use crate::widgets::command_palette::Command;
use std::os::unix::fs::PermissionsExt;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let query = tmp.path().join("src/Alert.ql");
std::fs::create_dir_all(query.parent().unwrap()).unwrap();
std::fs::write(&query, "select 1").unwrap();
let qlref = tmp.path().join("test/A.qlref");
std::fs::create_dir_all(qlref.parent().unwrap()).unwrap();
std::fs::write(&qlref, "Alert.ql\n").unwrap();
let program = bin.path().join("codeql");
std::fs::write(
&program,
format!(
"#!/bin/sh\necho \"$*\" >> '{log}'\necho '{{ \"resolvedPath\" : \"{q}\", \"resolvedPostprocessingPaths\" : [ ] }}'\n",
log = bin.path().join("calls.log").display(),
q = query.display()
),
)
.unwrap();
std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.codeql_program = program;
app.run_command(Command::CodeqlOpenReferencedFile);
assert_eq!(app.status, "Open a .qlref file first");
app.editor.open(&qlref).unwrap();
app.run_command(Command::CodeqlOpenReferencedFile);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_codeql_doc() {
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert_eq!(app.status, "The query A.qlref references");
assert_eq!(app.editor.path.as_deref(), Some(query.as_path()));
let calls = std::fs::read_to_string(bin.path().join("calls.log")).unwrap();
assert_eq!(calls.trim(), format!("resolve qlref {}", qlref.display()));
});
}
/// #578's "open a referenced file" against the real CLI: a test pack's
/// `.qlref` names a query in the query pack it depends on.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-all; set CROFT_TEST_CODEQL"]
fn a_real_qlref_opens_the_query_in_the_pack_it_depends_on() {
let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let ws = tmp.path();
std::fs::write(
ws.join("codeql-workspace.yml"),
"provide:\n - \"*/qlpack.yml\"\n",
)
.unwrap();
std::fs::create_dir_all(ws.join("src")).unwrap();
std::fs::create_dir_all(ws.join("test")).unwrap();
std::fs::write(
ws.join("src/qlpack.yml"),
"name: me/src\nversion: 0.0.1\ndependencies:\n codeql/python-all: \"*\"\n",
)
.unwrap();
let query = ws.join("src/Alert.ql");
std::fs::write(&query, "import python\nselect 1\n").unwrap();
std::fs::write(
ws.join("test/qlpack.yml"),
"name: me/test\nversion: 0.0.1\ndependencies:\n me/src: \"*\"\nextractor: python\ntests: .\n",
)
.unwrap();
let qlref = ws.join("test/A.qlref");
std::fs::write(&qlref, "Alert.ql\n").unwrap();
for dir in ["src", "test"] {
let out = std::process::Command::new(&codeql)
.args(["pack", "install"])
.current_dir(ws.join(dir))
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
}
let mut app = App::new(ws.to_path_buf()).unwrap();
app.codeql_program = codeql;
app.editor.open(&qlref).unwrap();
app.run_command(crate::widgets::command_palette::Command::CodeqlOpenReferencedFile);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300);
while !app.drain_codeql_doc() {
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert_eq!(app.status, "The query A.qlref references");
assert_eq!(
app.editor.path.as_ref().map(|p| p.canonicalize().unwrap()),
Some(query.canonicalize().unwrap())
);
});
}
/// A stand-in `codeql` whose `execute query-server2` speaks the query
/// server's framed JSON-RPC: it answers `registerDatabases`, and answers
/// `runQuery` with `result` (a JSON object), writing `bqrs` to the output
/// path first. Every request is logged to `requests.jsonl`; `bqrs decode`
/// copies `csv` to its output.
#[cfg(unix)]
fn fake_query_server(dir: &std::path::Path, result: &str, csv: &str) -> std::path::PathBuf {
use std::os::unix::fs::PermissionsExt;
std::fs::write(dir.join("result.json"), result).unwrap();
std::fs::write(dir.join("reply.csv"), csv).unwrap();
let script = format!(
r#"#!/usr/bin/env python3
import json, sys, shutil
d = {dir:?}
args = sys.argv[1:]
if args[:2] == ["execute", "query-server2"]:
inp, out = sys.stdin.buffer, sys.stdout.buffer
while True:
n = None
while True:
line = inp.readline()
if not line:
sys.exit(0)
line = line.strip()
if not line and n is not None:
break
if line.lower().startswith(b"content-length:"):
n = int(line.split(b":")[1])
msg = json.loads(inp.read(n))
with open(d + "/requests.jsonl", "a") as f:
f.write(json.dumps(msg) + "\n")
if msg["method"] == "evaluation/runQuery":
open(msg["params"]["body"]["outputPath"], "w").write("bqrs")
res = json.load(open(d + "/result.json"))
else:
res = {{}}
body = json.dumps({{"jsonrpc": "2.0", "id": msg["id"], "result": res}}).encode()
out.write(b"Content-Length: %d\r\n\r\n" % len(body) + body)
out.flush()
for a in args:
if a.startswith("--output="):
shutil.copy(d + "/reply.csv", a[len("--output="):])
"#,
dir = dir.display().to_string()
);
let program = dir.join("codeql");
std::fs::write(&program, script).unwrap();
std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
program
}
#[cfg(unix)]
#[test]
fn quick_evaluation_runs_the_predicate_at_the_cursor_through_the_query_server() {
// #578: Quick Evaluation (and its count) of the predicate under the
// cursor, recorded in the query history like a run.
use crate::widgets::command_palette::Command;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(
tmp.path(),
"import python\n\npredicate isCall(Call c) { exists(c) }\n\nfrom Call c\nwhere isCall(c)\nselect c\n",
);
app.codeql_program = fake_query_server(
bin.path(),
r#"{"resultType": 0, "message": "", "evaluationTime": 384}"#,
"\"c\"\n\"run()\"\n",
);
let query = tmp.path().join("q.ql");
app.editor.cursor_row = 2;
app.editor.cursor_col = 13;
app.run_command(Command::CodeqlQuickEval);
assert_eq!(
app.status,
"Running Quick evaluation of isCall on app\u{2026}"
);
wait_for_codeql(&mut app);
assert!(app.status.contains("finished"), "{}", app.status);
assert!(
app.codeql.history[0].contains("Quick evaluation of isCall"),
"{}",
app.codeql.history[0]
);
let requests: Vec<serde_json::Value> =
std::fs::read_to_string(bin.path().join("requests.jsonl"))
.unwrap()
.lines()
.map(|l| serde_json::from_str(l).unwrap())
.collect();
assert_eq!(requests[0]["method"], "evaluation/registerDatabases");
assert_eq!(requests[1]["method"], "evaluation/runQuery");
let body = &requests[1]["params"]["body"];
assert_eq!(body["queryPath"], query.display().to_string());
assert_eq!(
body["target"]["quickEval"]["quickEvalPos"],
serde_json::json!({"fileName": query.display().to_string(), "line": 3, "column": 11, "endLine": 3, "endColumn": 16})
);
assert!(body["target"]["quickEval"].get("countOnly").is_none());
// The count variant says so, in the request and the history.
app.editor.open(&query).unwrap();
app.editor.cursor_row = 2;
app.editor.cursor_col = 13;
app.run_command(Command::CodeqlQuickEvalCount);
wait_for_codeql(&mut app);
assert!(app.codeql.history[0].contains("Quick evaluation count of isCall"));
let last: serde_json::Value = serde_json::from_str(
std::fs::read_to_string(bin.path().join("requests.jsonl"))
.unwrap()
.lines()
.last()
.unwrap(),
)
.unwrap();
assert_eq!(
last["params"]["body"]["target"]["quickEval"]["countOnly"],
true
);
// The server's refusal is the run's reason.
std::fs::write(
bin.path().join("result.json"),
r#"{"resultType": 2, "message": "ERROR: The selection is not a valid quick-eval target. (q.ql:1,1-6)\n", "evaluationTime": -1}"#,
)
.unwrap();
app.editor.open(&query).unwrap();
app.editor.cursor_row = 0;
app.editor.cursor_col = 2;
app.run_command(Command::CodeqlQuickEval);
wait_for_codeql(&mut app);
assert!(
app.status.ends_with(
"failed: ERROR: The selection is not a valid quick-eval target. (q.ql:1,1-6)"
),
"{}",
app.status
);
// Unsaved edits, and nothing under the cursor, are refused first.
app.editor.open(&query).unwrap();
app.editor.cursor_row = 1;
app.editor.cursor_col = 0;
app.run_command(Command::CodeqlQuickEval);
assert_eq!(
app.status,
"Put the cursor on a predicate, or select an expression"
);
app.editor.dirty = true;
app.run_command(Command::CodeqlQuickEval);
assert!(
app.status.starts_with("Save the query first"),
"{}",
app.status
);
});
}
#[cfg(unix)]
#[test]
fn debugging_a_codeql_query_stops_at_its_first_breakpoint() {
// #578: Debug Query quick-evaluates the predicate at the first
// breakpoint; with none it runs the whole query.
use crate::widgets::command_palette::Command;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(
tmp.path(),
"import python\n\npredicate isCall(Call c) { exists(c) }\n\nfrom Call c\nwhere isCall(c)\nselect c\n",
);
app.codeql_program = fake_query_server(
bin.path(),
r#"{"resultType": 0, "message": "", "evaluationTime": 1}"#,
"\"c\"\n",
);
let query = tmp.path().join("q.ql");
// A breakpoint on a line with no predicate is refused with why.
app.editor
.breakpoints
.entry(query.clone())
.or_default()
.insert(7);
app.run_command(Command::CodeqlDebugQuery);
assert!(
app.status
.starts_with("No predicate at the breakpoint on line 7"),
"{}",
app.status
);
// On the `where` line: the called predicate.
app.editor
.breakpoints
.entry(query.clone())
.or_default()
.insert(6);
app.run_command(Command::CodeqlDebugQuery);
assert_eq!(
app.status,
"Running Quick evaluation of isCall (breakpoint on line 6) on app\u{2026}"
);
wait_for_codeql(&mut app);
let requests = std::fs::read_to_string(bin.path().join("requests.jsonl")).unwrap();
let run: serde_json::Value =
serde_json::from_str(requests.lines().last().unwrap()).unwrap();
assert_eq!(
run["params"]["body"]["target"]["quickEval"]["quickEvalPos"]["line"],
6
);
assert_eq!(
run["params"]["body"]["target"]["quickEval"]["quickEvalPos"]["column"],
7
);
// Without breakpoints the whole query runs, as Run Query does.
app.editor.open(&query).unwrap();
app.editor.breakpoints.clear();
app.run_command(Command::CodeqlDebugQuery);
assert_eq!(app.status, "Running q.ql on app\u{2026}");
wait_for_codeql(&mut app);
});
}
/// #578's quick evaluation against the real CLI's query server: a
/// predicate's tuples, and their count.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-all; set CROFT_TEST_CODEQL"]
fn quick_evaluation_against_a_real_query_server() {
use crate::widgets::command_palette::Command;
let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(
src.join("app.py"),
"def run(cmd):\n print(cmd)\n\nrun(input())\n",
)
.unwrap();
let db = tmp.path().join("db");
let made = std::process::Command::new(&codeql)
.args(["database", "create", "--language=python", "--source-root"])
.arg(&src)
.arg(&db)
.output()
.unwrap();
assert!(
made.status.success(),
"{}",
String::from_utf8_lossy(&made.stderr)
);
crate::codeql_db::DatabaseStore {
databases: vec![crate::codeql_db::DbEntry {
name: String::from("py"),
path: db,
language: Some(String::from("python")),
added: 0,
former_names: Vec::new(),
}],
current: Some(0),
sort_by: None,
}
.save(&App::codeql_db_store_path())
.unwrap();
let pack = tmp.path().join("q");
std::fs::create_dir_all(&pack).unwrap();
std::fs::write(
pack.join("qlpack.yml"),
"name: me/q\nversion: 0.0.1\ndependencies:\n codeql/python-all: \"*\"\n",
)
.unwrap();
let installed = std::process::Command::new(&codeql)
.args(["pack", "install"])
.arg(&pack)
.output()
.unwrap();
assert!(
installed.status.success(),
"{}",
String::from_utf8_lossy(&installed.stderr)
);
let query = pack.join("Quick.ql");
std::fs::write(
&query,
"import python\n\npredicate isCall(Call c) { exists(c) }\n\nfrom Call c\nwhere isCall(c)\nselect c\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.codeql_program = codeql;
let run = |app: &mut App, command: Command| {
app.editor.open(&query).unwrap();
app.editor.cursor_row = 2;
app.editor.cursor_col = 13;
app.run_command(command);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(900);
while app.codeql_run.is_some() {
app.drain_codeql_run();
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert!(app.status.contains("finished"), "{}", app.status);
std::fs::read_to_string(app.editor.path.as_ref().unwrap()).unwrap()
};
let tuples = run(&mut app, Command::CodeqlQuickEval);
assert_eq!(
tuples.lines().count(),
4,
"a header and three calls: {tuples}"
);
let counts = run(&mut app, Command::CodeqlQuickEvalCount);
assert!(counts.contains("\"Total tuples\",3"), "{counts}");
});
}
/// #578's results walk against the real CLI: a table run keeps where its
/// entities are, and walking the table opens their code.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-all; set CROFT_TEST_CODEQL"]
fn a_real_results_table_is_walked_into_the_code() {
let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
std::fs::create_dir_all(&src).unwrap();
let file = src.join("app.py");
std::fs::write(
&file,
"import os\n\ndef run(cmd):\n print(cmd)\n\ndef go():\n run(input())\n",
)
.unwrap();
let db = tmp.path().join("db");
let made = std::process::Command::new(&codeql)
.args(["database", "create", "--language=python", "--source-root"])
.arg(&src)
.arg(&db)
.output()
.unwrap();
assert!(
made.status.success(),
"{}",
String::from_utf8_lossy(&made.stderr)
);
crate::codeql_db::DatabaseStore {
databases: vec![crate::codeql_db::DbEntry {
name: String::from("py"),
path: db,
language: Some(String::from("python")),
added: 0,
former_names: Vec::new(),
}],
current: Some(0),
sort_by: None,
}
.save(&App::codeql_db_store_path())
.unwrap();
let pack = tmp.path().join("q");
std::fs::create_dir_all(&pack).unwrap();
std::fs::write(
pack.join("qlpack.yml"),
"name: me/q\nversion: 0.0.1\ndependencies:\n codeql/python-all: \"*\"\n",
)
.unwrap();
let installed = std::process::Command::new(&codeql)
.args(["pack", "install"])
.arg(&pack)
.output()
.unwrap();
assert!(
installed.status.success(),
"{}",
String::from_utf8_lossy(&installed.stderr)
);
let query = pack.join("Functions.ql");
std::fs::write(
&query,
"import python\nfrom Function f\nselect f, f.getName()\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.codeql_program = codeql;
app.editor.open(&query).unwrap();
app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(900);
while app.codeql_run.is_some() {
app.drain_codeql_run();
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(50));
}
let table = app.editor.path.clone().unwrap();
assert!(
crate::codeql_query::locations_path(&table).is_file(),
"{}",
app.status
);
let data = &mut app.editor.sheet.as_mut().expect("the table").sheets[0];
data.cur_col = 0;
data.sort_by_column(1); // by name: go, run
data.cur_row = 0;
// Right, then Left: back on the first row's entity, `def go`.
app.run_command(crate::widgets::command_palette::Command::CodeqlResultsRight);
app.run_command(crate::widgets::command_palette::Command::CodeqlResultsLeft);
assert_eq!(
app.editor.path.as_ref().map(|p| p.canonicalize().unwrap()),
Some(file.canonicalize().unwrap()),
"{}",
app.status
);
assert_eq!(app.editor.cursor_row, 5, "def go is on line 6");
app.run_command(crate::widgets::command_palette::Command::CodeqlResultsDown);
assert_eq!(app.editor.cursor_row, 2, "def run is on line 3");
});
}
#[cfg(unix)]
#[test]
fn the_model_editor_lists_a_databases_endpoints_by_group() {
// #578: Method Modeling. The language pack's model-editor endpoints
// query runs on the current database, and its endpoints are listed by
// module or class with whether CodeQL models them; Enter goes to one.
use crate::widgets::codeql::{Action, Hit, Line};
use std::os::unix::fs::PermissionsExt;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "select 1");
let src = tmp.path().join("core.py");
std::fs::write(
&src,
"import os\n\ndef run(cmd, shell=True):\n return os.system(cmd)\n",
)
.unwrap();
let query = bin.path().join("FrameworkModeEndpoints.ql");
std::fs::write(&query, "select 1").unwrap();
let rows = format!(
r#"{{"columns":[],"tuples":[
[{{"label":"Function run","url":{{"uri":"file://{f}","startLine":3,"startColumn":1}}}},"mylib","core","run","(cmd,shell)",false,"core.py","",{{"label":"Function"}}],
[{{"label":"Function go","url":{{"uri":"file://{f}","startLine":3,"startColumn":1}}}},"mylib","core.Runner","go","(self,what)",true,"core.py","",{{"label":"InstanceMethod"}}]]}}"#,
f = src.display()
);
std::fs::write(bin.path().join("rows.json"), rows).unwrap();
let script = format!(
"#!/bin/sh\necho \"$*\" >> '{log}'\ncase \"$1 $2\" in 'resolve queries') echo '[\"{query}\"]'; exit 0 ;; esac\nfor a in \"$@\"; do case \"$a\" in --output=*) cp '{rows}' \"${{a#--output=}}\" ;; esac; done\nexit 0\n",
log = bin.path().join("calls.log").display(),
query = query.display(),
rows = bin.path().join("rows.json").display(),
);
let program = bin.path().join("codeql");
std::fs::write(&program, script).unwrap();
std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
app.codeql_program = program;
app.run_command(crate::widgets::command_palette::Command::CodeqlOpenModelEditor);
assert_eq!(app.status, "Reading the endpoints of app\u{2026}");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_codeql_model() {
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert_eq!(app.status, "2 endpoints of app, 1 modeled by CodeQL");
let calls = std::fs::read_to_string(bin.path().join("calls.log")).unwrap();
let calls: Vec<&str> = calls.lines().collect();
assert!(
calls[0].starts_with("resolve queries --format=json "),
"{calls:?}"
);
assert!(calls[1].starts_with("query run --database="), "{calls:?}");
assert!(calls[2].contains("--result-set=#select"), "{calls:?}");
let rows: Vec<(Action, String)> = app
.codeql
.lines()
.into_iter()
.filter_map(|l| match l {
Line::Action(
a
@ (Action::OpenModelEditor | Action::ModelGroup(_) | Action::ModelEndpoint(_)),
t,
) => Some((a, t)),
_ => None,
})
.collect();
let texts: Vec<&str> = rows.iter().map(|(_, t)| t.as_str()).collect();
assert_eq!(
texts,
[
"Refresh \u{b7} app (rust)",
"\u{25be} mylib.core 0/1 modeled",
" \u{25cb} run(cmd,shell)",
"\u{25be} mylib.core.Runner 1/1 modeled",
" \u{2713} go(self,what)",
]
);
// Enter on an endpoint goes to its code.
app.activate_codeql(Hit::Action(rows[2].0));
assert_eq!(app.editor.path.as_deref(), Some(src.as_path()));
assert_eq!(app.editor.cursor_row, 2);
assert_eq!(app.status, "run(cmd,shell) (Function): not modeled");
// A group folds.
app.activate_codeql(Hit::Action(rows[3].0));
assert!(
!app.codeql
.lines()
.iter()
.any(|l| matches!(l, Line::Action(_, t) if t.contains("go(self")))
);
});
}
#[cfg(unix)]
#[test]
fn modeling_an_endpoint_writes_a_model_pack_that_runs_use() {
// #578: the Model Editor models sources, sinks and summaries. A model
// lands in a model pack under .github/codeql/extensions, and query
// runs pass it as a model pack.
use crate::widgets::codeql::{Action, Line};
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "select 1");
app.codeql_program = fake_codeql(bin.path(), "col0\n1\n", 0, "");
app.codeql.model = Some(crate::codeql_model::ModelView {
database: String::from("lib"),
language: String::from("python"),
endpoints: crate::codeql_model::parse_endpoints(
r#"{"tuples":[[{"label":"Function run"},"mylib","core","run","(cmd,shell)",false,"core.py","",{"label":"Function"}]]}"#,
),
..Default::default()
});
app.open_codeql_view();
app.focus = Pane::Tree;
let row = app
.codeql
.lines()
.iter()
.position(|l| matches!(l, Line::Action(Action::ModelEndpoint(0), _)))
.unwrap();
app.codeql.selected = row;
app.handle_key(key(KeyCode::Char('m'), KeyModifiers::NONE))
.unwrap();
let picker = app.list_picker.as_ref().expect("what to model it as");
assert_eq!(picker.title, "Model run(cmd,shell)");
let labels: Vec<&str> = picker.rows.iter().map(|r| r.label.as_str()).collect();
assert_eq!(
labels,
[
"source ReturnValue (remote)",
"sink Argument[0,cmd:] (command-injection)",
"sink Argument[1,shell:] (command-injection)",
"summary Argument[0,cmd:] \u{2192} ReturnValue (taint)",
"summary Argument[1,shell:] \u{2192} ReturnValue (taint)",
]
);
app.list_picker.as_mut().unwrap().selected = 1;
app.confirm_list_picker();
let prompt = app.input_prompt.as_ref().expect("its kind");
assert_eq!(prompt.value, "command-injection");
app.submit_input_prompt();
let pack = tmp.path().join(".github/codeql/extensions/lib-python");
assert!(
app.status
.starts_with("Modeled run(cmd,shell) as a sink Argument[0,cmd:]"),
"{}",
app.status
);
assert_eq!(
std::fs::read_to_string(pack.join("models/lib-python.model.yml")).unwrap(),
"extensions:\n - addsTo:\n pack: codeql/python-all\n extensible: sinkModel\n data:\n - ['mylib', 'Member[core].Member[run].Argument[0,cmd:]', 'command-injection']\n"
);
assert!(
std::fs::read_to_string(pack.join("codeql-pack.yml"))
.unwrap()
.starts_with("name: croft/lib-python\n")
);
assert!(
app.codeql.lines().iter().any(|l| matches!(
l,
Line::Action(Action::ModelEndpoint(0), t) if t == " \u{25cf} run(cmd,shell)"
)),
"marked as modeled by you"
);
// A query run now uses the pack.
app.editor.open(&tmp.path().join("q.ql")).unwrap();
app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
wait_for_codeql(&mut app);
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert!(calls.contains("--model-packs=croft/lib-python"), "{calls}");
// Removing its models empties the extension.
app.open_codeql_view();
app.focus = Pane::Tree;
app.codeql.selected = app
.codeql
.lines()
.iter()
.position(|l| matches!(l, Line::Action(Action::ModelEndpoint(0), _)))
.unwrap();
app.handle_key(key(KeyCode::Char('m'), KeyModifiers::NONE))
.unwrap();
let rows = &app.list_picker.as_ref().unwrap().rows;
let remove = rows
.iter()
.position(|r| r.id == "0:remove")
.expect("remove is offered");
app.list_picker.as_mut().unwrap().selected = remove;
app.confirm_list_picker();
assert!(
app.status
.starts_with("Removed the models of run(cmd,shell)"),
"{}",
app.status
);
assert_eq!(
std::fs::read_to_string(pack.join("models/lib-python.model.yml")).unwrap(),
"extensions:\n []\n"
);
});
}
/// #578's Model Editor end to end against the real CLI: model a library
/// function as a source and another as a sink, and the command-injection
/// query, run through croft, finds the flow it misses without them.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-queries; set CROFT_TEST_CODEQL"]
fn real_models_made_in_the_model_editor_change_what_a_query_finds() {
let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
std::fs::create_dir_all(src.join("mylib")).unwrap();
std::fs::write(src.join("mylib/__init__.py"), "").unwrap();
std::fs::write(
src.join("mylib/core.py"),
"import os\n\ndef run(cmd, shell=True):\n return os.system(cmd)\n\ndef fetch():\n return \"x\"\n",
)
.unwrap();
std::fs::write(
src.join("app.py"),
"from mylib.core import run, fetch\nrun(fetch())\n",
)
.unwrap();
let db = tmp.path().join("db");
let made = std::process::Command::new(&codeql)
.args(["database", "create", "--language=python", "--source-root"])
.arg(&src)
.arg(&db)
.output()
.unwrap();
assert!(
made.status.success(),
"{}",
String::from_utf8_lossy(&made.stderr)
);
crate::codeql_db::DatabaseStore {
databases: vec![crate::codeql_db::DbEntry {
name: String::from("lib"),
path: db,
language: Some(String::from("python")),
added: 0,
former_names: Vec::new(),
}],
current: Some(0),
sort_by: None,
}
.save(&App::codeql_db_store_path())
.unwrap();
let resolved = std::process::Command::new(&codeql)
.args([
"resolve",
"queries",
"--format=json",
"codeql/python-queries:Security/CWE-078/CommandInjection.ql",
])
.output()
.unwrap();
let query = crate::codeql_ast::first_query(&String::from_utf8_lossy(&resolved.stdout))
.expect("the command-injection query");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.codeql_program = codeql;
let run_query = |app: &mut App| -> String {
app.editor.open(&query).unwrap();
app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(900);
while app.codeql_run.is_some() {
app.drain_codeql_run();
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(50));
}
let history = crate::codeql_query::History::load(&App::codeql_history_path());
std::fs::read_to_string(&history.entries[history.newest().unwrap()].output)
.unwrap_or_else(|e| panic!("{e}: {}", app.status))
};
let before = run_query(&mut app);
assert!(before.contains("\"results\":[]"), "no flow yet: {before}");
app.run_command(crate::widgets::command_palette::Command::CodeqlOpenModelEditor);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(900);
while !app.drain_codeql_model() {
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(50));
}
let find = |app: &App, f: &str| {
app.codeql
.model
.as_ref()
.unwrap_or_else(|| panic!("{}", app.status))
.endpoints
.iter()
.position(|e| e.function == f)
.unwrap()
};
let (fetch, run) = (find(&app, "fetch"), find(&app, "run"));
app.choose_codeql_model(&format!("{fetch}:0"));
app.submit_input_prompt(); // remote source at ReturnValue
app.choose_codeql_model(&format!("{run}:1"));
app.submit_input_prompt(); // command-injection sink at Argument[0,cmd:]
let after = run_query(&mut app);
assert!(
after.contains("\"ruleId\":\"py/command-line-injection\""),
"{after}"
);
});
}
/// #578's Model Editor against the real CLI: a Python library's
/// framework-mode endpoints, read from a database built in the test.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-queries; set CROFT_TEST_CODEQL"]
fn the_model_editor_reads_a_real_librarys_endpoints() {
let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
std::fs::create_dir_all(src.join("mylib")).unwrap();
std::fs::write(
src.join("mylib/__init__.py"),
"from .core import run, Runner\n",
)
.unwrap();
std::fs::write(
src.join("mylib/core.py"),
"import os\n\ndef run(cmd, shell=True):\n return os.system(cmd)\n\nclass Runner:\n def go(self, what):\n return run(what)\n",
)
.unwrap();
std::fs::write(
src.join("pyproject.toml"),
"[project]\nname = \"mylib\"\nversion = \"0.1\"\n",
)
.unwrap();
let db = tmp.path().join("db");
let made = std::process::Command::new(&codeql)
.args(["database", "create", "--language=python", "--source-root"])
.arg(&src)
.arg(&db)
.output()
.unwrap();
assert!(
made.status.success(),
"{}",
String::from_utf8_lossy(&made.stderr)
);
crate::codeql_db::DatabaseStore {
databases: vec![crate::codeql_db::DbEntry {
name: String::from("lib"),
path: db,
language: Some(String::from("python")),
added: 0,
former_names: Vec::new(),
}],
current: Some(0),
sort_by: None,
}
.save(&App::codeql_db_store_path())
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.codeql_program = codeql;
app.run_command(crate::widgets::command_palette::Command::CodeqlOpenModelEditor);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(900);
while !app.drain_codeql_model() {
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(50));
}
let view = app
.codeql
.model
.as_ref()
.unwrap_or_else(|| panic!("{}", app.status));
let labels: Vec<String> = view.endpoints.iter().map(|e| e.label()).collect();
assert!(
labels.contains(&String::from("run(cmd,shell)")),
"{labels:?}"
);
assert!(
labels.contains(&String::from("go(self,what)")),
"{labels:?}"
);
let run = view.endpoints.iter().find(|e| e.function == "run").unwrap();
assert_eq!(
(run.namespace.as_str(), run.class.as_str()),
("mylib", "core")
);
assert_eq!(run.location.as_ref().map(|l| l.line), Some(3));
});
}
/// #578's AST Viewer against the real CLI: build a Python database, read
/// the AST of its source file, and find the function in it. Needs a
/// `codeql` with the codeql/python-all pack downloaded; set
/// `CROFT_TEST_CODEQL` to it.
#[cfg(unix)]
#[test]
#[ignore = "needs the CodeQL CLI and codeql/python-all; set CROFT_TEST_CODEQL"]
fn the_ast_viewer_reads_a_real_databases_ast() {
let codeql = std::path::PathBuf::from(std::env::var("CROFT_TEST_CODEQL").unwrap());
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
std::fs::create_dir_all(&src).unwrap();
let file = src.join("app.py");
std::fs::write(&file, "import os\n\ndef run(cmd):\n os.system(cmd)\n").unwrap();
let db = tmp.path().join("db");
let made = std::process::Command::new(&codeql)
.args(["database", "create", "--language=python", "--source-root"])
.arg(&src)
.arg(&db)
.output()
.unwrap();
assert!(
made.status.success(),
"{}",
String::from_utf8_lossy(&made.stderr)
);
crate::codeql_db::DatabaseStore {
databases: vec![crate::codeql_db::DbEntry {
name: String::from("py"),
path: db,
language: Some(String::from("python")),
added: 0,
former_names: Vec::new(),
}],
current: Some(0),
sort_by: None,
}
.save(&App::codeql_db_store_path())
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.codeql_program = codeql;
app.editor.open(&file).unwrap();
app.run_command(crate::widgets::command_palette::Command::CodeqlViewAst);
wait_for_codeql_ast(&mut app, 600);
let view = app
.codeql
.ast
.as_ref()
.unwrap_or_else(|| panic!("{}", app.status));
let def = view
.tree
.roots
.iter()
.copied()
.find(|&i| view.tree.nodes[i].label.starts_with("[FunctionDef] run"))
.expect("the function is a top-level node");
assert_eq!(
view.target(def).map(|t| (t.0, t.1)),
Some((file.clone(), 3))
);
assert!(!view.tree.nodes[def].children.is_empty());
});
}
#[cfg(unix)]
#[test]
fn a_problem_query_runs_on_the_current_database_and_opens_as_sarif() {
// #578: VS Code's "Run Query on Selected Database"; alerts open in the
// SARIF viewer and the run is kept in the query history.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(
tmp.path(),
"/**\n * @kind problem\n */\nimport rust\nselect 1",
);
app.codeql_program = fake_codeql(
bin.path(),
r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"CodeQL"}},"results":[{"ruleId":"q","message":{"text":"From codeql."}}]}]}"#,
0,
"",
);
app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
assert!(app.status.contains("Running q.ql on app"), "{}", app.status);
assert_eq!(app.codeql.history.len(), 1);
assert!(
app.codeql.history[0].contains("running"),
"{:?}",
app.codeql.history
);
wait_for_codeql(&mut app);
// The alerts open as a .sarif file, which the SARIF viewer claims.
let opened = app.editor.path.clone().expect("the results open");
assert_eq!(opened.extension().and_then(|e| e.to_str()), Some("sarif"));
assert!(
std::fs::read_to_string(&opened)
.unwrap()
.contains("From codeql.")
);
assert!(
app.codeql.history[0].starts_with("\u{2713} q.ql \u{b7} app"),
"{:?}",
app.codeql.history
);
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert!(calls.starts_with("database analyze "), "{calls}");
});
}
#[cfg(unix)]
#[test]
fn a_failed_query_run_is_recorded_with_codeqls_own_words() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "import rust\nselect 1");
app.codeql_program = fake_codeql(bin.path(), "", 2, "ERROR: could not resolve module rust");
app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
wait_for_codeql(&mut app);
assert_eq!(
app.codeql.history[0],
"\u{2717} q.ql \u{b7} app \u{b7} failed: ERROR: could not resolve module rust"
);
assert!(
app.status.contains("could not resolve module"),
"{}",
app.status
);
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert!(
calls.starts_with("query run "),
"a table query runs as a query: {calls}"
);
});
}
#[cfg(unix)]
#[test]
fn a_successful_query_run_records_its_result_count() {
// #578: Query History shows how many results a run produced, and can
// sort by it.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "import rust\nselect 1");
app.codeql_program = fake_codeql(bin.path(), "col0\n1\n2\n", 0, "");
app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
wait_for_codeql(&mut app);
let history = crate::codeql_query::History::load(&App::codeql_history_path());
assert_eq!(history.entries[0].results, Some(2), "{}", app.status);
assert!(
app.codeql.history[0].ends_with("\u{b7} 2 results"),
"{}",
app.codeql.history[0]
);
});
}
#[cfg(unix)]
#[test]
fn a_runs_query_text_is_kept_as_it_was_when_it_ran() {
// #578: "View Query Text" shows the query a run used, even after the
// file has changed.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "import rust\nselect 1");
app.codeql_program = fake_codeql(bin.path(), "col0\n1\n", 0, "");
app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
wait_for_codeql(&mut app);
std::fs::write(tmp.path().join("q.ql"), "import rust\nselect 2").unwrap();
app.open_codeql_view();
app.focus = Pane::Tree;
app.codeql.select_history(0);
app.handle_key(key(KeyCode::Char('t'), KeyModifiers::NONE))
.unwrap();
let opened = app.editor.path.clone().expect("the query text opened");
assert!(
opened.starts_with(App::codeql_results_dir()),
"{opened:?}: {}",
app.status
);
assert_eq!(opened.file_name().unwrap(), "q.ql");
assert_eq!(app.editor.lines, ["import rust", "select 1"]);
assert!(
app.status.contains("as it was when it ran"),
"{}",
app.status
);
});
}
#[cfg(unix)]
#[test]
fn codeql_accept_test_output_accepts_the_open_test_or_the_failed_ones() {
// #578: accept a failing CodeQL test's actual output as expected,
// through `codeql test accept`.
use crate::widgets::command_palette::Command;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let dir = tmp.path().join("test/Find");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(tmp.path().join("test/qlpack.yml"), "name: t\ntests: .\n").unwrap();
std::fs::write(dir.join("Find.qlref"), "Find.ql\n").unwrap();
std::fs::write(dir.join("Find.expected"), "old\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.set_codeql_program(fake_codeql(bin.path(), "", 0, ""));
let wait = |app: &mut App| {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_codeql_pack_job() {
assert!(std::time::Instant::now() < deadline, "never finished");
std::thread::sleep(std::time::Duration::from_millis(20));
}
};
assert_eq!(
Command::from_id("codeql_accept_test_output"),
Some(Command::CodeqlAcceptTestOutput)
);
app.run_command(Command::CodeqlAcceptTestOutput);
assert!(
app.status.starts_with("No CodeQL test to accept"),
"{}",
app.status
);
// The open file's test, but no run has left output yet.
app.editor.open(&dir.join("Find.expected")).unwrap();
app.run_command(Command::CodeqlAcceptTestOutput);
assert!(app.status.starts_with("No actual output"), "{}", app.status);
std::fs::write(dir.join("Find.actual"), "new\n").unwrap();
app.run_command(Command::CodeqlAcceptTestOutput);
wait(&mut app);
assert_eq!(app.status, "Accepted the output of Find.qlref as expected");
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert_eq!(
calls.trim(),
format!("test accept {}", dir.join("Find.qlref").display())
);
// With no test file open: the tests the last run failed.
app.editor
.open(&tmp.path().join("test/qlpack.yml"))
.unwrap();
app.testing.apply_case(crate::testing::model::TestCase {
name: String::from("test/Find::Find.qlref"),
status: crate::testing::model::TestStatus::Failed,
});
app.run_command(Command::CodeqlAcceptTestOutput);
wait(&mut app);
assert_eq!(app.status, "Accepted the output of Find.qlref as expected");
});
}
#[test]
fn a_variant_runs_repository_list_is_copied_and_its_logs_opened() {
// #578: for a variant analysis run, copy the repository list and view
// its logs, which live on the controller's GitHub Actions run.
use crate::codeql_submit::{parse_progress, parse_submission, record_submitted};
use crate::widgets::command_palette::Command;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(Command::CodeqlCopyVariantRepoList);
assert_eq!(app.status, "No variant analysis has been submitted yet");
let run = parse_submission(
r#"{"id": 9}"#,
"me/ctl",
std::path::Path::new("/w/Find.ql"),
"python",
0,
)
.unwrap();
record_submitted(&App::codeql_variant_runs_path(), run.clone()).unwrap();
app.run_command(Command::CodeqlCopyVariantRepoList);
assert_eq!(
app.status,
"Variant analysis 9 has not reported its repositories yet"
);
app.run_command(Command::CodeqlViewVariantLogs);
assert!(
app.status.contains("has no Actions run yet"),
"{}",
app.status
);
let mut later = run;
later.id = 10;
later.workflow_run = Some(777);
later.progress = parse_progress(
r#"{"status": "in_progress", "scanned_repositories": [
{"repository": {"full_name": "a/b"}, "analysis_status": "succeeded", "result_count": 1},
{"repository": {"full_name": "c/d"}, "analysis_status": "pending"}]}"#,
)
.ok();
record_submitted(&App::codeql_variant_runs_path(), later).unwrap();
// With no run selected in the side bar: the newest.
app.run_command(Command::CodeqlCopyVariantRepoList);
assert_eq!(
app.status,
"Copied the 2 repositories of variant analysis 10"
);
assert_eq!(crate::clipboard::read_string().unwrap(), "a/b\nc/d");
app.run_command(Command::CodeqlViewVariantLogs);
assert_eq!(
app.status,
"Open https://github.com/me/ctl/actions/runs/777"
);
});
}
#[cfg(unix)]
#[test]
fn a_running_codeql_query_shows_in_the_status_bar_and_a_click_cancels_it() {
// #578: progress and cancellation in the status bar. The run is killed
// mid-flight and recorded as cancelled, not failed.
use crate::widgets::command_palette::Command;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "import rust\nselect 1");
app.run_command(Command::CodeqlCancelRunningQuery);
assert_eq!(app.status, "No CodeQL query is running");
app.codeql_program = fake_codeql(bin.path(), "col0\n1\n", 0, "");
let script = std::fs::read_to_string(&app.codeql_program).unwrap();
std::fs::write(
&app.codeql_program,
script.replace("exit 0", "exec sleep 30"),
)
.unwrap();
app.run_command(Command::CodeqlRunQuery);
let started = std::time::Instant::now();
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let screen = screen_text(&term);
assert!(screen.contains("CodeQL q.ql 0:0"), "{screen}");
let chip = app.status_codeql_rect;
assert!(chip.width > 0, "the chip is a click target");
app.handle_mouse(MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column: chip.x + 1,
row: chip.y,
modifiers: KeyModifiers::NONE,
});
assert!(app.status.starts_with("Cancelling"), "{}", app.status);
wait_for_codeql(&mut app);
assert!(
started.elapsed() < std::time::Duration::from_secs(10),
"killed, not waited out"
);
assert_eq!(app.status, "q.ql cancelled");
let history = crate::codeql_query::History::load(&App::codeql_history_path());
assert_eq!(
history.entries[0].status,
crate::codeql_query::RunStatus::Cancelled
);
assert!(
app.codeql.history[0].ends_with("cancelled"),
"{}",
app.codeql.history[0]
);
term.draw(|f| app.render(f)).unwrap();
assert!(!screen_text(&term).contains("CodeQL q.ql"), "the chip goes");
assert_eq!(app.status_codeql_rect, ratatui::layout::Rect::default());
});
}
#[test]
fn running_a_query_needs_an_open_ql_file_and_a_database() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.rs"), "fn main() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&tmp.path().join("a.rs")).unwrap();
app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
assert!(app.status.contains("Open a .ql query"), "{}", app.status);
std::fs::write(tmp.path().join("q.ql"), "select 1").unwrap();
app.editor.open(&tmp.path().join("q.ql")).unwrap();
app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
assert!(
app.status.contains("Add a CodeQL database"),
"{}",
app.status
);
assert!(app.codeql_run.is_none());
});
}
#[cfg(unix)]
#[test]
fn a_query_history_entry_reopens_its_results() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "select 1");
app.codeql_program = fake_codeql(bin.path(), "col0\n1\n", 0, "");
app.run_command(crate::widgets::command_palette::Command::CodeqlRunQuery);
wait_for_codeql(&mut app);
let results = app.editor.path.clone().unwrap();
assert_eq!(results.extension().and_then(|e| e.to_str()), Some("csv"));
app.editor.open(&tmp.path().join("q.ql")).unwrap();
app.activate_codeql(crate::widgets::codeql::Hit::Action(
crate::widgets::codeql::Action::OpenHistory(0),
));
assert_eq!(app.editor.path.as_deref(), Some(results.as_path()));
});
}
#[cfg(unix)]
#[test]
fn a_query_row_in_the_side_bar_runs_that_file_and_records_it() {
// #578: the Queries section lists the workspace's queries by pack, and
// Enter on one runs it from disk on the current database, whatever the
// editor has open.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("pack")).unwrap();
std::fs::write(
tmp.path().join("pack/qlpack.yml"),
"name: acme/rust\nextractor: rust\n",
)
.unwrap();
std::fs::write(
tmp.path().join("pack/r.ql"),
"/** @kind problem */ select 1",
)
.unwrap();
let mut app = codeql_query_fixture(tmp.path(), "select 1");
app.codeql_program = fake_codeql(bin.path(), r#"{"version":"2.1.0","runs":[]}"#, 0, "");
app.open_codeql_view();
let names: Vec<&str> = app.codeql.queries.iter().map(|p| p.name.as_str()).collect();
assert_eq!(names, vec!["acme/rust", crate::codeql_query::NO_PACK]);
let row = app
.codeql
.lines()
.iter()
.position(|l| {
matches!(l, crate::widgets::codeql::Line::Action(
crate::widgets::codeql::Action::RunQuery(0, 0),
label,
) if label.trim() == "r.ql")
})
.expect("the pack's query is listed");
app.codeql.selected = row;
app.focus = Pane::Tree;
app.handle_codeql_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(app.status.contains("Running r.ql on app"), "{}", app.status);
wait_for_codeql(&mut app);
assert!(
app.codeql.history[0].starts_with("\u{2713} r.ql \u{b7} app"),
"{:?}",
app.codeql.history
);
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert!(
calls.starts_with("database analyze ") && calls.contains("pack/r.ql"),
"the saved file's @kind picks SARIF: {calls}"
);
});
}
/// A workspace whose pack `acme/rust` holds `a.ql`, `b.ql` and `c.ql`,
/// database "app" current, the CodeQL view open on the pack's line, and a
/// stand-in `codeql` in `bin` that fails whatever runs `b.ql`.
#[cfg(unix)]
fn codeql_pack_fixture(tmp: &std::path::Path, bin: &std::path::Path) -> App {
use std::os::unix::fs::PermissionsExt;
let pack = tmp.join("pack");
std::fs::create_dir_all(&pack).unwrap();
std::fs::write(
pack.join("qlpack.yml"),
"name: acme/rust\nextractor: rust\n",
)
.unwrap();
for q in ["a", "b", "c"] {
std::fs::write(pack.join(format!("{q}.ql")), "select 1").unwrap();
}
let mut app = codeql_query_fixture(tmp, "select 1");
let reply = bin.join("codeql-reply");
std::fs::write(&reply, "col0\n1\n").unwrap();
let script = format!(
"#!/bin/sh\necho \"$*\" >> '{log}'\ncase \"$*\" in *b.ql*) echo 'ERROR: b is broken' >&2; exit 1 ;; esac\nfor a in \"$@\"; do case \"$a\" in --output=*) cp '{reply}' \"${{a#--output=}}\" ;; esac; done\nexit 0\n",
log = bin.join("codeql-calls.log").display(),
reply = reply.display(),
);
let program = bin.join("codeql");
std::fs::write(&program, script).unwrap();
std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
app.codeql_program = program;
app.open_codeql_view();
app.focus = Pane::Tree;
let row = app
.codeql
.lines()
.iter()
.position(|l| {
matches!(
l,
crate::widgets::codeql::Line::Action(
crate::widgets::codeql::Action::TogglePack(0),
_
)
)
})
.expect("the pack is listed");
app.codeql.selected = row;
app
}
/// Drain until one query run lands (the next of a pack run may start).
fn drain_one_codeql_run(app: &mut App) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_codeql_run() {
assert!(
std::time::Instant::now() < deadline,
"the query run never finished"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
#[cfg(unix)]
#[test]
fn codeql_runs_every_workspace_query_or_the_ones_selected_in_the_explorer() {
// #578: "run one or all" queries, and run on selected files.
use crate::widgets::command_palette::Command;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_pack_fixture(tmp.path(), bin.path());
let pack = tmp.path().join("pack");
let listed: usize = app.codeql.queries.iter().map(|p| p.queries.len()).sum();
assert!(listed >= 3);
app.run_command(Command::CodeqlRunAllQueries);
assert!(
app.status
.starts_with(&format!("Running CodeQL queries 1/{listed}: ")),
"{}",
app.status
);
while app.codeql_run.is_some() {
drain_one_codeql_run(&mut app);
}
assert_eq!(app.status, format!("Ran {listed} CodeQL queries, 1 failed"));
// Nothing selected in the Explorer that holds a query.
app.tree.marked.clear();
app.tree.marked.insert(tmp.path().join("pack/qlpack.yml"));
app.run_command(Command::CodeqlRunSelectedQueries);
assert!(app.status.starts_with("Select .ql files"), "{}", app.status);
// Two files, listed out of order.
app.tree.marked.clear();
app.tree.marked.insert(pack.join("c.ql"));
app.tree.marked.insert(pack.join("a.ql"));
app.run_command(Command::CodeqlRunSelectedQueries);
assert_eq!(
app.status,
"Running CodeQL queries 1/2: a.ql on app\u{2026}"
);
drain_one_codeql_run(&mut app);
assert_eq!(
app.status,
"Running CodeQL queries 2/2: c.ql on app\u{2026}"
);
drain_one_codeql_run(&mut app);
assert_eq!(app.status, "Ran 2 CodeQL queries");
});
}
#[cfg(unix)]
#[test]
fn a_codeql_query_runs_on_each_database_checked_in_the_list() {
// #578: "Run Query on Multiple Databases": check databases in a list,
// and the open query, as edited, runs on each in the list's order.
use crate::widgets::command_palette::Command;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "select 1");
app.codeql_program = fake_codeql(bin.path(), "col0\n1\n", 0, "");
let mut store = crate::codeql_db::DatabaseStore::load(&App::codeql_db_store_path());
for name in ["lib", "gone"] {
let path = tmp.path().join("dbs").join(name);
std::fs::create_dir_all(&path).unwrap();
store.databases.push(crate::codeql_db::DbEntry {
name: name.to_string(),
path,
language: None,
added: 0,
former_names: Vec::new(),
});
}
store.save(&App::codeql_db_store_path()).unwrap();
app.editor.lines[0] = String::from("select 2");
app.run_command(Command::CodeqlRunQueryOnDatabases);
let labels = |app: &App| -> Vec<String> {
let picker = app.list_picker.as_ref().expect("the databases");
picker.rows.iter().map(|r| r.label.clone()).collect()
};
assert_eq!(
app.list_picker.as_ref().unwrap().title,
"Run q.ql on databases"
);
assert_eq!(
labels(&app),
[
"\u{25b6} Run on the checked database",
"[x] app (rust)",
"[ ] lib",
"[ ] gone",
]
);
// Check lib and gone, the cursor staying on the row picked.
for row in [2, 3] {
app.list_picker.as_mut().unwrap().selected = row;
app.confirm_list_picker();
assert_eq!(app.list_picker.as_ref().unwrap().selected, row);
}
assert_eq!(labels(&app)[0], "\u{25b6} Run on the 3 checked databases");
assert_eq!(labels(&app)[3], "[x] gone");
// Unchecking all of them refuses to run.
for row in [1, 2, 3] {
app.list_picker.as_mut().unwrap().selected = row;
app.confirm_list_picker();
}
app.list_picker.as_mut().unwrap().selected = 0;
app.confirm_list_picker();
assert_eq!(app.status, "Check at least one database to run on");
for row in [3, 2, 1] {
app.list_picker.as_mut().unwrap().selected = row;
app.confirm_list_picker();
}
app.list_picker.as_mut().unwrap().selected = 0;
app.confirm_list_picker();
assert!(app.list_picker.is_none());
assert_eq!(
app.status,
"Running CodeQL queries 1/3: q.ql on app\u{2026}"
);
// gone disappears before its turn: skipped, the rest still run.
let mut store = crate::codeql_db::DatabaseStore::load(&App::codeql_db_store_path());
store.databases.retain(|db| db.name != "gone");
store.save(&App::codeql_db_store_path()).unwrap();
drain_one_codeql_run(&mut app);
assert_eq!(
app.status,
"Running CodeQL queries 2/3: q.ql on lib\u{2026}"
);
drain_one_codeql_run(&mut app);
assert!(app.codeql_run.is_none());
assert_eq!(app.status, "Ran 3 CodeQL queries, 1 failed");
let history = crate::codeql_query::History::load(&App::codeql_history_path());
let ran: Vec<&str> = history
.entries
.iter()
.map(|e| e.database.as_str())
.collect();
assert_eq!(ran.len(), 2);
assert!(ran.contains(&"app") && ran.contains(&"lib"), "{ran:?}");
for e in &history.entries {
let text =
std::fs::read_to_string(crate::codeql_query::query_text_path(&e.output, &e.query))
.unwrap();
assert_eq!(text, "select 2", "the buffer, not the file");
}
});
}
#[cfg(unix)]
#[test]
fn running_a_codeql_pack_runs_each_query_in_turn_past_a_failure() {
// #578: `r` on a pack line queues every query in it; each run lands in
// the query history in order and a failing one doesn't stop the rest.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_pack_fixture(tmp.path(), bin.path());
let pack = tmp.path().join("pack");
assert_eq!(
app.codeql.queries[0].queries,
vec![pack.join("a.ql"), pack.join("b.ql"), pack.join("c.ql")]
);
app.handle_codeql_key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE));
assert_eq!(
app.status,
"Running CodeQL queries 1/3: a.ql on app\u{2026}"
);
drain_one_codeql_run(&mut app);
assert_eq!(
app.status,
"Running CodeQL queries 2/3: b.ql on app\u{2026}"
);
drain_one_codeql_run(&mut app);
assert_eq!(
app.status,
"Running CodeQL queries 3/3: c.ql on app\u{2026}"
);
drain_one_codeql_run(&mut app);
assert_eq!(app.status, "Ran 3 CodeQL queries, 1 failed");
assert!(app.codeql_run.is_none());
assert!(app.codeql_run_queue.is_empty());
// Newest first: one entry per query, in the order they ran.
assert_eq!(app.codeql.history.len(), 3, "{:?}", app.codeql.history);
assert!(app.codeql.history[2].starts_with("\u{2713} a.ql \u{b7} app"));
assert_eq!(
app.codeql.history[1],
"\u{2717} b.ql \u{b7} app \u{b7} failed: ERROR: b is broken"
);
assert!(app.codeql.history[0].starts_with("\u{2713} c.ql \u{b7} app"));
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
let at = |q: &str| calls.find(&format!("pack/{q}.ql")).unwrap();
assert!(at("a") < at("b") && at("b") < at("c"), "{calls}");
});
}
#[cfg(unix)]
#[test]
fn queued_codeql_queries_are_cancelled_from_the_palette_or_with_esc() {
// #578: cancelling drops the queries still waiting; the one running
// finishes and is recorded.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_pack_fixture(tmp.path(), bin.path());
app.run_command(Command::CodeqlRunPack);
assert!(app.status.contains("1/3"), "{}", app.status);
app.run_command(Command::CodeqlCancelQueue);
assert_eq!(app.status, "Cancelled 2 queued CodeQL queries");
wait_for_codeql(&mut app);
assert_eq!(app.codeql.history.len(), 1, "{:?}", app.codeql.history);
assert!(app.codeql.history[0].starts_with("\u{2713} a.ql"));
// Esc in the side bar cancels first and leaves the view only after.
app.set_sidebar_view(SidebarView::CodeQL);
app.focus = Pane::Tree;
app.handle_codeql_key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE));
app.handle_codeql_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
assert_eq!(app.status, "Cancelled 2 queued CodeQL queries");
assert!(app.sidebar_view == SidebarView::CodeQL);
wait_for_codeql(&mut app);
assert_eq!(app.codeql.history.len(), 2, "{:?}", app.codeql.history);
app.run_command(Command::CodeqlCancelQueue);
assert_eq!(app.status, "No CodeQL queries are queued");
app.handle_codeql_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
assert!(app.sidebar_view == SidebarView::Explorer);
assert_eq!(
Command::from_id("codeql_run_pack"),
Some(Command::CodeqlRunPack)
);
assert_eq!(
Command::CodeqlRunPack.title(),
"CodeQL: Run Queries in Pack"
);
assert_eq!(
Command::CodeqlCancelQueue.title(),
"CodeQL: Cancel Queued Queries"
);
});
}
#[cfg(unix)]
#[test]
fn running_a_codeql_pack_is_refused_while_a_query_runs_or_without_a_database() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_pack_fixture(tmp.path(), bin.path());
// A single query is running: the pack run is refused, not mixed in.
app.run_command(Command::CodeqlRunQuery);
assert!(app.codeql_run.is_some());
app.handle_codeql_key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE));
assert_eq!(app.status, "A CodeQL query is already running");
assert!(app.codeql_run_queue.is_empty());
wait_for_codeql(&mut app);
assert_eq!(app.codeql.history.len(), 1);
// Nothing selected in the Queries section.
app.codeql.selected = 0;
app.run_command(Command::CodeqlRunPack);
assert!(app.status.contains("Select a query pack"), "{}", app.status);
// No current database: nothing is queued or recorded.
let mut store = crate::codeql_db::DatabaseStore::load(&App::codeql_db_store_path());
store.current = None;
store.save(&App::codeql_db_store_path()).unwrap();
app.open_codeql_view();
let row = app
.codeql
.lines()
.iter()
.position(|l| {
matches!(
l,
crate::widgets::codeql::Line::Action(
crate::widgets::codeql::Action::RunQuery(0, 1),
_
)
)
})
.expect("b.ql is listed");
app.codeql.selected = row;
app.run_command(Command::CodeqlRunPack);
assert_eq!(app.status, "Add a CodeQL database and select it first");
assert!(app.codeql_run.is_none());
assert!(app.codeql_run_queue.is_empty());
assert_eq!(app.codeql.history.len(), 1);
});
}
#[cfg(unix)]
#[test]
fn codeql_run_tests_runs_the_test_pack_through_the_testing_view() {
// #578: "CodeQL: Run Tests" runs every CodeQL test with the app's
// `codeql`, and the results land in the Testing view; outside a
// CodeQL test workspace it says why nothing ran.
// Opening the CodeQL view reads croft's cache, whose test override is
// process-global: without the lock and a cache of its own, this test
// reads whatever another CodeQL test has there at the time.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
use crate::testing::model::TestStatus;
use crate::widgets::command_palette::Command;
use std::os::unix::fs::PermissionsExt;
assert_eq!(
Command::from_id("codeql_run_tests"),
Some(Command::CodeqlRunTests)
);
assert_eq!(Command::CodeqlRunTests.title(), "CodeQL: Run Tests");
let plain = tempfile::tempdir().unwrap();
let mut app = App::new(plain.path().to_path_buf()).unwrap();
app.run_command(Command::CodeqlRunTests);
assert!(
app.status.starts_with("No CodeQL tests here"),
"{}",
app.status
);
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::create_dir_all(root.join("test/Bad")).unwrap();
std::fs::write(
root.join("test/qlpack.yml"),
"name: acme/tests\nextractor: rust\ntests: .\n",
)
.unwrap();
std::fs::write(root.join("test/Bad/Bad.ql"), "select 1").unwrap();
std::fs::write(root.join("test/Bad/Bad.expected"), "").unwrap();
let bin = tempfile::tempdir().unwrap();
let log = bin.path().join("calls.log");
let program = bin.path().join("codeql");
std::fs::write(
&program,
format!(
"#!/bin/sh\necho \"$*\" >> '{log}'\n\
echo '[1/1 comp 1s eval 9ms] FAILED(RESULT) {root}/test/Bad/Bad.ql'\n\
echo '--- expected'\necho '+++ actual'\necho '+| 1 |'\n\
echo '0 tests passed; 1 tests failed:'\nexit 1\n",
log = log.display(),
root = root.display(),
),
)
.unwrap();
std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut app = App::new(root.clone()).unwrap();
app.set_codeql_program(program.clone());
app.run_command(Command::CodeqlRunTests);
assert_eq!(app.status, "Running CodeQL tests");
assert!(app.sidebar_view == SidebarView::Testing);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
let _ = app.test_worker.drain(&mut app.testing);
if !app.testing.is_busy()
&& app
.testing
.cases_for_test()
.contains(&(String::from("test/Bad::Bad.ql"), TestStatus::Failed))
{
break;
}
assert!(
std::time::Instant::now() < deadline,
"the CodeQL run never reported; cases: {:?}",
app.testing.cases_for_test()
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert_eq!(app.testing.failed_count(), 1);
assert_eq!(std::fs::read_to_string(&log).unwrap(), "test run test\n");
});
}
#[cfg(unix)]
#[test]
fn a_codeql_test_clicked_in_the_tree_runs_with_the_configured_codeql() {
// #578: the test worker learns the app's `codeql` when it starts and
// whenever it changes, so a tree click runs the configured program
// (never PATH's) without "CodeQL: Run Tests" having run first.
use crate::testing::model::TestStatus;
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::create_dir_all(root.join("test/Find")).unwrap();
std::fs::write(root.join("test/qlpack.yml"), "name: acme/tests\ntests: .\n").unwrap();
std::fs::write(root.join("test/Find/Find.qlref"), "Find.ql\n").unwrap();
std::fs::write(root.join("test/Find/Find.expected"), "").unwrap();
let bin = tempfile::tempdir().unwrap();
let log = bin.path().join("calls.log");
let program = bin.path().join("codeql");
std::fs::write(
&program,
format!(
"#!/bin/sh\necho \"$*\" >> '{log}'\n\
echo '[1/1 comp 1s eval 9ms] PASSED {root}/test/Find/Find.qlref'\nexit 0\n",
log = log.display(),
root = root.display(),
),
)
.unwrap();
std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut app = App::new(root.clone()).unwrap();
app.set_codeql_program(program);
app.run_test(String::from("test/Find::Find.qlref"));
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
let _ = app.test_worker.drain(&mut app.testing);
if app.testing.status_of("test/Find::Find.qlref") == Some(TestStatus::Passed) {
break;
}
assert!(
std::time::Instant::now() < deadline,
"the clicked test never ran with the configured codeql; cases: {:?}",
app.testing.cases_for_test()
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert_eq!(
std::fs::read_to_string(&log).unwrap(),
"test run test/Find/Find.qlref\n"
);
}
#[cfg(unix)]
#[test]
fn copy_codeql_version_copies_croft_the_cli_and_the_platform() {
// Opening the CodeQL view reads croft's cache, whose test override is
// process-global: without the lock and a cache of its own, this test
// reads whatever another CodeQL test has there at the time.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.codeql_program = fake_codeql(bin.path(), "", 0, "");
// The fake prints nothing on stdout; give it a version to report.
let script = std::fs::read_to_string(&app.codeql_program).unwrap();
std::fs::write(
&app.codeql_program,
script.replace("exit 0", "echo 2.19.3\nexit 0"),
)
.unwrap();
app.run_command(crate::widgets::command_palette::Command::CodeqlCopyVersion);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_codeql_version() {
assert!(
std::time::Instant::now() < deadline,
"the version check never finished"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert_eq!(app.status, "Copied CodeQL version information");
let clip = crate::clipboard::read_string().unwrap();
assert!(clip.contains(concat!("croft version: ", env!("CARGO_PKG_VERSION"))));
assert!(clip.contains("CodeQL CLI version: 2.19.3"));
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert_eq!(calls.trim(), "version --format=terse");
});
}
/// Offline stand-ins for the CodeQL CLI's network calls (#578): the
/// latest release is `latest`, and a download copies `zip` (or fails with
/// `offline` when there is none), noting each URL asked for in `urls`.
fn offline_codeql_net(
latest: &str,
zip: Option<std::path::PathBuf>,
urls: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
) -> crate::codeql_cli::Net {
let latest = latest.to_string();
crate::codeql_cli::Net {
latest: std::sync::Arc::new(move || Ok(latest.clone())),
download: std::sync::Arc::new(move |url, dest, progress| {
urls.lock().unwrap().push(url.to_string());
let zip = zip.as_ref().ok_or_else(|| String::from("offline"))?;
let n = std::fs::copy(zip, dest).map_err(|e| e.to_string())?;
progress(n);
Ok(())
}),
}
}
/// Drain the CLI download until it lands, or fail after a few seconds.
fn wait_for_codeql_cli_download(app: &mut App) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while app.codeql_cli_download.is_some() {
app.drain_codeql_cli_download();
assert!(
std::time::Instant::now() < deadline,
"the CLI download never finished"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
/// Drain the CLI update check until it lands, or fail after a few seconds.
fn wait_for_codeql_cli_check(app: &mut App) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_codeql_cli_check() {
assert!(
std::time::Instant::now() < deadline,
"the CLI update check never finished"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
#[cfg(unix)]
#[test]
fn codeql_cli_update_check_then_download_switches_to_the_managed_cli() {
// #578: "Check for CLI Updates" compares the latest release with the
// CLI in use; "Download CLI" then installs that release into the cache
// and runs it from then on, for the Testing view's CodeQL tests too.
let _guard = relay_test_lock()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let home = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let zip = bin.path().join("release.zip");
crate::codeql_cli::write_test_archive(&zip, "#!/bin/sh\necho 2.30.0\n");
let urls = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
with_relay_home(home.path(), || {
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.codeql_cli_net = offline_codeql_net("2.30.0", Some(zip.clone()), urls.clone());
let on_path = fake_codeql(bin.path(), "", 0, "");
let script = std::fs::read_to_string(&on_path).unwrap();
std::fs::write(&on_path, script.replace("exit 0", "echo 2.19.3\nexit 0")).unwrap();
app.set_codeql_program(on_path);
app.codeql_cli_source = crate::codeql_cli::Source::Path;
app.run_command(crate::widgets::command_palette::Command::CodeqlCheckCliUpdates);
wait_for_codeql_cli_check(&mut app);
assert_eq!(
app.status,
"CodeQL CLI v2.30.0 is available \u{2014} run CodeQL: Download CLI to install it"
);
app.start_codeql_cli_download("codeql-linux64.zip");
wait_for_codeql_cli_download(&mut app);
assert_eq!(
app.status,
"Installed CodeQL CLI v2.30.0 and switched to it"
);
let root = crate::codeql_cli::cli_root(&home.path().join(".cache").join("croft"));
assert_eq!(
urls.lock().unwrap().as_slice(),
[crate::codeql_cli::download_url(
"2.30.0",
"codeql-linux64.zip"
)]
);
assert_eq!(
app.codeql_program,
crate::codeql_cli::managed_program(&root, "2.30.0")
);
assert!(!root.join("2.30.0.download.zip").exists());
// The managed copy's folder names its version, so the next check
// does not need to run it.
app.run_command(crate::widgets::command_palette::Command::CodeqlCheckCliUpdates);
wait_for_codeql_cli_check(&mut app);
assert_eq!(app.status, "The CodeQL CLI is up to date (v2.30.0)");
// Downloading an installed release reuses it.
app.start_codeql_cli_download("codeql-linux64.zip");
wait_for_codeql_cli_download(&mut app);
assert_eq!(
app.status,
"Installed CodeQL CLI v2.30.0 and switched to it"
);
assert_eq!(urls.lock().unwrap().len(), 1);
});
}
#[cfg(unix)]
#[test]
fn codeql_cli_download_keeps_the_settings_cli_and_reports_failures() {
// #578: a CLI named in settings always wins over the downloaded one,
// and a failed download says why on the status line.
let _guard = relay_test_lock()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let home = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let urls = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
with_relay_home(home.path(), || {
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.codeql_cli_net = offline_codeql_net("2.30.0", None, urls.clone());
app.start_codeql_cli_download("codeql-linux64.zip");
wait_for_codeql_cli_download(&mut app);
assert_eq!(
app.status,
"Could not install the CodeQL CLI: download failed: offline"
);
assert_eq!(app.codeql_program, std::path::PathBuf::from("codeql"));
let zip = bin.path().join("release.zip");
crate::codeql_cli::write_test_archive(&zip, "#!/bin/sh\necho 2.30.0\n");
app.codeql_cli_net = offline_codeql_net("2.30.0", Some(zip), urls.clone());
let mine = fake_codeql(bin.path(), "", 0, "");
app.codeql_cli_setting = Some(mine.display().to_string());
app.resolve_codeql_cli();
assert_eq!(app.codeql_cli_source, crate::codeql_cli::Source::Settings);
// No check has run, so the pinned release is the one installed.
app.start_codeql_cli_download("codeql-linux64.zip");
wait_for_codeql_cli_download(&mut app);
assert_eq!(
app.status,
format!(
"Installed CodeQL CLI v{}; codeql_cli_path in settings still takes precedence",
crate::codeql_cli::PINNED_VERSION
)
);
assert_eq!(app.codeql_program, mine);
// Cleared from settings, the managed copy is found at the next
// resolution (PATH aside).
app.codeql_cli_setting = None;
let resolved = crate::codeql_cli::resolve(None, None, None, &crate::app::croft_cache_dir());
assert_eq!(
resolved.source,
crate::codeql_cli::Source::Managed(crate::codeql_cli::PINNED_VERSION.into())
);
});
}
/// Drain the database upgrade until it lands, or fail after a few seconds.
fn wait_for_codeql_upgrade(app: &mut App) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !app.drain_codeql_upgrade() {
assert!(
std::time::Instant::now() < deadline,
"the upgrade never finished"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
#[cfg(unix)]
#[test]
fn upgrading_a_codeql_database_runs_the_cli_off_the_ui_thread() {
// #578: VS Code's "CodeQL: Upgrade Database". `u` on a database row
// runs `codeql database upgrade` on a worker; the status line says how
// it went, with the CLI's first error line when it failed. An upgrade
// and a query run never overlap.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "select 1");
app.codeql_program = fake_codeql(bin.path(), "", 0, "");
app.open_codeql_view();
app.focus = Pane::Tree;
app.codeql.select_database(0);
let u = KeyEvent::new(KeyCode::Char('u'), KeyModifiers::NONE);
app.handle_codeql_key(u);
assert_eq!(app.status, "Upgrading CodeQL database app\u{2026}");
app.handle_codeql_key(u);
assert_eq!(app.status, "A CodeQL database upgrade is already running");
app.run_command(Command::CodeqlRunQuery);
assert_eq!(app.status, "Wait for the CodeQL database upgrade to finish");
assert!(app.codeql_run.is_none());
wait_for_codeql_upgrade(&mut app);
assert_eq!(app.status, "Upgraded CodeQL database app");
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
assert_eq!(
calls.trim(),
format!("database upgrade {}", tmp.path().join("dbs/app").display())
);
app.codeql_program = fake_codeql(bin.path(), "", 1, "ERROR: the database is too new");
app.run_command(Command::CodeqlUpgradeDatabase);
wait_for_codeql_upgrade(&mut app);
assert_eq!(
app.status,
"Could not upgrade CodeQL database app: ERROR: the database is too new"
);
// A query is running: the upgrade waits its turn.
app.codeql_program = fake_codeql(bin.path(), "col0\n1\n", 0, "");
app.run_command(Command::CodeqlRunQuery);
assert!(app.codeql_run.is_some());
app.run_command(Command::CodeqlUpgradeDatabase);
assert_eq!(
app.status,
"Wait for the CodeQL query run to finish before upgrading"
);
assert!(app.codeql_upgrade.is_none());
wait_for_codeql(&mut app);
assert_eq!(
Command::from_id("codeql_upgrade_database"),
Some(Command::CodeqlUpgradeDatabase)
);
assert_eq!(
Command::CodeqlUpgradeDatabase.title(),
"CodeQL: Upgrade Database"
);
});
}
#[cfg(unix)]
#[test]
fn the_codeql_cache_commands_clean_up_the_selected_database() {
// #578: VS Code's "CodeQL: Clear Cache", "Trim Cache" and "Trim Cache
// to Overlay Base" run `codeql database cleanup` on the selected
// database, one job at a time and never beside a query run.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let mut app = codeql_query_fixture(tmp.path(), "select 1");
app.codeql_program = fake_codeql(bin.path(), "", 0, "");
app.open_codeql_view();
app.codeql.select_database(0);
let db = tmp.path().join("dbs/app");
app.run_command(Command::CodeqlClearCache);
assert_eq!(
app.status,
"Clearing the cache of CodeQL database app\u{2026}"
);
app.run_command(Command::CodeqlUpgradeDatabase);
assert_eq!(
app.status,
"A CodeQL database cache cleanup is already running"
);
app.run_command(Command::CodeqlRunQuery);
assert_eq!(
app.status,
"Wait for the CodeQL database cache cleanup to finish"
);
wait_for_codeql_upgrade(&mut app);
assert_eq!(app.status, "Cleared the cache of CodeQL database app");
app.run_command(Command::CodeqlTrimCache);
wait_for_codeql_upgrade(&mut app);
assert_eq!(app.status, "Trimmed the cache of CodeQL database app");
app.run_command(Command::CodeqlTrimCacheToOverlay);
wait_for_codeql_upgrade(&mut app);
assert_eq!(
app.status,
"Trimmed the cache of CodeQL database app to its overlay base"
);
let calls = std::fs::read_to_string(bin.path().join("codeql-calls.log")).unwrap();
let expected: Vec<String> = ["clear", "trim", "overlay"]
.iter()
.map(|m| format!("database cleanup --cache-cleanup={m} {}", db.display()))
.collect();
assert_eq!(calls.lines().collect::<Vec<_>>(), expected);
app.codeql_program = fake_codeql(bin.path(), "", 1, "ERROR: the cache is locked");
app.run_command(Command::CodeqlTrimCache);
wait_for_codeql_upgrade(&mut app);
assert_eq!(
app.status,
"Could not clean up the cache of CodeQL database app: ERROR: the cache is locked"
);
app.codeql_program = fake_codeql(bin.path(), "col0\n1\n", 0, "");
app.run_command(Command::CodeqlRunQuery);
app.run_command(Command::CodeqlClearCache);
assert_eq!(
app.status,
"Wait for the CodeQL query run to finish before cleaning up the cache"
);
assert!(app.codeql_upgrade.is_none());
wait_for_codeql(&mut app);
assert_eq!(
Command::from_id("codeql_trim_cache_to_overlay_base"),
Some(Command::CodeqlTrimCacheToOverlay)
);
});
}
#[test]
fn a_codeql_databases_source_is_added_to_the_workspace() {
// #578: VS Code's "CodeQL: Add Database Source to Workspace". A `src`
// folder is added as it is; a `src.zip` is extracted once into croft's
// cache and that folder added.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::widgets::command_palette::Command;
use std::io::Write as _;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let folder_db = make_codeql_db(&tmp.path().join("dbs"), "folder", "go");
std::fs::create_dir_all(folder_db.join("src/proj")).unwrap();
std::fs::write(folder_db.join("src/proj/main.go"), "package main\n").unwrap();
let zip_db = make_codeql_db(&tmp.path().join("dbs"), "zipped", "go");
let mut z = zip::ZipWriter::new(std::fs::File::create(zip_db.join("src.zip")).unwrap());
let opts = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Stored);
z.start_file("proj/main.go", opts).unwrap();
z.write_all(b"package main\n").unwrap();
z.finish().unwrap();
let bare_db = make_codeql_db(&tmp.path().join("dbs"), "bare", "go");
let mut store = crate::codeql_db::DatabaseStore::default();
for db in [&folder_db, &zip_db, &bare_db] {
store.add(db).unwrap();
}
store.current = Some(0);
store.save(&App::codeql_db_store_path()).unwrap();
let ws = tmp.path().join("ws");
std::fs::create_dir_all(&ws).unwrap();
let mut app = App::new(ws).unwrap();
app.workspace_folders_path = tmp.path().join("folders.json");
let has_root = |app: &App, p: &std::path::Path| {
app.roots.iter().any(|r| r == p.canonicalize().unwrap())
};
app.run_command(Command::CodeqlAddDatabaseSource);
assert_eq!(
app.status,
"Added the source of CodeQL database folder to the workspace"
);
assert!(has_root(&app, &folder_db.join("src")));
app.run_command(Command::CodeqlAddDatabaseSource);
assert_eq!(
app.status,
"The source of CodeQL database folder is already in the workspace"
);
app.open_codeql_view();
app.focus = Pane::Tree;
app.codeql.select_database(1);
let w = KeyEvent::new(KeyCode::Char('w'), KeyModifiers::NONE);
app.handle_codeql_key(w);
assert_eq!(
app.status,
"Added the source of CodeQL database zipped to the workspace"
);
let extracted = App::codeql_source_cache_dir().join(crate::codeql_db::source_cache_name(
&zip_db,
&zip_db.join("src.zip"),
));
assert_eq!(
std::fs::read_to_string(extracted.join("proj/main.go")).unwrap(),
"package main\n"
);
assert!(has_root(&app, &extracted));
// Extracted once: adding it again reuses the folder as it is.
std::fs::write(extracted.join("mine.txt"), "kept").unwrap();
app.remove_workspace_folder(extracted.canonicalize().unwrap());
assert!(!has_root(&app, &extracted));
app.set_sidebar_view(SidebarView::CodeQL);
app.focus = Pane::Tree;
app.codeql.select_database(1);
app.handle_codeql_key(w);
assert!(has_root(&app, &extracted));
assert!(extracted.join("mine.txt").exists());
// A database replaced at the same path has a new src.zip: it is
// extracted afresh and the out-of-date copy dropped.
app.remove_workspace_folder(extracted.canonicalize().unwrap());
let mut z = zip::ZipWriter::new(std::fs::File::create(zip_db.join("src.zip")).unwrap());
z.start_file("proj/main.go", opts).unwrap();
z.write_all(b"package main // v2\n").unwrap();
z.finish().unwrap();
app.set_sidebar_view(SidebarView::CodeQL);
app.focus = Pane::Tree;
app.codeql.select_database(1);
app.handle_codeql_key(w);
let fresh = App::codeql_source_cache_dir().join(crate::codeql_db::source_cache_name(
&zip_db,
&zip_db.join("src.zip"),
));
assert_ne!(fresh, extracted);
assert_eq!(
std::fs::read_to_string(fresh.join("proj/main.go")).unwrap(),
"package main // v2\n"
);
assert!(has_root(&app, &fresh));
assert!(!extracted.exists(), "the stale extraction is removed");
app.codeql.select_database(2);
app.handle_codeql_key(w);
assert_eq!(
app.status,
"CodeQL database bare has no src folder or src.zip"
);
assert_eq!(
Command::CodeqlAddDatabaseSource.title(),
"CodeQL: Add Database Source to Workspace"
);
});
}
#[test]
fn deleting_unused_codeql_databases_keeps_used_current_and_outside_ones() {
// #578: VS Code's "CodeQL: Delete Unused Databases". Only copies in
// croft's cache that no query history entry ran on go, after a
// confirmation; the current database and ones elsewhere stay.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::widgets::command_palette::Command;
use crate::widgets::input_prompt::InputPurpose;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let cache = App::codeql_db_cache_dir();
// An archive's extraction keeps the database one level down.
let cached = |name: &str| make_codeql_db(&cache.join(name), name, "go");
let used = cached("used");
let legacy = cached("legacy");
let current = cached("current");
let stale_a = cached("stale-a");
let stale_b = cached("stale-b");
let outside = make_codeql_db(tmp.path(), "outside", "go");
let mut store = crate::codeql_db::DatabaseStore::default();
for db in [&used, &legacy, ¤t, &stale_a, &stale_b, &outside] {
store.add(db).unwrap();
}
// Renamed since its run: the history still finds it by path.
store.rename(0, "used, renamed").unwrap();
store.current = Some(2);
store.save(&App::codeql_db_store_path()).unwrap();
let mut history = crate::codeql_query::History::default();
for (db, name, path) in [
(&used, "used", Some(used.clone())),
// Saved before runs recorded a path: matched by name.
(&legacy, "legacy", None),
] {
history.push(crate::codeql_query::HistoryEntry {
query: tmp.path().join("q.ql"),
database: name.to_string(),
database_path: path,
started: 1,
seconds: 1,
status: crate::codeql_query::RunStatus::Succeeded,
output: db.join("unused-output.csv"),
name: None,
results: None,
});
}
history.save(&App::codeql_history_path()).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
// Renaming the database a pre-path run named pins that run to its
// path first, so the rename does not make it look unused.
app.submit_rename_codeql_database(&legacy, "legacy, renamed");
let history = crate::codeql_query::History::load(&App::codeql_history_path());
assert!(history.entries.iter().any(
|e| e.database == "legacy" && e.database_path.as_deref() == Some(legacy.as_path())
));
app.run_command(Command::CodeqlDeleteUnusedDatabases);
let prompt = app.input_prompt.as_ref().expect("asks first");
assert_eq!(prompt.title, "Delete 2 unused CodeQL databases?");
assert_eq!(
prompt.purpose,
InputPurpose::CodeqlDeleteUnusedDatabases {
paths: vec![stale_a.clone(), stale_b.clone()]
}
);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.status, "Deleted 2 unused CodeQL databases");
let store = crate::codeql_db::DatabaseStore::load(&App::codeql_db_store_path());
let names: Vec<&str> = store.databases.iter().map(|d| d.name.as_str()).collect();
assert_eq!(
names,
["used, renamed", "legacy, renamed", "current", "outside"]
);
assert_eq!(store.current, Some(2), "still the current one");
assert!(!cache.join("stale-a").exists() && !cache.join("stale-b").exists());
for kept in [&used, &legacy, ¤t, &outside] {
assert!(kept.exists(), "{}", kept.display());
}
app.run_command(Command::CodeqlDeleteUnusedDatabases);
assert!(app.input_prompt.is_none());
assert_eq!(app.status, "There are no unused CodeQL databases to delete");
assert_eq!(
Command::from_id("codeql_delete_unused_databases"),
Some(Command::CodeqlDeleteUnusedDatabases)
);
});
}
#[test]
fn renaming_one_of_two_same_named_databases_keeps_both_protected() {
// #578: an old run that names "dup" could have been on either of two
// databases called that. After one is renamed, Delete Unused must
// still leave both alone: the renamed one remembers its former name.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let cache = App::codeql_db_cache_dir();
let first = make_codeql_db(&cache.join("one"), "dup", "go");
let second = make_codeql_db(&cache.join("two"), "dup", "go");
let current = make_codeql_db(&cache.join("cur"), "current", "go");
let mut store = crate::codeql_db::DatabaseStore::default();
for db in [&first, &second, ¤t] {
store.add(db).unwrap();
}
store.current = Some(2);
store.save(&App::codeql_db_store_path()).unwrap();
let mut history = crate::codeql_query::History::default();
history.push(crate::codeql_query::HistoryEntry {
query: tmp.path().join("q.ql"),
database: String::from("dup"),
database_path: None,
started: 1,
seconds: 1,
status: crate::codeql_query::RunStatus::Succeeded,
output: tmp.path().join("r.csv"),
name: None,
results: None,
});
history.save(&App::codeql_history_path()).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.submit_rename_codeql_database(&first, "renamed");
let history = crate::codeql_query::History::load(&App::codeql_history_path());
assert_eq!(
history.entries[0].database_path, None,
"ambiguous: not pinned to either"
);
app.run_command(Command::CodeqlDeleteUnusedDatabases);
assert!(app.input_prompt.is_none());
assert_eq!(app.status, "There are no unused CodeQL databases to delete");
assert!(first.exists() && second.exists());
});
}
#[test]
fn creating_a_codeql_query_writes_opens_and_lists_it_in_the_selected_pack() {
// #578: "CodeQL: Create Query" asks for a name and writes a starter
// query into the selected pack, in its language; from the empty
// Queries section it goes to the workspace root, with a pack file in
// the Language section's language.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
use crate::widgets::codeql::{Action, Hit, Section};
use crate::widgets::command_palette::Command;
use crate::widgets::input_prompt::InputPurpose;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let press = |app: &mut App, code: KeyCode| {
app.handle_key(key(code, KeyModifiers::NONE)).unwrap();
};
let type_str = |app: &mut App, text: &str| {
for c in text.chars() {
press(app, KeyCode::Char(c));
}
};
let tmp = tempfile::tempdir().unwrap();
let pack = tmp.path().join("pack");
std::fs::create_dir_all(&pack).unwrap();
std::fs::write(pack.join("qlpack.yml"), "name: acme/go\nextractor: go\n").unwrap();
std::fs::write(pack.join("a.ql"), "select 1").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_codeql_view();
app.focus = Pane::Tree;
let row = app
.codeql
.lines()
.iter()
.position(|l| {
matches!(
l,
crate::widgets::codeql::Line::Action(Action::TogglePack(0), _)
)
})
.expect("the pack is listed");
app.codeql.selected = row;
app.run_command(Command::CodeqlCreateQuery);
let prompt = app.input_prompt.as_ref().expect("a name is asked for");
assert_eq!(
prompt.purpose,
InputPurpose::CodeqlCreateQuery {
dir: pack.clone(),
language: Some(String::from("go")),
}
);
assert!(prompt.title.contains("acme/go"), "{}", prompt.title);
type_str(&mut app, "find-calls");
press(&mut app, KeyCode::Enter);
let created = pack.join("find-calls.ql");
let text = std::fs::read_to_string(&created).expect("written");
assert!(text.contains("\nimport go\n"), "{text}");
assert!(text.contains("@id go/find-calls"), "{text}");
assert_eq!(app.editor.path.as_deref(), Some(created.as_path()));
assert!(app.focus == Pane::Editor);
assert!(app.codeql.queries[0].queries.contains(&created), "listed");
assert!(app.status.contains("pack/find-calls.ql"), "{}", app.status);
assert!(!pack.join("sub").exists());
// The same name again is refused on the status line.
app.set_sidebar_view(SidebarView::CodeQL);
app.focus = Pane::Tree;
press(&mut app, KeyCode::Char('n'));
type_str(&mut app, "find-calls.ql");
press(&mut app, KeyCode::Enter);
assert!(app.status.contains("already exists"), "{}", app.status);
assert_eq!(std::fs::read_to_string(&created).unwrap(), text);
// An empty workspace: the welcome row, in the chosen language.
let empty = tempfile::tempdir().unwrap();
let mut app = App::new(empty.path().to_path_buf()).unwrap();
app.open_codeql_view();
app.focus = Pane::Tree;
app.codeql.language = Some(6);
app.codeql.collapsed.insert(Section::Databases);
let row = app
.codeql
.lines()
.iter()
.position(|l| {
matches!(
l,
crate::widgets::codeql::Line::Action(Action::CreateQuery, _)
)
})
.expect("the welcome offers to create one");
app.codeql.selected = row;
assert_eq!(
app.codeql.selected_hit(),
Some(Hit::Action(Action::CreateQuery))
);
press(&mut app, KeyCode::Enter);
type_str(&mut app, "hello");
press(&mut app, KeyCode::Enter);
let created = empty.path().join("hello.ql");
assert!(
std::fs::read_to_string(&created)
.unwrap()
.contains("import python"),
"{}",
app.status
);
let qlpack = std::fs::read_to_string(empty.path().join("qlpack.yml")).unwrap();
assert!(qlpack.contains("codeql/python-all"), "{qlpack}");
assert_eq!(app.editor.path.as_deref(), Some(created.as_path()));
assert!(
app.codeql
.queries
.iter()
.any(|p| p.queries.contains(&created)),
"{:?}",
app.codeql.queries
);
assert_eq!(
Command::from_id("codeql_create_query"),
Some(Command::CodeqlCreateQuery)
);
assert_eq!(Command::CodeqlCreateQuery.title(), "CodeQL: Create Query");
});
}
/// The phone loop (#359), end to end through the App: a proposal sends one
/// notification whose Approve link carries the proposal's token, and that
/// token, sent back the way `croft decide` sends it, answers the hook and
/// closes the popup without a key pressed.
#[test]
fn an_approval_notifies_once_and_its_approve_token_answers_the_hook() {
use std::io::{BufRead, Write};
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("a.rs");
std::fs::write(&file, "let x = 1;\n").unwrap();
let out = tmp.path().join("notified");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.notifier = crate::notifications::Notifier::new(&[crate::prefs::NotificationSink {
kind: String::from("command"),
argv: vec![
String::from("/bin/sh"),
String::from("-c"),
format!(
"printf '%s %s\\n' \"$CROFT_EVENT\" \"$CROFT_APPROVE_LINK\" >> '{}'",
out.display()
),
],
..Default::default()
}]);
let sock = tmp.path().join("hook.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
listener.set_nonblocking(true).unwrap();
app.hook_listener = Some(listener);
let mut hook = std::os::unix::net::UnixStream::connect(&sock).unwrap();
let req = crate::agent_hook::EditRequest {
agent: "claude-code".into(),
tool: "Edit".into(),
input: serde_json::json!({"file_path": file, "old_string": "1", "new_string": "2"}),
cwd: tmp.path().into(),
};
writeln!(hook, "{}", serde_json::to_string(&req).unwrap()).unwrap();
assert!(app.drain_hook_requests());
// Later passes do not notify it again.
app.drain_hook_requests();
app.drain_hook_requests();
let token = app.approvals[0].token.clone();
// One worker delivers in order, so once this sentinel lands, anything
// the passes above sent has landed too.
app.notifier.emit(
crate::notifications::Event::Osc9 {
pane: String::from("p"),
message: String::from("sentinel"),
},
tmp.path(),
"h",
);
crate::test_budget::await_spawned(
std::time::Duration::from_secs(5),
"the notification",
|| std::fs::read_to_string(&out).is_ok_and(|s| s.contains("osc9")),
);
let sent = std::fs::read_to_string(&out).unwrap();
let approvals: Vec<_> = sent
.lines()
.filter(|l| l.starts_with("approval_pending "))
.collect();
assert_eq!(approvals.len(), 1, "{sent}");
let (event, link) = approvals[0].split_once(' ').unwrap();
assert_eq!(event, "approval_pending");
let link = crate::deep_link::parse(link).unwrap();
assert_eq!(link.decide.as_ref().unwrap().token, token);
assert!(link.decide.as_ref().unwrap().allow);
assert_eq!(
link.path.as_deref(),
Some(tmp.path().to_str().unwrap()),
"the link names the workspace whose croft holds the edit"
);
let mut phone = std::os::unix::net::UnixStream::connect(&sock).unwrap();
writeln!(
phone,
"{}",
serde_json::json!({"decide": {"token": token, "allow": true}})
)
.unwrap();
assert!(app.drain_hook_requests());
assert!(app.approval_ui.is_none() && app.approvals.is_empty());
let mut reply = String::new();
std::io::BufReader::new(phone)
.read_line(&mut reply)
.unwrap();
assert!(reply.contains("\"ok\":true"), "{reply}");
let mut line = String::new();
std::io::BufReader::new(hook).read_line(&mut line).unwrap();
assert_eq!(
serde_json::from_str::<crate::agent_hook::Decision>(line.trim()).unwrap(),
crate::agent_hook::Decision::Allow
);
}
/// A log whose one result carries a two-step code flow, a stack and rule help.
fn sarif_flow_fixture() -> (tempfile::TempDir, std::path::PathBuf) {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
std::fs::write(
tmp.path().join("src/api.rs"),
"fn a() {}\nlet input = read();\n",
)
.unwrap();
std::fs::write(
tmp.path().join("src/db.rs"),
"one\ntwo\nthree\nrun(input);\n",
)
.unwrap();
let log = tmp.path().join("flow.sarif");
std::fs::write(
&log,
r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"lint","rules":[{"id":"R1","name":"Taint",
"help":{"text":"Use parameters instead."},"properties":{"tags":["security"]}}]}},
"results":[{"ruleId":"R1","level":"error",
"message":{"text":"Tainted by [the input](1)."},
"locations":[{"physicalLocation":{"artifactLocation":{"uri":"src/db.rs"},"region":{"startLine":4,"startColumn":1}}}],
"relatedLocations":[{"id":1,"physicalLocation":{"artifactLocation":{"uri":"src/api.rs"},"region":{"startLine":2,"startColumn":5}}}],
"codeFlows":[{"threadFlows":[{"locations":[
{"location":{"message":{"text":"source"},"physicalLocation":{"artifactLocation":{"uri":"src/api.rs"},"region":{"startLine":2,"startColumn":5}}}},
{"location":{"message":{"text":"sink"},"physicalLocation":{"artifactLocation":{"uri":"src/db.rs"},"region":{"startLine":4,"startColumn":5}}}}]}]}],
"stacks":[{"frames":[{"location":{"message":{"text":"frame zero"},"physicalLocation":{"artifactLocation":{"uri":"src/db.rs"},"region":{"startLine":3,"startColumn":2}}}}]}]
}]}]}"#,
)
.unwrap();
(tmp, log)
}
fn draw_screen(app: &mut App) -> String {
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 40)).unwrap();
term.draw(|f| app.render(f)).unwrap();
screen_text(&term)
}
#[test]
fn sarif_info_tab_shows_rule_help_tags_and_related_locations() {
let (tmp, log) = sarif_flow_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
let screen = draw_screen(&mut app);
assert!(
screen.contains("Use parameters instead."),
"rule help:\n{screen}"
);
assert!(screen.contains("security"), "tags:\n{screen}");
assert!(
screen.contains("src/api.rs:2:5"),
"related location:\n{screen}"
);
}
#[test]
fn sarif_steps_tab_walks_the_code_flow_in_the_editor() {
let (tmp, log) = sarif_flow_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_preview(&log).unwrap();
app.handle_sarif_key(key(KeyCode::Char('d'), KeyModifiers::NONE));
let screen = draw_screen(&mut app);
assert!(screen.contains("Steps"), "{screen}");
assert!(
screen.contains("source") && screen.contains("sink"),
"{screen}"
);
app.handle_sarif_key(key(KeyCode::Char('n'), KeyModifiers::NONE));
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("src/api.rs").as_path()),
"step 1 opened: {}",
app.status
);
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 4));
// Back to the viewer tab and on to step 2.
let viewer = (0..app.editor.tab_count())
.find(|&i| app.editor.tab_path(i).as_deref() == Some(log.as_path()))
.expect("the viewer tab stayed open");
app.editor.select(viewer);
app.handle_sarif_key(key(KeyCode::Char('n'), KeyModifiers::NONE));
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("src/db.rs").as_path())
);
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (3, 4));
}
#[test]
fn sarif_stacks_and_raw_tabs() {
let (tmp, log) = sarif_flow_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
app.handle_sarif_key(key(KeyCode::Char('d'), KeyModifiers::NONE));
app.handle_sarif_key(key(KeyCode::Char('d'), KeyModifiers::NONE));
let screen = draw_screen(&mut app);
assert!(screen.contains("frame zero"), "stacks tab:\n{screen}");
assert!(
screen.contains("src/db.rs:3:2"),
"frame location with its column:\n{screen}"
);
app.handle_sarif_key(key(KeyCode::Char('d'), KeyModifiers::NONE));
let screen = draw_screen(&mut app);
assert!(screen.contains("\"ruleId\": \"R1\""), "raw tab:\n{screen}");
app.handle_sarif_key(key(KeyCode::Char('D'), KeyModifiers::NONE));
let screen = draw_screen(&mut app);
assert!(
screen.contains("frame zero"),
"D goes back a tab:\n{screen}"
);
}
#[test]
fn sarif_message_link_opens_its_related_location() {
let (tmp, log) = sarif_flow_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_preview(&log).unwrap();
app.handle_sarif_key(key(KeyCode::Char('L'), KeyModifiers::NONE));
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("src/api.rs").as_path()),
"[the input](1) followed: {}",
app.status
);
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 4));
}
#[test]
fn an_open_sarif_log_publishes_its_results_as_diagnostics() {
// #577: results reach the editor through the ordinary diagnostics store
// under "SARIF: <tool>", so squiggles, hover and Problems all see them.
let (tmp, log) = sarif_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_preview(&log).unwrap();
assert!(app.sync_sarif_diagnostics(), "publishing is a change");
let target = tmp.path().join("src/a.rs");
let by_source = app
.lsp_diagnostics
.get(&target)
.expect("the result's file has diagnostics");
let diags = by_source.get("SARIF: lint").expect("keyed by the tool");
assert_eq!(diags.len(), 1);
let d = &diags[0];
assert_eq!((d.start_line, d.start_char), (1, 8));
assert_eq!(d.end_line, 1);
assert_eq!(
d.end_char as usize,
" let q = format!(\"{}\", id);".encode_utf16().count(),
"no endColumn: the range runs to the end of the start line"
);
assert_eq!(d.severity, crate::lsp::manager::DiagnosticSeverity::Error);
assert_eq!(d.message, "[R1] Query built from user input.");
assert!(
!app.sync_sarif_diagnostics(),
"an unchanged log is not a change"
);
// The file's own tab gets them as squiggles. The viewer is pinned first,
// as opening a result does, so the preview open does not replace it.
app.editor.pin_active();
app.editor.open_preview(&target).unwrap();
app.sync_sarif_diagnostics();
let merged = app.merged_diagnostics(&target);
assert!(merged.iter().any(|d| d.message.contains("[R1]")));
}
#[test]
fn closing_the_sarif_tab_withdraws_its_diagnostics() {
let (tmp, log) = sarif_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
app.sync_sarif_diagnostics();
let target = tmp.path().join("src/a.rs");
assert!(app.lsp_diagnostics.contains_key(&target));
// Replace the log's tab with an ordinary file: no SARIF view is open.
app.editor.open(&target).unwrap();
assert!(app.sync_sarif_diagnostics(), "withdrawing is a change");
assert!(
app.lsp_diagnostics
.get(&target)
.is_none_or(|m| !m.contains_key("SARIF: lint")),
"nothing left behind"
);
}
#[test]
fn sarif_levels_map_to_editor_severities() {
use crate::lsp::manager::DiagnosticSeverity as S;
use crate::sarif::semantics::Level;
assert_eq!(crate::sarif::diagnostics::severity(Level::Error), S::Error);
assert_eq!(
crate::sarif::diagnostics::severity(Level::Warning),
S::Warning
);
assert_eq!(
crate::sarif::diagnostics::severity(Level::Note),
S::Information
);
assert_eq!(
crate::sarif::diagnostics::severity(Level::None),
S::Information
);
}
/// A log whose one result carries a fix for the line it reports.
fn sarif_fix_fixture() -> (tempfile::TempDir, std::path::PathBuf) {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("q.rs"), "let q = format!(\"{}\", id);\n").unwrap();
let log = tmp.path().join("fix.sarif");
std::fs::write(
&log,
r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"lint"}},"columnKind":"unicodeCodePoints",
"results":[{"ruleId":"R9","level":"warning","message":{"text":"Unsanitised id."},
"locations":[{"physicalLocation":{"artifactLocation":{"uri":"q.rs"},"region":{"startLine":1,"startColumn":23}}}],
"fixes":[{"description":{"text":"Sanitise it"},"artifactChanges":[{"artifactLocation":{"uri":"q.rs"},
"replacements":[{"deletedRegion":{"startLine":1,"startColumn":23,"endColumn":25},"insertedContent":{"text":"clean(id)"}}]}]}]}]}]}"#,
)
.unwrap();
(tmp, log)
}
#[test]
fn sarif_fix_tab_previews_and_f_applies_the_fix_as_an_unsaved_edit() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let (tmp, log) = sarif_fix_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_preview(&log).unwrap();
// The Fix tab is the fifth: Info, Steps, Stacks, Raw, Fix.
for _ in 0..4 {
app.handle_sarif_key(key(KeyCode::Char('d'), KeyModifiers::NONE));
}
let screen = draw_screen(&mut app);
assert!(
screen.contains("Sanitise it"),
"the fix's description:\n{screen}"
);
assert!(
screen.contains("+ let q = format!(\"{}\", clean(id));"),
"its preview:\n{screen}"
);
app.handle_sarif_key(key(KeyCode::Char('f'), KeyModifiers::NONE));
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("q.rs").as_path()),
"the fixed file is open: {}",
app.status
);
assert_eq!(app.editor.lines[0], "let q = format!(\"{}\", clean(id));");
assert!(
app.editor.dirty,
"applied to the buffer, not saved behind the user's back"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("q.rs")).unwrap(),
"let q = format!(\"{}\", id);\n",
"the disk is untouched"
);
// The result is marked fixed, and that survives reopening the log.
let viewer = (0..app.editor.tab_count())
.find(|&i| app.editor.tab_path(i).as_deref() == Some(log.as_path()))
.unwrap();
app.editor.select(viewer);
assert!(app.editor.sarif.as_ref().unwrap().entries[0].fixed);
let mut again = App::new(tmp.path().to_path_buf()).unwrap();
again.editor.open(&log).unwrap();
assert!(
again.editor.sarif.as_ref().unwrap().entries[0].fixed,
"persisted"
);
// A fixed result no longer squiggles.
again.sync_sarif_diagnostics();
assert!(
again
.lsp_diagnostics
.get(&tmp.path().join("q.rs"))
.is_none_or(|m| m.values().all(|v| v.is_empty())),
"fixed results are withdrawn from the editor"
);
});
}
/// Two results in one file and one in another, for navigation.
fn sarif_nav_fixture() -> (tempfile::TempDir, std::path::PathBuf) {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.rs"), "l1\nl2\nl3\nl4\nl5\nl6\n").unwrap();
std::fs::write(tmp.path().join("b.rs"), "m1\nm2\n").unwrap();
let log = tmp.path().join("nav.sarif");
let r = |uri: &str, line: u32, msg: &str| {
format!(
r#"{{"message":{{"text":"{msg}"}},"locations":[{{"physicalLocation":{{"artifactLocation":{{"uri":"{uri}"}},"region":{{"startLine":{line},"startColumn":1}}}}}}]}}"#
)
};
std::fs::write(
&log,
format!(
r#"{{"version":"2.1.0","runs":[{{"tool":{{"driver":{{"name":"lint"}}}},"results":[{},{},{}]}}]}}"#,
r("a.rs", 2, "first"),
r("a.rs", 5, "second"),
r("b.rs", 1, "third")
),
)
.unwrap();
(tmp, log)
}
#[test]
fn next_and_previous_sarif_result_walk_locations_across_files() {
let (tmp, log) = sarif_nav_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
app.editor.pin_active();
app.open_at(&tmp.path().join("a.rs"), 0, 0).unwrap();
use crate::widgets::command_palette::Command;
app.run_command(Command::SarifNextResult);
assert_eq!(
(app.editor.cursor_row, app.status.contains("first")),
(1, true),
"{}",
app.status
);
app.run_command(Command::SarifNextResult);
assert_eq!(app.editor.cursor_row, 4);
app.run_command(Command::SarifNextResult);
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("b.rs").as_path()),
"on to the next file"
);
app.run_command(Command::SarifNextResult);
assert_eq!(
(app.editor.path.as_deref(), app.editor.cursor_row),
(Some(tmp.path().join("a.rs").as_path()), 1),
"wraps to the first"
);
app.run_command(Command::SarifPreviousResult);
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("b.rs").as_path())
);
assert_eq!(Command::SarifNextResult.title(), "SARIF: Next Result");
}
#[test]
fn moving_the_cursor_onto_a_result_selects_it_in_the_viewer() {
let (tmp, log) = sarif_nav_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
app.editor.pin_active();
app.open_at(&tmp.path().join("a.rs"), 4, 0).unwrap();
app.sync_sarif_selection_to_cursor();
let viewer = (0..app.editor.tab_count())
.find(|&i| app.editor.tab_path(i).as_deref() == Some(log.as_path()))
.unwrap();
let view = app.editor.editors[viewer].sarif.as_ref().unwrap();
assert_eq!(view.selected_entry().unwrap().message, "second");
}
#[test]
fn a_missing_file_from_a_known_repository_downloads_once_its_host_is_trusted() {
// #577: the run's versionControlProvenance names the repository and
// commit; nothing is fetched until the user trusts the host.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let log = tmp.path().join("remote.sarif");
std::fs::write(
&log,
r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"ci"}},
"versionControlProvenance":[{"repositoryUri":"https://github.com/o/r","revisionId":"c0ffee"}],
"results":[{"message":{"text":"m"},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"src/gone.rs"},"region":{"startLine":2,"startColumn":3}}}]}]}]}"#,
)
.unwrap();
fn fake(url: &str) -> Result<Vec<u8>, String> {
assert_eq!(
url,
"https://raw.githubusercontent.com/o/r/c0ffee/src/gone.rs"
);
Ok(b"one\n two\nthree\n".to_vec())
}
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sarif_fetch = fake;
app.editor.open_preview(&log).unwrap();
app.editor.sarif.as_mut().unwrap().selected = 1;
app.open_selected_sarif_result();
match app.input_prompt.as_ref().map(|p| &p.purpose) {
Some(crate::widgets::input_prompt::InputPurpose::SarifTrustHost { host, .. }) => {
assert_eq!(host, "github.com")
}
other => panic!("a trust prompt, not {other:?}: {}", app.status),
}
assert!(app.sarif_download.is_none(), "nothing fetched before trust");
// Enter on the empty field trusts the host and downloads.
app.submit_input_prompt();
assert!(crate::sarif::resolve::trusted_hosts().contains(&"github.com".to_string()));
let rx_wait = std::time::Instant::now();
while app.sarif_download.is_some() && rx_wait.elapsed().as_secs() < 10 {
app.poll_sarif_download();
std::thread::sleep(std::time::Duration::from_millis(5));
}
let opened = app.editor.path.clone().expect("the download opened");
assert!(opened.starts_with(croft_cache_dir()), "{opened:?}");
assert_eq!(opened.file_name().unwrap(), "gone.rs");
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 2));
// Now trusted: the next open downloads without asking.
let mut again = App::new(tmp.path().to_path_buf()).unwrap();
again.sarif_fetch = fake;
again.editor.open_preview(&log).unwrap();
again.editor.sarif.as_mut().unwrap().selected = 1;
again.open_selected_sarif_result();
assert!(again.input_prompt.is_none(), "{}", again.status);
assert!(again.sarif_download.is_some());
});
}
#[test]
fn a_missing_file_asks_to_locate_it_and_the_mapping_is_learned_and_kept() {
// #577: VS Code's Locate… prompt, with the learned prefix remembered.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
std::fs::create_dir_all(tmp.path().join("lib")).unwrap();
std::fs::write(tmp.path().join("src/a.rs"), "a1\na2\n").unwrap();
std::fs::write(tmp.path().join("lib/b.rs"), "b1\nb2\nb3\n").unwrap();
let log = tmp.path().join("ci.sarif");
std::fs::write(
&log,
r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"ci"}},"results":[
{"message":{"text":"in a"},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"file:///home/runner/work/app/src/a.rs"},"region":{"startLine":2}}}]},
{"message":{"text":"in b"},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"file:///home/runner/work/app/lib/b.rs"},"region":{"startLine":3}}}]}
]}]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_preview(&log).unwrap();
// The first result's file is not here: Enter asks where it is.
app.handle_sarif_key(key(KeyCode::Enter, KeyModifiers::NONE));
assert!(
matches!(
app.input_prompt.as_ref().map(|p| &p.purpose),
Some(crate::widgets::input_prompt::InputPurpose::SarifLocate { .. })
),
"a Locate prompt: {}",
app.status
);
// Groups of equal size sort by path, so `lib/b.rs` is selected first.
assert_eq!(
app.editor
.sarif
.as_ref()
.unwrap()
.selected_entry()
.map(|e| e.message.clone())
.as_deref(),
Some("in b")
);
// A file with another name is refused.
app.submit_sarif_locate(&tmp.path().join("src/a.rs").display().to_string());
assert!(app.status.contains("names must match"), "{}", app.status);
// The right file opens, and the mapping is learned.
app.submit_sarif_locate(&tmp.path().join("lib/b.rs").display().to_string());
assert_eq!(
app.editor.path.as_deref(),
Some(tmp.path().join("lib/b.rs").as_path())
);
assert_eq!(app.editor.cursor_row, 2);
// The other result now resolves on its own, in the next session too.
let mut again = App::new(tmp.path().to_path_buf()).unwrap();
again.editor.open_preview(&log).unwrap();
let rows = again.editor.sarif.as_ref().unwrap().rows();
let a_row = rows
.iter()
.position(|r| match r {
crate::sarif::view::Row::Item { entry } => {
again.editor.sarif.as_ref().unwrap().entries[*entry].message == "in a"
}
_ => false,
})
.unwrap();
again.editor.sarif.as_mut().unwrap().selected = a_row;
again.handle_sarif_key(key(KeyCode::Enter, KeyModifiers::NONE));
assert_eq!(
again.editor.path.as_deref(),
Some(tmp.path().join("src/a.rs").as_path()),
"resolved through the saved prefix: {}",
again.status
);
assert_eq!(again.editor.cursor_row, 1);
});
}
#[test]
fn a_second_log_joins_the_viewer_and_delete_closes_it_from_the_logs_tab() {
// #577: VS Code merges several logs in one panel; its Logs tab closes one.
let (tmp, log) = sarif_fixture();
let second = tmp.path().join("second.sarif");
std::fs::write(
&second,
r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"other"}},"results":[
{"ruleId":"Z1","message":{"text":"From the second log."}}]}]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
app.handle_sarif_key(key(KeyCode::Char('o'), KeyModifiers::NONE));
assert!(
matches!(
app.input_prompt.as_ref().map(|p| &p.purpose),
Some(crate::widgets::input_prompt::InputPurpose::SarifAddLog)
),
"o asks for a log"
);
app.submit_sarif_add_log(&second.display().to_string());
let view = app.editor.sarif.as_ref().unwrap();
assert_eq!(view.logs.len(), 2);
assert_eq!(view.entries.len(), 2);
assert!(
view.entries
.iter()
.any(|e| e.message == "From the second log.")
);
// Adding the same log again does nothing.
app.submit_sarif_add_log(&second.display().to_string());
assert_eq!(app.editor.sarif.as_ref().unwrap().logs.len(), 2);
// Logs tab: select the second log's group and close it.
app.handle_sarif_key(key(KeyCode::Tab, KeyModifiers::NONE));
app.handle_sarif_key(key(KeyCode::Tab, KeyModifiers::NONE));
let view = app.editor.sarif.as_mut().unwrap();
assert_eq!(view.tab, crate::sarif::view::Tab::Logs);
let rows = view.rows();
let second_header = rows
.iter()
.position(|r| matches!(r, crate::sarif::view::Row::Group { label, .. } if label == "second.sarif"))
.unwrap();
view.selected = second_header;
app.handle_sarif_key(key(KeyCode::Delete, KeyModifiers::NONE));
let view = app.editor.sarif.as_ref().unwrap();
assert_eq!(view.logs.len(), 1);
assert!(
view.entries
.iter()
.all(|e| e.message != "From the second log.")
);
// The last log is not closed this way: that is closing the tab.
app.handle_sarif_key(key(KeyCode::Delete, KeyModifiers::NONE));
assert_eq!(
app.editor.sarif.as_ref().unwrap().logs.len(),
1,
"{}",
app.status
);
}
#[test]
fn the_run_tab_shows_the_tool_its_invocation_and_notifications() {
// #577, beyond VS Code: run.tool, invocations and notifications.
let tmp = tempfile::tempdir().unwrap();
let log = tmp.path().join("run.sarif");
std::fs::write(
&log,
r#"{"version":"2.1.0","runs":[{
"tool":{"driver":{"name":"CodeQL","semanticVersion":"2.19.3","informationUri":"https://codeql.github.com"}},
"invocations":[{"commandLine":"codeql database analyze db --format=sarif-latest","executionSuccessful":true,"exitCode":0,
"startTimeUtc":"2026-09-24T10:00:00Z","endTimeUtc":"2026-09-24T10:03:12Z",
"toolExecutionNotifications":[{"level":"warning","message":{"text":"Skipped vendor/huge.js: too large"}}]}],
"results":[]}]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
for _ in 0..3 {
app.handle_sarif_key(key(KeyCode::Tab, KeyModifiers::NONE));
}
assert_eq!(
app.editor.sarif.as_ref().unwrap().tab,
crate::sarif::view::Tab::Run
);
let screen = draw_screen(&mut app);
for want in [
"CodeQL 2.19.3",
"https://codeql.github.com",
"codeql database analyze db --format=sarif-latest",
"exit 0",
"Skipped vendor/huge.js: too large",
] {
assert!(screen.contains(want), "{want:?} on the Run tab:\n{screen}");
}
// Back round to Locations.
app.handle_sarif_key(key(KeyCode::Tab, KeyModifiers::NONE));
assert_eq!(
app.editor.sarif.as_ref().unwrap().tab,
crate::sarif::view::Tab::Locations
);
}
#[test]
fn a_baseline_log_marks_results_new_or_unchanged_and_lists_what_disappeared() {
// #577: logs without baselineState are compared against a chosen baseline.
let tmp = tempfile::tempdir().unwrap();
let result = |rule: &str, file: &str, line: i64| {
format!(
r#"{{"ruleId":"{rule}","message":{{"text":"{rule} here"}},"locations":[{{"physicalLocation":{{"artifactLocation":{{"uri":"{file}"}},"region":{{"startLine":{line}}}}}}}]}}"#
)
};
let write_log = |name: &str, results: Vec<String>| {
let p = tmp.path().join(name);
std::fs::write(
&p,
format!(
r#"{{"version":"2.1.0","runs":[{{"tool":{{"driver":{{"name":"T"}}}},"results":[{}]}}]}}"#,
results.join(",")
),
)
.unwrap();
p
};
for f in ["a.js", "c.js", "d.js"] {
std::fs::write(tmp.path().join(f), "one\ntwo\nthree\n").unwrap();
}
let now = write_log(
"now.sarif",
vec![result("kept", "a.js", 3), result("fresh", "d.js", 2)],
);
let before = write_log(
"before.sarif",
vec![result("kept", "a.js", 3), result("gone", "c.js", 1)],
);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&now).unwrap();
app.handle_sarif_key(key(KeyCode::Char('b'), KeyModifiers::NONE));
assert!(
matches!(
app.input_prompt.as_ref().map(|p| &p.purpose),
Some(crate::widgets::input_prompt::InputPurpose::SarifBaseline)
),
"b asks for a baseline"
);
app.submit_sarif_baseline(&before.display().to_string());
let view = app.editor.sarif.as_ref().unwrap();
assert_eq!(view.baseline, Some(1));
let state = |rule: &str| {
view.entries
.iter()
.find(|e| e.rule_id == rule)
.map(|e| e.baseline)
};
use crate::sarif::semantics::BaselineState;
assert_eq!(state("kept"), Some(BaselineState::Unchanged));
assert_eq!(state("fresh"), Some(BaselineState::New));
assert_eq!(state("gone"), Some(BaselineState::Absent));
// The baseline contributes only what disappeared, never a second "kept".
assert_eq!(view.entries.len(), 3);
// What disappeared is not a problem in today's code.
app.sync_sarif_diagnostics();
let c = tmp.path().join("c.js");
assert!(
app.lsp_diagnostics
.get(&c)
.is_none_or(|m| m.values().all(Vec::is_empty)),
"absent results publish no diagnostics"
);
assert!(
app.lsp_diagnostics
.get(&tmp.path().join("d.js"))
.is_some_and(|m| m.values().any(|v| !v.is_empty()))
);
}
#[test]
fn e_exports_the_visible_sarif_results_to_a_csv_file() {
// #577: the filtered list leaves the editor as a spreadsheet.
let (tmp, log) = sarif_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
app.handle_sarif_key(key(KeyCode::Char('E'), KeyModifiers::SHIFT));
let prompt = app.input_prompt.as_ref().expect("E asks where to write");
assert!(matches!(
prompt.purpose,
crate::widgets::input_prompt::InputPurpose::SarifExport
));
assert_eq!(
prompt.value, "sarif-results.csv",
"a default name is offered"
);
app.submit_sarif_export("out/results.csv");
let written = std::fs::read_to_string(tmp.path().join("out/results.csv"))
.expect("written relative to the workspace, creating the folder");
assert!(
written.starts_with("rule,level,file,line,column,message"),
"{written}"
);
assert_eq!(
written.lines().count(),
2,
"one result plus the header: {written}"
);
assert!(app.status.contains("1 result"), "{}", app.status);
}
#[test]
fn the_sarif_key_legend_names_the_fix_log_baseline_and_export_keys() {
// #577: every viewer key is discoverable from its footer at a common width.
let (tmp, log) = sarif_fixture();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
let screen = draw_screen(&mut app);
for want in ["f fix", "o add log", "b baseline", "E export"] {
assert!(screen.contains(want), "{want} missing:\n{screen}");
}
}
/// A stand-in `gh` answering from canned files: each rule maps a substring
/// of the arguments to the file whose contents it prints.
#[cfg(unix)]
fn fake_gh(dir: &std::path::Path, rules: &[(&str, &str)]) -> std::path::PathBuf {
use std::os::unix::fs::PermissionsExt;
let mut script = String::from(
"#!/bin/sh\necho \"$*\" >> \"$(dirname \"$0\")/gh-calls.log\"\ncase \"$*\" in\n",
);
for (i, (pattern, body)) in rules.iter().enumerate() {
let file = dir.join(format!("gh-reply-{i}"));
std::fs::write(&file, body).unwrap();
script.push_str(&format!(" *'{pattern}'*) cat '{}' ;;\n", file.display()));
}
script.push_str(" *) echo '{\"message\":\"unexpected call\"}' >&2; exit 1 ;;\nesac\n");
let gh = dir.join("gh");
std::fs::write(&gh, script).unwrap();
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
gh
}
#[cfg(unix)]
#[test]
fn a_code_scanning_analysis_opens_from_github_in_the_sarif_viewer() {
// #577: VS Code's SARIF viewer pulls a repository's code scanning
// analyses; croft lists them and opens the chosen one as a log.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let gh = fake_gh(
bin.path(),
&[
(
"analyses?per_page=30",
r#"[{"id":201,"ref":"refs/heads/main","commit_sha":"abc","error":"","category":"",
"created_at":"2026-09-20T10:00:00Z","results_count":1,"tool":{"name":"CodeQL","version":"2.19.3"}}]"#,
),
(
"analyses/201",
r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"CodeQL"}},
"results":[{"ruleId":"rust/sql-injection","message":{"text":"From GitHub."}}]}]}"#,
),
],
);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.gh_program = gh;
app.run_command(crate::widgets::command_palette::Command::SarifOpenCodeScanning);
let picker = app.list_picker.as_ref().expect("the analyses are offered");
assert_eq!(
picker.purpose,
crate::widgets::list_picker::ListPurpose::CodeScanningAnalysis
);
assert_eq!(picker.rows.len(), 1);
assert_eq!(picker.rows[0].id, "201");
assert!(
picker.rows[0].label.contains("CodeQL 2.19.3"),
"{}",
picker.rows[0].label
);
app.confirm_list_picker();
let view = app
.editor
.sarif
.as_ref()
.expect("the analysis opens in the viewer");
assert!(view.entries.iter().any(|e| e.message == "From GitHub."));
let calls = std::fs::read_to_string(bin.path().join("gh-calls.log")).unwrap();
assert!(calls.contains("Accept: application/sarif+json"), "{calls}");
});
}
#[cfg(unix)]
#[test]
fn code_scanning_reports_githubs_own_error() {
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let gh = fake_gh(bin.path(), &[]);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.gh_program = gh;
app.run_command(crate::widgets::command_palette::Command::SarifOpenCodeScanning);
assert!(app.list_picker.is_none());
assert!(app.status.contains("unexpected call"), "{}", app.status);
}
#[cfg(unix)]
#[test]
fn x_dismisses_the_selected_results_code_scanning_alert_with_a_reason() {
// #577: VS Code's SARIF viewer dismisses GitHub alerts from the list.
// This result carries no alert number, so it is matched to the alerts
// list by rule, path and line.
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
std::fs::write(tmp.path().join("src/db.rs"), "a\nb\nc\n").unwrap();
let log = tmp.path().join("scan.sarif");
std::fs::write(
&log,
r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"CodeQL"}},"results":[
{"ruleId":"rust/sql-injection","message":{"text":"Tainted."},
"locations":[{"physicalLocation":{"artifactLocation":{"uri":"src/db.rs"},"region":{"startLine":2}}}]}]}]}"#,
)
.unwrap();
let bin = tempfile::tempdir().unwrap();
let gh = fake_gh(
bin.path(),
&[
(
"code-scanning/alerts?per_page=100",
r#"[{"number":8,"state":"open","rule":{"id":"rust/sql-injection"},
"most_recent_instance":{"location":{"path":"src/db.rs","start_line":2}}}]"#,
),
("PATCH", r#"{"number":8,"state":"dismissed"}"#),
],
);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.gh_program = gh;
app.editor.open(&log).unwrap();
app.editor.sarif.as_mut().unwrap().selected = 1;
app.handle_sarif_key(key(KeyCode::Char('X'), KeyModifiers::SHIFT));
let picker = app.list_picker.as_ref().expect("X asks why");
assert_eq!(
picker.purpose,
crate::widgets::list_picker::ListPurpose::DismissAlert
);
let labels: Vec<&str> = picker.rows.iter().map(|r| r.label.as_str()).collect();
assert_eq!(labels, ["False positive", "Won't fix", "Used in tests"]);
// Pick "Won't fix", then give a comment.
app.list_picker.as_mut().unwrap().selected = 1;
app.confirm_list_picker();
assert!(matches!(
app.input_prompt.as_ref().map(|p| &p.purpose),
Some(
crate::widgets::input_prompt::InputPurpose::DismissAlertComment {
number: 8,
reason: 1
}
)
));
app.dismiss_code_scanning_alert(8, 1, "tracked elsewhere");
let calls = std::fs::read_to_string(bin.path().join("gh-calls.log")).unwrap();
assert!(
calls.contains("PATCH repos/{owner}/{repo}/code-scanning/alerts/8 -f state=dismissed -f dismissed_reason=won't fix -f dismissed_comment=tracked elsewhere"),
"{calls}"
);
assert!(app.status.contains("#8"), "{}", app.status);
let view = app.editor.sarif.as_ref().unwrap();
assert_eq!(
view.entries[0].suppression,
crate::sarif::semantics::SuppressionState::Suppressed,
"the dismissed result leaves the default list"
);
}
#[test]
fn the_info_tab_lists_the_results_taxa() {
// #577: CWE / OWASP entries a result names, resolved through taxonomies.
let tmp = tempfile::tempdir().unwrap();
let log = tmp.path().join("t.sarif");
std::fs::write(
&log,
r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"T"}},
"taxonomies":[{"name":"CWE","taxa":[{"id":"CWE-89","name":"SqlInjection"}]}],
"results":[{"ruleId":"R1","message":{"text":"m"},
"taxa":[{"id":"CWE-89","toolComponent":{"name":"CWE"}}]}]}]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
app.editor.sarif.as_mut().unwrap().selected = 1;
let screen = draw_screen(&mut app);
assert!(screen.contains("CWE CWE-89: SqlInjection"), "{screen}");
}
#[cfg(unix)]
#[test]
fn code_scanning_offers_the_current_branchs_analyses_and_falls_back_to_all() {
// #577: like VS Code's viewer, the analyses of the branch being worked
// on come first; a branch with none shows the repository's.
let tmp = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let one = |id: u64, git_ref: &str| {
format!(
r#"[{{"id":{id},"ref":"{git_ref}","commit_sha":"c","error":"","category":"","created_at":"2026-09-20T10:00:00Z","results_count":0,"tool":{{"name":"CodeQL"}}}}]"#
)
};
let on_branch = one(301, "refs/heads/feat/x");
let everything = one(300, "refs/heads/main");
let gh = fake_gh(
bin.path(),
&[
("ref=refs%2Fheads%2Ffeat%2Fx", &on_branch),
("ref=refs%2Fheads%2Fempty", "[]"),
("analyses?per_page=30", &everything),
],
);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.gh_program = gh;
app.source_control.status.branch = Some(String::from("feat/x"));
app.run_command(crate::widgets::command_palette::Command::SarifOpenCodeScanning);
let picker = app.list_picker.take().expect("offered");
assert_eq!(
picker
.rows
.iter()
.map(|r| r.id.as_str())
.collect::<Vec<_>>(),
["301"]
);
assert!(picker.title.contains("feat/x"), "{}", picker.title);
app.source_control.status.branch = Some(String::from("empty"));
app.run_command(crate::widgets::command_palette::Command::SarifOpenCodeScanning);
let picker = app.list_picker.take().expect("offered");
assert_eq!(
picker
.rows
.iter()
.map(|r| r.id.as_str())
.collect::<Vec<_>>(),
["300"]
);
}
fn status_row(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> String {
let buf = term.backend().buffer();
let y = buf.area.height - 1;
(0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect()
}
/// #355: the notebook in the editor names its kernel in the status bar
/// once the kernel is up, and says when a cell is running.
#[test]
fn the_status_bar_names_the_notebooks_kernel_and_when_it_is_busy() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("t.ipynb");
std::fs::write(&path, NOTEBOOK_355).unwrap();
std::fs::write(tmp.path().join("other.py"), "x = 1\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&path).unwrap();
let (run, kernel, _requests) = crate::notebook_kernel::NotebookRun::for_test();
app.notebook_kernels.insert(path.clone(), run);
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("kernel:"),
"no name before the kernel says it is up"
);
kernel
.send(crate::notebook_kernel::Event::Ready {
kernel: "python3".into(),
display: "Python 3 (ipykernel)".into(),
})
.unwrap();
app.poll_notebook_kernels();
term.draw(|f| app.render(f)).unwrap();
let row = status_row(&term);
assert!(row.contains("kernel: Python 3 (ipykernel)"), "{row}");
assert!(!row.contains("busy"), "{row}");
click_first_cell_glyph(&mut app, &mut term);
term.draw(|f| app.render(f)).unwrap();
assert!(status_row(&term).contains("kernel: Python 3 (ipykernel) · busy"));
// Another file in the editor has no kernel to name.
app.editor.open(&tmp.path().join("other.py")).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert!(!status_row(&term).contains("kernel:"));
}
/// #356: a terminal recording has its own status-bar badge with the time
/// it has run, apart from the macro recorder's REC.
#[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);
// The start message names the file; the badge must stand on its own.
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"));
}
/// #371: at a scrubbed commit, Enter opens that version of the file as a
/// tab of its own, and "Diff Scrubbed File to Working Tree" diffs it
/// against the file on disk. Both leave the scrubber and the live buffer
/// (dirty or not) untouched. At the working tree, Enter is ordinary typing.
#[test]
fn the_scrubber_opens_a_commits_version_here_or_diffs_it_to_the_working_tree() {
let repo = scrub_repo();
let file = repo.path().join("a.txt");
// Uncommitted work on disk, and more unsaved in the buffer.
std::fs::write(&file, "v1\nv2\nv3\nv4\n").unwrap();
let mut app = App::new(repo.path().to_path_buf()).unwrap();
app.editor.open(&file).unwrap();
app.editor.lines.push(String::from("unsaved"));
app.editor.dirty = true;
app.scrub_history();
assert!(
!app.handle_scrubber_key(KeyCode::Enter),
"at the working tree there is nothing to open"
);
assert!(app.handle_scrubber_key(KeyCode::Left), "to HEAD");
assert!(app.handle_scrubber_key(KeyCode::Left), "to v2");
let short = app
.scrubber
.as_ref()
.unwrap()
.commit()
.unwrap()
.short_hash
.clone();
assert!(app.handle_scrubber_key(KeyCode::Enter));
assert!(app.scrubber.is_none() && app.scrub_view.is_none());
assert_eq!(
app.editor.path.as_deref(),
Some(Path::new(&format!("a.txt @ {short}")))
);
assert_eq!(app.editor.lines, vec!["v1", "v2"]);
let live = app.editor.find_tab_with_path(&file).expect("the live tab");
app.editor.select(live);
assert!(app.editor.dirty, "the live buffer keeps its unsaved edit");
assert_eq!(app.editor.lines.last().map(String::as_str), Some("unsaved"));
app.scrub_history();
assert!(app.handle_scrubber_key(KeyCode::Left));
assert!(app.handle_scrubber_key(KeyCode::Left));
app.run_command(crate::widgets::command_palette::Command::ScrubDiffToWorkingTree);
assert!(app.scrubber.is_none());
let diff = app.editor.diff.as_ref().expect("a diff tab");
assert_eq!(diff.left_lines, vec!["v1", "v2"]);
assert_eq!(
diff.right_lines,
vec!["v1", "v2", "v3", "v4"],
"the file on disk"
);
// With no scrubbed commit, the commands say so rather than guess.
app.run_command(crate::widgets::command_palette::Command::ScrubOpenHere);
assert!(app.status.contains("Step the scrubber"), "{}", app.status);
}
/// #345: a lane row counts the lines added and removed since the content
/// the user reviewed, follows later writes, and shows nothing for a row
/// with no review to count against.
#[test]
fn a_lane_row_counts_lines_added_and_removed_since_the_review() {
use crate::widgets::agent_lane::LaneRow;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("f.rs");
let g = tmp.path().join("g.rs");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
let working = vec![String::from("claude")];
let write = |app: &mut App, path: &Path, text: &str| {
std::fs::write(path, text).unwrap();
app.agent_ledger.record_write(
path,
crate::agent_lane::content_hash(text.as_bytes()),
&working,
);
};
let changes_of = |app: &mut App, path: &Path| {
app.agent_lane_panel_rows()
.into_iter()
.find_map(|r| match r {
LaneRow::File {
path: p, changes, ..
} if p == path => Some(changes),
_ => None,
})
.expect("the file has a row")
};
write(&mut app, &f, "a\nb\nc\n");
write(&mut app, &g, "new\n");
assert_eq!(
changes_of(&mut app, &g),
None,
"never reviewed: no baseline"
);
assert!(app.mark_agent_file_reviewed("claude", &f));
assert_eq!(changes_of(&mut app, &f), Some((0, 0)));
// Replace one line and add two.
write(&mut app, &f, "a\nB\nc\nd\ne\n");
assert_eq!(changes_of(&mut app, &f), Some((3, 1)));
// A later write is counted afresh, not served from the cache.
write(&mut app, &f, "a\n");
assert_eq!(changes_of(&mut app, &f), Some((0, 2)));
// Painted beside the label.
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 40)).unwrap();
app.show_agent_lane_section();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let screen: String = (0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol())
.collect::<String>()
+ "\n"
})
.collect();
assert!(screen.contains("f.rs +0 −2"), "{screen}");
}
/// Starting the tour while it runs keeps the first one: a second start
/// would record the first tour's scratch project as the way home, and the
/// user's own workspace would be lost when it ended.
#[test]
fn starting_the_tour_again_while_it_runs_keeps_the_way_home() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.start_demo();
let scratch = app.workspace_root().to_path_buf();
app.run_command(crate::widgets::command_palette::Command::TakeTheTour);
assert!(app.status.contains("already running"), "{}", app.status);
assert_eq!(app.workspace_root(), scratch);
app.finish_tour();
assert_eq!(
app.workspace_root(),
tmp.path(),
"back in the user's workspace"
);
assert!(!scratch.exists());
});
}
/// #371: switching to another file while scrubbing shows that file at the
/// scrubbed commit, not the previous file's history over it.
#[test]
fn switching_files_while_scrubbing_shows_the_new_files_history() {
let repo = scrub_repo();
std::fs::write(repo.path().join("new.txt"), "fresh\n").unwrap();
let mut app = App::new(repo.path().to_path_buf()).unwrap();
app.editor.open(&repo.path().join("a.txt")).unwrap();
app.scrub_history();
assert!(app.handle_scrubber_key(KeyCode::Left), "to HEAD");
assert_eq!(
app.scrub_view.as_ref().unwrap().lines,
vec!["v1", "v2", "v3"]
);
app.editor.open(&repo.path().join("new.txt")).unwrap();
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let view = app.scrub_view.as_ref().expect("still scrubbing");
assert!(
view.lines[0].contains("new.txt did not exist"),
"{:?}",
view.lines
);
}
/// #365: the review tab's `gh` calls run off the UI thread, and a pasted
/// URL from another repository opens that repository's pull request.
#[test]
fn a_pr_review_loads_off_the_ui_thread_and_a_url_keeps_its_repository() {
use std::os::unix::fs::PermissionsExt;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let log = tmp.path().join("gh-args");
let gh = tmp.path().join("gh");
std::fs::write(
&gh,
format!(
r#"#!/bin/sh
echo "$@" >> '{}'
sleep 0.3
case "$2" in
view) echo '{{"number": 42, "title": "t", "url": "https://github.com/x/y/pull/42", "author": {{"login": "a"}}, "files": [{{"path": "a.rs", "additions": 1, "deletions": 0, "changeType": "ADDED"}}], "statusCheckRollup": []}}' ;;
diff) printf 'diff --git a/a.rs b/a.rs\nnew file mode 100644\n--- /dev/null\n+++ b/a.rs\n@@ -0,0 +1 @@\n+fn a() {{}}\n' ;;
esac
"#,
log.display()
),
)
.unwrap();
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.review_gh = gh.display().to_string();
let started = std::time::Instant::now();
app.submit_pr_number("https://github.com/x/y/pull/42/files");
assert!(
started.elapsed() < std::time::Duration::from_millis(250),
"the prompt returns before gh does"
);
assert!(app.status.contains("Loading PR"), "{}", app.status);
crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "gh pr view", || {
app.poll_pr_gh();
app.editor.pr_review.is_some()
});
assert_eq!(app.editor.pr_review.as_ref().unwrap().pr.number, 42);
app.handle_pr_review_key(key(KeyCode::Enter, KeyModifiers::NONE));
assert!(app.status.contains("Fetching the diff"), "{}", app.status);
crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "gh pr diff", || {
app.poll_pr_gh();
app.editor.diff.is_some()
});
let args = std::fs::read_to_string(&log).unwrap();
// The viewed-state read (`gh api graphql`) runs beside these.
let lines: Vec<&str> = args.lines().filter(|l| l.starts_with("pr ")).collect();
assert!(
lines[0].starts_with("pr view https://github.com/x/y/pull/42 --json"),
"the URL, not a bare 42 this repository would resolve: {args}"
);
assert_eq!(lines[1], "pr diff https://github.com/x/y/pull/42");
});
}
/// A stub `gh` for the viewed-sync tests (#365): it logs its argv to
/// `gh-args`, answers `pr view` with PR x/y#42 (a.rs, b.rs, c.rs), and
/// runs `graphql` for everything else.
fn viewed_sync_gh(
dir: &std::path::Path,
graphql: &str,
) -> (std::path::PathBuf, std::path::PathBuf) {
use std::os::unix::fs::PermissionsExt;
let log = dir.join("gh-args");
let gh = dir.join("gh");
std::fs::write(
&gh,
format!(
r#"#!/bin/sh
echo "$@" >> '{}'
case "$*" in
"pr view"*) echo '{{"number": 42, "title": "t", "url": "https://github.com/x/y/pull/42", "author": {{"login": "a"}}, "files": [{{"path": "a.rs", "additions": 1, "deletions": 0, "changeType": "ADDED"}}, {{"path": "b.rs", "additions": 1, "deletions": 0, "changeType": "ADDED"}}, {{"path": "c.rs", "additions": 1, "deletions": 0, "changeType": "ADDED"}}], "statusCheckRollup": []}}' ;;
{graphql}
esac
"#,
log.display()
),
)
.unwrap();
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
(gh, log)
}
/// Load x/y#42 through `gh` and wait for its viewed-state read to settle.
fn open_synced_pr(app: &mut App) {
app.submit_pr_number("42");
crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "gh pr view", || {
app.poll_pr_gh();
app.editor.pr_review.is_some() && app.pr_viewed_fetch.is_none()
});
}
/// Wait until every queued viewed mutation has run.
fn settle_viewed_writes(app: &mut App) {
crate::test_budget::await_spawned(
std::time::Duration::from_secs(5),
"the viewed mutations",
|| {
app.poll_pr_gh();
app.pr_viewed_queue.is_empty() && app.pr_viewed_write.is_none()
},
);
}
/// #365: GitHub's viewed state (paged) is the truth when it loads: VIEWED
/// ticks, DISMISSED (changed since viewed) and UNVIEWED untick even a
/// local mark, and the local store follows. Toggling sends the matching
/// mutation; a failed one keeps the local mark and says so once.
#[test]
fn pr_viewed_state_syncs_with_github() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let page = |nodes: &str, next: &str| {
format!(
r#"echo '{{"data":{{"repository":{{"pullRequest":{{"id":"PR_kw42","files":{{"nodes":[{nodes}],"pageInfo":{next}}}}}}}}}}}'"#
)
};
let graphql = format!(
" *unmarkFileAsViewed*) echo '{{}}' ;;\n *markFileAsViewed*) echo 'Resource not accessible' >&2; exit 1 ;;\n *after=CUR1*) {} ;;\n *graphql*) {} ;;",
page(
r#"{"path":"c.rs","viewerViewedState":"UNVIEWED"}"#,
r#"{"hasNextPage":false,"endCursor":"CUR2"}"#
),
page(
r#"{"path":"a.rs","viewerViewedState":"VIEWED"},{"path":"b.rs","viewerViewedState":"DISMISSED"}"#,
r#"{"hasNextPage":true,"endCursor":"CUR1"}"#
),
);
let (gh, log) = viewed_sync_gh(tmp.path(), &graphql);
// Marked locally before; GitHub says otherwise for both.
let store_path = App::pr_viewed_path();
let mut store = crate::pr_review::ViewedStore::default();
store.set("x/y#42", "b.rs", true);
store.set("x/y#42", "c.rs", true);
store.save(&store_path).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.review_gh = gh.display().to_string();
open_synced_pr(&mut app);
let view = app.editor.pr_review.as_ref().unwrap();
assert_eq!(view.github_id.as_deref(), Some("PR_kw42"));
assert_eq!(
view.viewed.iter().map(String::as_str).collect::<Vec<_>>(),
vec!["a.rs"],
"both pages applied, GitHub wins"
);
assert!(pr_screen(&mut app).contains("1 of 3 viewed"));
let stored = crate::pr_review::ViewedStore::load(&store_path).viewed("x/y#42");
assert_eq!(
stored.iter().map(String::as_str).collect::<Vec<_>>(),
vec!["a.rs"],
"the local store follows GitHub"
);
// a.rs is selected and viewed: Space unticks it at once and sends
// unmarkFileAsViewed, which succeeds.
app.status.clear();
app.handle_pr_review_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
assert!(
!app.editor
.pr_review
.as_ref()
.unwrap()
.viewed
.contains("a.rs")
);
settle_viewed_writes(&mut app);
assert!(app.status.is_empty(), "{}", app.status);
let args = std::fs::read_to_string(&log).unwrap();
let unmark = args.lines().last().unwrap();
assert!(
unmark.starts_with("api graphql -f query=mutation(")
&& unmark.contains("unmarkFileAsViewed(input: {pullRequestId: $id, path: $path})")
&& unmark.ends_with("-f id=PR_kw42 -f path=a.rs"),
"{unmark}"
);
// b.rs: marking fails on GitHub; the mark stays, locally too, and
// the reason shows once.
app.handle_pr_review_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
assert!(
app.editor
.pr_review
.as_ref()
.unwrap()
.viewed
.contains("b.rs")
);
settle_viewed_writes(&mut app);
assert_eq!(
app.status,
"Viewed state saved locally; GitHub could not be updated: Resource not accessible"
);
assert!(
crate::pr_review::ViewedStore::load(&store_path)
.viewed("x/y#42")
.contains("b.rs")
);
// c.rs fails too, quietly this time.
app.status.clear();
app.handle_pr_review_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
settle_viewed_writes(&mut app);
assert!(app.status.is_empty(), "said once: {}", app.status);
assert!(
app.editor
.pr_review
.as_ref()
.unwrap()
.viewed
.contains("c.rs")
);
let args = std::fs::read_to_string(&log).unwrap();
assert!(
args.lines()
.last()
.unwrap()
.ends_with("-f id=PR_kw42 -f path=c.rs"),
"{args}"
);
});
}
/// #365: when gh cannot read the viewed state (signed out, not GitHub),
/// review behaves as before: local marks, no error, no mutations.
#[test]
fn pr_viewed_state_stays_local_without_github() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let (gh, log) = viewed_sync_gh(
tmp.path(),
" *graphql*) echo 'gh auth login required' >&2; exit 4 ;;",
);
let store_path = App::pr_viewed_path();
let mut store = crate::pr_review::ViewedStore::default();
store.set("x/y#42", "b.rs", true);
store.save(&store_path).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.review_gh = gh.display().to_string();
open_synced_pr(&mut app);
assert_eq!(app.status, "Reviewing PR #42", "no error spam");
let view = app.editor.pr_review.as_ref().unwrap();
assert_eq!(view.github_id, None);
assert!(view.viewed.contains("b.rs"), "local marks as before");
app.handle_pr_review_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
settle_viewed_writes(&mut app);
assert!(
app.editor
.pr_review
.as_ref()
.unwrap()
.viewed
.contains("a.rs")
);
assert!(
crate::pr_review::ViewedStore::load(&store_path)
.viewed("x/y#42")
.contains("a.rs")
);
assert_eq!(app.status, "Reviewing PR #42");
let args = std::fs::read_to_string(&log).unwrap();
assert!(!args.contains("FileAsViewed"), "no mutation: {args}");
});
}
/// #365: a file toggled while GitHub's viewed state is still loading keeps
/// the person's mark, and it is sent once the PR's id is known.
#[test]
fn a_toggle_before_github_answers_wins_and_is_sent() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let (gh, log) = viewed_sync_gh(tmp.path(), " *FileAsViewed*) echo '{}' ;;");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.review_gh = gh.display().to_string();
app.open_pr_review(
crate::pr_review::parse_pr(
r#"{"number": 42, "url": "https://github.com/x/y/pull/42", "files": [{"path": "a.rs"}]}"#,
)
.unwrap(),
String::from("x/y#42"),
);
// A read in flight that has not answered yet.
let (tx, rx) = std::sync::mpsc::channel();
app.pr_viewed_fetch = Some((String::from("x/y#42"), app.pr_viewed_seq, rx));
app.handle_pr_review_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
let mut states = std::collections::BTreeMap::new();
states.insert(
String::from("a.rs"),
crate::pr_review::ViewedState::Unviewed,
);
tx.send(Ok((String::from("PR_kw42"), states))).unwrap();
settle_viewed_writes(&mut app);
let view = app.editor.pr_review.as_ref().unwrap();
assert!(view.viewed.contains("a.rs"), "the click is newer");
assert!(view.unsynced.is_empty());
let args = std::fs::read_to_string(&log).unwrap();
assert!(
args.contains(" markFileAsViewed(") && args.ends_with("-f id=PR_kw42 -f path=a.rs\n"),
"{args}"
);
});
}
/// #365: a viewed-state read that began while a write was in flight may
/// have seen GitHub before the write landed. Its answer must not undo the
/// mark, even after the write finished and a refresh replaced the view.
#[test]
fn a_read_that_began_before_a_write_settled_does_not_undo_it() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let (gh, _log) = viewed_sync_gh(tmp.path(), " *FileAsViewed*) echo '{}' ;;");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.review_gh = gh.display().to_string();
let pr = || {
crate::pr_review::parse_pr(
r#"{"number": 42, "url": "https://github.com/x/y/pull/42", "files": [{"path": "a.rs"}]}"#,
)
.unwrap()
};
app.open_pr_review(pr(), String::from("x/y#42"));
app.editor.pr_review.as_mut().unwrap().github_id = Some(String::from("PR_kw42"));
// Tick a.rs: its mutation is queued, then sent.
app.handle_pr_review_key(key(KeyCode::Char(' '), KeyModifiers::NONE));
app.poll_pr_viewed();
assert!(app.pr_viewed_write.is_some(), "in flight");
// A refresh replaces the view and starts a read while it is.
app.open_pr_review(pr(), String::from("x/y#42"));
let (tx, rx) = std::sync::mpsc::channel();
app.pr_viewed_fetch = Some((String::from("x/y#42"), app.pr_viewed_seq, rx));
// The write lands and settles before the read answers ...
settle_viewed_writes(&mut app);
assert!(app.pr_viewed_queue.is_empty() && app.pr_viewed_write.is_none());
// ... with what GitHub said before it: unviewed.
let mut states = std::collections::BTreeMap::new();
states.insert(
String::from("a.rs"),
crate::pr_review::ViewedState::Unviewed,
);
tx.send(Ok((String::from("PR_kw42"), states))).unwrap();
app.poll_pr_viewed();
let view = app.editor.pr_review.as_ref().unwrap();
assert!(view.viewed.contains("a.rs"), "the stale answer is ignored");
assert!(
crate::pr_review::ViewedStore::load(&App::pr_viewed_path())
.viewed("x/y#42")
.contains("a.rs"),
"and does not reach the local store"
);
// A read that begins after the write settled is trusted again.
let (tx, rx) = std::sync::mpsc::channel();
app.pr_viewed_fetch = Some((String::from("x/y#42"), app.pr_viewed_seq, rx));
let mut states = std::collections::BTreeMap::new();
states.insert(
String::from("a.rs"),
crate::pr_review::ViewedState::Unviewed,
);
tx.send(Ok((String::from("PR_kw42"), states))).unwrap();
app.poll_pr_viewed();
assert!(
!app.editor
.pr_review
.as_ref()
.unwrap()
.viewed
.contains("a.rs")
);
});
}
/// #345: clicking an unreviewed lane row's ● marks that file reviewed;
/// clicking its name still opens the diff.
#[test]
fn clicking_a_lane_rows_dot_marks_the_file_reviewed() {
use crate::widgets::agent_lane::LaneRow;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("f.rs");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
std::fs::write(&f, "a\n").unwrap();
app.agent_ledger.record_write(
&f,
crate::agent_lane::content_hash(b"a\n"),
&[String::from("claude")],
);
app.show_agent_lane_section();
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 40)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer().clone();
let (x, y) = (0..buf.area.height)
.find_map(|y| {
let row: String = (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect();
let at = row.find("● f.rs")?;
Some((row[..at].chars().count() as u16, y))
})
.expect("the unreviewed row is painted");
let unreviewed = |app: &mut App| {
app.agent_lane_panel_rows().into_iter().any(|r| {
matches!(
r,
LaneRow::File {
unreviewed: true,
..
}
)
})
};
assert!(unreviewed(&mut app));
let click = |app: &mut App, column: u16| {
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
column,
row: y,
modifiers: KeyModifiers::NONE,
});
};
// The name opens the diff (refused here: never reviewed) and marks
// nothing.
click(&mut app, x + 3);
assert!(unreviewed(&mut app), "{}", app.status);
click(&mut app, x);
assert!(!unreviewed(&mut app), "{}", app.status);
assert!(app.status.contains("f.rs: reviewed"), "{}", app.status);
}
/// #365: an open review tab whose checks are still running re-reads them
/// in the background, and says when the last one finishes.
#[test]
fn running_pr_checks_refresh_themselves_until_they_finish() {
use std::os::unix::fs::PermissionsExt;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let gh = tmp.path().join("gh");
std::fs::write(
&gh,
r#"#!/bin/sh
echo '{"number": 42, "title": "t", "url": "https://github.com/x/y/pull/42", "author": {"login": "a"}, "files": [], "statusCheckRollup": [{"__typename": "CheckRun", "name": "build", "status": "COMPLETED", "conclusion": "SUCCESS"}]}'
"#,
)
.unwrap();
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.review_gh = gh.display().to_string();
let mut pr = crate::pr_review::parse_pr(
r#"{"number": 42, "title": "t", "url": "https://github.com/x/y/pull/42", "author": {"login": "a"}, "files": [], "statusCheckRollup": [{"__typename": "CheckRun", "name": "build", "status": "IN_PROGRESS", "conclusion": ""}]}"#,
)
.unwrap();
pr.number = 42;
app.open_pr_review(pr, String::from("x/y#42"));
assert!(app.editor.pr_review.as_ref().unwrap().has_pending_checks());
// The first pass only starts the clock; nothing is fetched yet.
app.poll_pr_gh();
assert!(app.pr_gh.is_none());
app.pr_checks_polled = Some(std::time::Instant::now() - std::time::Duration::from_secs(31));
// A due refresh runs gh. Not asserted through `pr_gh` straight after
// the poll: that poll also reads the answer, and under load the stub
// can answer before it does, leaving `pr_gh` already empty again.
// The checks turning from running to passed, below, is what only a
// gh run can do.
app.poll_pr_gh();
crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "the refresh", || {
app.poll_pr_gh();
!app.editor.pr_review.as_ref().unwrap().has_pending_checks()
});
assert_eq!(
app.editor.pr_review.as_ref().unwrap().pr.checks[0].state,
crate::pr_review::CheckState::Pass
);
assert!(
app.status.contains("every check has finished"),
"{}",
app.status
);
// Nothing pending: no more refreshes.
app.pr_checks_polled = Some(std::time::Instant::now() - std::time::Duration::from_secs(31));
app.poll_pr_gh();
assert!(app.pr_gh.is_none());
});
}
/// #263: the coverage report opens as a tab, least covered file first,
/// and without a run it says how to get one.
#[test]
fn show_coverage_report_opens_the_last_run_as_a_tab() {
use crate::widgets::command_palette::Command;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(Command::TestingShowCoverageReport);
assert!(app.status.contains("No coverage yet"), "{}", app.status);
let root = app.active_test_root.clone();
app.testing.coverage = Some(crate::testing::coverage::Coverage::from_lcov(
"SF:a.rs\nDA:1,1\nDA:2,0\nend_of_record\n",
&root,
));
app.run_command(Command::TestingShowCoverageReport);
assert_eq!(
app.editor.path.as_deref(),
Some(Path::new("Coverage Report"))
);
assert_eq!(app.editor.lines[0], "Coverage: 50.0% of 2 lines");
assert!(
app.editor.lines[2].ends_with(" a.rs"),
"{:?}",
app.editor.lines
);
}
/// #365: Review Pull Request lists the open PRs to pick from (off the UI
/// thread), picking one opens it by URL, and the last row asks for a
/// number instead. When gh cannot list, the prompt opens directly.
#[test]
fn review_pull_request_picks_from_the_open_prs() {
use crate::widgets::command_palette::Command;
use std::os::unix::fs::PermissionsExt;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let log = tmp.path().join("gh-args");
let gh = tmp.path().join("gh");
std::fs::write(
&gh,
format!(
r#"#!/bin/sh
echo "$@" >> '{}'
case "$2" in
list) echo '[{{"number": 9, "title": "Add it", "author": {{"login": "ada"}}, "url": "https://github.com/o/r/pull/9", "isDraft": false}}]' ;;
*) exit 1 ;;
esac
"#,
log.display()
),
)
.unwrap();
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.review_gh = gh.display().to_string();
app.run_command(Command::ReviewPullRequest);
crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "gh pr list", || {
app.poll_pr_gh();
app.list_picker.is_some()
});
let picker = app.list_picker.as_ref().unwrap();
assert_eq!(picker.rows.len(), 2);
assert!(picker.rows[0].label.contains("#9") && picker.rows[0].label.contains("Add it"));
assert_eq!(picker.rows[1].id, crate::widgets::list_picker::PR_BY_NUMBER);
app.confirm_list_picker();
assert!(
app.status
.contains("Loading PR https://github.com/o/r/pull/9"),
"{}",
app.status
);
crate::test_budget::await_spawned(std::time::Duration::from_secs(5), "gh pr view", || {
app.poll_pr_gh();
app.pr_gh.is_none()
});
let args = std::fs::read_to_string(&log).unwrap();
assert!(
args.lines()
.nth(1)
.unwrap()
.starts_with("pr view https://github.com/o/r/pull/9"),
"{args}"
);
// gh unable to list: straight to the prompt, with the reason.
app.review_gh = String::from("/nonexistent/gh");
app.run_command(Command::ReviewPullRequest);
crate::test_budget::await_spawned(
std::time::Duration::from_secs(5),
"the fallback",
|| {
app.poll_pr_gh();
app.input_prompt.is_some()
},
);
assert!(
app.status.contains("Could not list pull requests"),
"{}",
app.status
);
});
}
/// #356: a recorded frame is masked like a scrollback dump. The cast is a
/// file made to be shared, so a key on screen is recorded as •••, and a
/// reveal on screen does not reach it.
#[test]
fn a_recorded_frame_masks_secrets_even_while_revealed() {
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!("export KEY={key}\r\n").as_bytes());
app.reveal_redacted_secrets();
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();
assert!(!text.contains(key), "the key reached the cast:\n{text}");
assert!(text.contains("export KEY="), "{text}");
}
/// #263 against real pytest-cov: "Run Test at Cursor with Coverage" runs
/// only the caret's test, so code that only another test reaches stays
/// uncovered. Set `CROFT_TEST_PYTEST_COV_PYTHON` as for the whole-run test.
#[test]
#[ignore = "needs pytest and pytest-cov; set CROFT_TEST_PYTEST_COV_PYTHON"]
fn a_real_scoped_coverage_run_covers_only_the_test_at_the_cursor() {
use crate::testing::coverage::LineCov;
let python = std::path::PathBuf::from(std::env::var("CROFT_TEST_PYTEST_COV_PYTHON").unwrap());
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::os::unix::fs::symlink(
python.parent().and_then(Path::parent).unwrap(),
root.join(".venv"),
)
.unwrap();
std::fs::write(
root.join("pyproject.toml"),
"[project]\nname = \"t\"\nversion = \"0\"\n",
)
.unwrap();
std::fs::write(
root.join("calc.py"),
"def add(a, b):\n return a + b\n\n\ndef sub(a, b):\n return a - b\n",
)
.unwrap();
std::fs::write(
root.join("test_calc.py"),
"from calc import add, sub\n\n\ndef test_add():\n assert add(1, 2) == 3\n\n\ndef test_sub():\n assert sub(3, 2) == 1\n",
)
.unwrap();
let mut app = App::new(root.clone()).unwrap();
app.editor.open(&root.join("test_calc.py")).unwrap();
app.editor.cursor_row = 4; // inside test_add
app.run_command(crate::widgets::command_palette::Command::RunTestAtCursorWithCoverage);
assert!(app.status.contains("with coverage"), "{}", app.status);
let end = std::time::Instant::now() + std::time::Duration::from_secs(120);
while app.testing.coverage.is_none() {
assert!(std::time::Instant::now() < end, "status: {}", app.status);
let _ = app.test_worker.drain(&mut app.testing);
app.sync_coverage();
std::thread::sleep(std::time::Duration::from_millis(100));
}
let cov = app.testing.coverage.clone().unwrap();
let calc = cov
.files
.get(&root.join("calc.py"))
.expect("calc.py measured");
assert_eq!(calc.line(2), Some(LineCov::Covered), "`return a + b` ran");
assert_eq!(
calc.line(6),
Some(LineCov::Uncovered),
"only test_sub reaches `return a - b`"
);
}
/// #371: the scrubber's slider sits on the editor's bottom row; a click at
/// its left end shows the oldest commit, and dragging to its right end
/// returns to the working tree.
#[test]
fn the_scrubber_slider_seeks_on_click_and_drag() {
let repo = scrub_repo();
let mut app = App::new(repo.path().to_path_buf()).unwrap();
app.editor.open(&repo.path().join("a.txt")).unwrap();
app.scrub_history();
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let track = app.scrub_slider;
assert!(track.width > 10, "the slider lays out: {track:?}");
let row: String = (0..120)
.map(|x| term.backend().buffer()[(x, track.y)].symbol().to_string())
.collect();
assert!(row.contains("working tree"), "{row}");
let mouse = |app: &mut App, kind, column| {
app.handle_mouse(crossterm::event::MouseEvent {
kind,
column,
row: track.y,
modifiers: KeyModifiers::NONE,
});
};
mouse(
&mut app,
crossterm::event::MouseEventKind::Down(MouseButton::Left),
track.x,
);
assert_eq!(
app.scrub_view.as_ref().unwrap().lines,
vec!["v1"],
"the oldest commit"
);
term.draw(|f| app.render(f)).unwrap();
let row: String = (0..120)
.map(|x| term.backend().buffer()[(x, track.y)].symbol().to_string())
.collect();
assert!(row.contains(" 1/3 "), "{row}");
// The drag keeps seeking off the row too.
mouse(
&mut app,
crossterm::event::MouseEventKind::Drag(MouseButton::Left),
track.x + track.width + 5,
);
assert!(app.scrub_view.is_none(), "back at the working tree");
mouse(
&mut app,
crossterm::event::MouseEventKind::Up(MouseButton::Left),
0,
);
assert!(!app.scrub_dragging);
assert!(app.scrubber.is_some(), "the scrubber stays open");
}
/// #347: `a` in the approval popup approves this edit and the same agent's
/// next ones for ten minutes, with a countdown chip; another agent still
/// asks, and Agents: Stop Auto-Approving (or the time running out) ends it.
#[test]
fn approve_all_lets_one_agent_through_until_stopped() {
use std::io::{BufRead, Write};
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.rs"), "let x = 1;\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let sock = tmp.path().join("hook.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
listener.set_nonblocking(true).unwrap();
app.hook_listener = Some(listener);
let propose = |app: &mut App, agent: &str| {
let mut hook = std::os::unix::net::UnixStream::connect(&sock).unwrap();
let req = crate::agent_hook::EditRequest {
agent: agent.into(),
tool: "Edit".into(),
input: serde_json::json!({"file_path": tmp.path().join("a.rs"), "old_string": "1", "new_string": "2"}),
cwd: tmp.path().into(),
};
writeln!(hook, "{}", serde_json::to_string(&req).unwrap()).unwrap();
app.drain_hook_requests();
hook
};
let answer = |hook: std::os::unix::net::UnixStream| {
hook.set_read_timeout(Some(std::time::Duration::from_millis(200)))
.unwrap();
let mut line = String::new();
let _ = std::io::BufReader::new(hook).read_line(&mut line);
serde_json::from_str::<crate::agent_hook::Decision>(line.trim()).ok()
};
let first = propose(&mut app, "claude-code");
let other = propose(&mut app, "other-agent");
app.approval_ui.as_mut().unwrap().shown_at -= crate::agent_approval::ARM_DELAY;
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
.unwrap();
assert_eq!(answer(first), Some(crate::agent_hook::Decision::Allow));
assert!(app.status.contains("for 10 minutes"), "{}", app.status);
assert_eq!(app.approvals.len(), 1, "the other agent still asks");
assert_eq!(app.approvals[0].request.agent, "other-agent");
// The same agent's next edit goes straight through.
let next = propose(&mut app, "claude-code");
assert_eq!(answer(next), Some(crate::agent_hook::Decision::Allow));
assert_eq!(app.approvals.len(), 1);
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let bottom: String = (0..160).map(|x| buf[(x, 29)].symbol()).collect();
assert!(
bottom.contains("auto-approving claude-code 9:")
|| bottom.contains("auto-approving claude-code 10:00"),
"{bottom}"
);
app.run_command(crate::widgets::command_palette::Command::StopAutoApprove);
let after = propose(&mut app, "claude-code");
assert_eq!(app.approvals.len(), 2, "asks again once stopped");
drop((after, other));
// A window that has run out closes by itself.
app.auto_approve = Some((String::from("x"), std::time::Instant::now()));
app.drain_hook_requests();
assert!(app.auto_approve.is_none());
}
/// #363 end to end: a fleet run's results open as tiles in the Fleet tab,
/// `s` saves the whole run to a file, `d` switches to full output, Enter
/// opens a shell pane on the selected host, and Esc closes the tab.
#[test]
fn a_fleet_run_opens_tiles_that_save_and_open_a_shell() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_fleet_command("localhost: echo fleet-ok");
crate::test_budget::await_spawned(std::time::Duration::from_secs(10), "the fleet run", || {
app.drain_fleet_results();
app.editor.fleet.is_some()
});
let view = app.editor.fleet.as_ref().unwrap();
assert_eq!(view.command, "echo fleet-ok");
assert_eq!(view.results.len(), 1);
assert_eq!(view.results[0].output, "fleet-ok");
assert_eq!(app.editor.path.as_deref(), Some(Path::new("Fleet")));
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let screen: String = (0..30)
.map(|y| {
(0..120)
.map(|x| term.backend().buffer()[(x, y)].symbol())
.collect::<String>()
+ "\n"
})
.collect();
assert!(screen.contains("localhost"), "{screen}");
app.handle_key(key(KeyCode::Char('d'), KeyModifiers::NONE))
.unwrap();
assert!(!app.editor.fleet.as_ref().unwrap().diff_mode);
app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
.unwrap();
let saved = std::fs::read_dir(tmp.path())
.unwrap()
.filter_map(|e| e.ok().map(|e| e.path()))
.find(|p| {
p.file_name()
.is_some_and(|n| n.to_string_lossy().starts_with("fleet-"))
})
.expect("a capture file");
let text = std::fs::read_to_string(saved).unwrap();
assert!(text.starts_with("$ echo fleet-ok\n"), "{text}");
assert!(text.contains("== localhost (exit 0,"), "{text}");
let panes = app.terminals.len();
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.terminals.len(),
panes + 1,
"a shell pane opened: {}",
app.status
);
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(app.editor.fleet.is_none());
}
#[test]
fn fleet_shell_commands_quote_the_target() {
assert_eq!(fleet_shell_command("localhost"), None);
assert_eq!(fleet_shell_command("db-1").as_deref(), Some("ssh 'db-1'"));
assert_eq!(
fleet_shell_command("docker:web").as_deref(),
Some("docker exec -it 'web' sh")
);
}
/// A second click on the same forwarded loopback link reuses the tunnel
/// instead of asking for another (each one was a new tunnel on a random port
/// and a new browser tab, #648); a click while one is in flight asks nothing.
#[test]
fn a_forwarded_port_is_reused_and_a_pending_forward_not_repeated() {
use crate::widgets::ports::PortOrigin;
let _guard = relay_test_lock().lock().unwrap();
let workspace = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let mut app = App::new(workspace.path().to_path_buf()).unwrap();
let log = with_relay_home(home.path(), || {
let log = app.relay_log_path().expect("relay log path derivable");
app.request_remote_forward(3000, true);
app.request_remote_forward(3000, true);
let first = std::fs::read_to_string(&log).unwrap_or_default();
assert_eq!(first.matches("forward\t").count(), 1, "{first:?}");
// Once forwarded, a click opens the existing tunnel.
app.pending_remote_pulls.clear();
app.ports
.upsert(3000, None, None, PortOrigin::Remote("box".into()));
app.ports.mark_forwarded(3000, 3001);
app.request_remote_forward(3000, true);
log
});
let all = std::fs::read_to_string(&log).unwrap();
assert_eq!(all.matches("forward\t").count(), 1, "{all:?}");
assert!(all.contains("http://127.0.0.1:3001/"), "{all:?}");
}
/// #694: a source build of croft on this host stops the language servers
/// for its duration and restarts them after, since a compile next to
/// rust-analyzer is what exhausted memory on small remotes.
#[test]
fn a_source_build_pauses_the_language_servers_and_its_end_restarts_them() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.lsp.is_some(), "precondition: a manager is running");
assert!(app.apply_source_build_state(true));
assert!(app.lsp.is_none(), "the servers must stop for the build");
assert!(
!app.apply_source_build_state(true),
"a build still running changes nothing"
);
assert!(app.apply_source_build_state(false));
assert!(
app.lsp.is_some(),
"the servers must come back once the build ends"
);
assert!(!app.apply_source_build_state(false));
// Nothing running is nothing to pause, and nothing to start later: a
// manager that failed to start is not brought up by an unrelated build.
app.lsp = None;
assert!(!app.apply_source_build_state(true));
assert!(!app.apply_source_build_state(false));
assert!(app.lsp.is_none());
}
/// #694: re-rooting while a build has the language servers stopped must not
/// start them beside the compile; the build's end starts them at the new
/// root instead.
#[test]
fn a_reroot_during_a_source_build_leaves_the_servers_stopped() {
let tmp = tempfile::tempdir().unwrap();
let other = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.apply_source_build_state(true));
assert!(app.lsp.is_none());
app.change_workspace_root(other.path().to_path_buf());
assert!(
app.lsp.is_none(),
"a re-root started the servers while the build still runs"
);
assert!(app.apply_source_build_state(false));
let lsp = app
.lsp
.as_ref()
.expect("the build's end restarts the servers");
assert_eq!(
lsp.workspace_root(),
app.workspace_root(),
"the restarted servers must serve the NEW root"
);
}
/// #694 review: a resumed manager numbers semantic replies from 0 again, so
/// the old manager's per-file high-water marks must go with it, or every
/// reply for those files is rejected until the new count catches up.
#[test]
fn resuming_after_a_build_forgets_the_old_semantic_generations() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let p = tmp.path().join("a.rs");
app.semantic_generation_seen.insert(p.clone(), 500);
assert!(app.apply_source_build_state(true));
assert!(app.apply_source_build_state(false));
assert!(
semantic_reply_is_current(app.semantic_generation_seen.get(&p).copied(), 0),
"the restarted server's first reply must be accepted"
);
}
/// #694 review: diagnostics of a file with no open buffer do not outlive a
/// pause; nothing else would ever drop them.
#[test]
fn resuming_after_a_build_drops_diagnostics_no_open_tab_owns() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "open.rs", "fn main() {}");
let open = app.editor.path.clone().unwrap();
let closed = tmp.path().join("closed.rs");
app.lsp_diagnostics.insert(open.clone(), Default::default());
app.lsp_diagnostics
.insert(closed.clone(), Default::default());
assert!(app.apply_source_build_state(true));
assert!(app.apply_source_build_state(false));
assert!(
!app.lsp_diagnostics.contains_key(&closed),
"a tab closed during the build kept its diagnostics"
);
assert!(
app.lsp_diagnostics.contains_key(&open),
"an open tab's diagnostics stay until the new servers publish"
);
}
/// #694 review: a format-on-save in flight when the servers stop is saved at
/// once, unformatted, rather than left armed for an unrelated reply.
#[test]
fn pausing_for_a_build_completes_a_pending_format_on_save() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}");
let file = app.editor.path.clone().unwrap();
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
app.format_request_id = Some(7);
app.save_after_format = Some(file.clone());
assert!(app.apply_source_build_state(true));
assert!(app.format_request_id.is_none());
assert!(app.save_after_format.is_none(), "the save was left armed");
assert!(
std::fs::read_to_string(&file).unwrap().starts_with('x'),
"the edit must reach disk"
);
}
/// A local croft (no update watcher) never pauses its servers, and the
/// marker is read at most once a second.
#[test]
fn only_a_remote_launched_croft_polls_the_build_marker() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.update_watch.is_none());
assert!(!app.poll_source_build_marker());
assert!(
app.build_marker_checked.is_none(),
"a local croft read the marker"
);
assert!(app.lsp.is_some());
app.update_watch = Some(crate::update_watch::UpdateWatch::start(
tmp.path().to_path_buf(),
String::new(),
));
let just_now = std::time::Instant::now();
app.build_marker_checked = Some(just_now);
assert!(!app.poll_source_build_marker());
assert_eq!(
app.build_marker_checked,
Some(just_now),
"the marker was read again within the second"
);
}
/// #737: the poll's positive path. A marker naming a live build pauses the
/// servers of a remote-launched croft; the marker going resumes them.
#[test]
fn a_live_build_marker_pauses_the_servers_and_its_removal_resumes_them() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.update_watch = Some(crate::update_watch::UpdateWatch::start(
tmp.path().to_path_buf(),
String::new(),
));
let cache = croft_cache_dir();
std::fs::create_dir_all(&cache).unwrap();
let marker = cache.join(format!(
"{}{}",
crate::update_watch::BUILD_MARKER_PREFIX,
std::process::id()
));
// This test process stands in for the compile: alive, and ours.
std::fs::write(&marker, std::process::id().to_string()).unwrap();
if let Some(boot) = crate::update_watch::boot_id() {
let sidecar = format!(
"{}{}",
marker.display(),
crate::update_watch::BOOT_SIDECAR_SUFFIX
);
std::fs::write(sidecar, boot).unwrap();
}
assert!(app.poll_source_build_marker());
assert!(app.lsp.is_none() && app.lsp_paused_for_build);
std::fs::remove_file(&marker).unwrap();
app.build_marker_checked = None; // past the once-a-second gate
assert!(app.poll_source_build_marker());
assert!(app.lsp.is_some() && !app.lsp_paused_for_build);
});
}
/// #737: a re-root starts a new manager, which numbers semantic replies from
/// 0 again, so the old high-water marks go with the old one.
#[test]
fn a_reroot_forgets_the_old_semantic_generations() {
let tmp = tempfile::tempdir().unwrap();
let other = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let p = tmp.path().join("a.rs");
app.semantic_generation_seen.insert(p.clone(), 500);
app.change_workspace_root(other.path().to_path_buf());
assert!(
semantic_reply_is_current(app.semantic_generation_seen.get(&p).copied(), 0),
"the new server's first reply must be accepted"
);
assert!(app.lsp.is_some(), "the new root's servers started");
}
/// #694: an "all clear" from the last server reporting on a path drops the
/// path from the store instead of leaving an empty entry behind; another
/// server's findings on it survive.
#[test]
fn an_all_clear_from_every_server_drops_the_path_from_the_store() {
use crate::lsp::manager::{DiagnosticSeverity, DiagnosticsUpdate};
let mut store = std::collections::HashMap::new();
let path = PathBuf::from("/w/gone.rs");
let update = |server: &str, diagnostics| DiagnosticsUpdate {
path: path.clone(),
server: server.to_string(),
diagnostics,
};
store_diagnostics_update(
&mut store,
update("ra", vec![diag(0, 1, DiagnosticSeverity::Error)]),
);
store_diagnostics_update(
&mut store,
update("clippy", vec![diag(2, 3, DiagnosticSeverity::Warning)]),
);
store_diagnostics_update(&mut store, update("ra", Vec::new()));
assert_eq!(store[&path].len(), 1, "clippy's findings stay");
store_diagnostics_update(&mut store, update("clippy", Vec::new()));
assert!(store.is_empty(), "{store:?}");
// An all-clear for a path never reported does not create one.
store_diagnostics_update(&mut store, update("ra", Vec::new()));
assert!(store.is_empty());
}
/// #262: a config file croft did not write itself (one that arrived by
/// config sync) is applied within the watch interval, not on next launch;
/// a macro croft records itself is not reloaded behind its back.
#[test]
fn a_macros_file_written_outside_croft_is_reloaded_live() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let store = tmp.path().join("macros.json");
app.macros_path = store.clone();
app.config_watch = crate::config_sync::ConfigWatch::new(vec![store.clone()]);
app.macro_registers.clear();
let mut mac = crate::macros::Macro::default();
mac.push_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Char('x'),
crossterm::event::KeyModifiers::NONE,
));
crate::macros::save_register(&store, "q", mac).unwrap();
let t0 = std::time::Instant::now();
assert!(!app.tick_config_watch_at(t0), "not before the interval");
assert!(app.tick_config_watch_at(t0 + crate::config_sync::ConfigWatch::INTERVAL * 2));
assert!(
app.macro_registers.contains_key("q"),
"{:?}",
app.macro_registers.keys()
);
assert!(app.status.starts_with("Macros reloaded"), "{}", app.status);
// Nothing more changed: the next check reloads nothing.
assert!(!app.tick_config_watch_at(t0 + crate::config_sync::ConfigWatch::INTERVAL * 4));
}
/// #577: export to a `.sarif` name writes the visible results as SARIF,
/// each run kept with its tool and rules, filtered results left out and a
/// run with nothing left dropped; any other name still gets CSV.
#[test]
fn sarif_export_writes_the_visible_results_as_sarif_or_csv() {
use crate::sarif::semantics::Level;
let tmp = tempfile::tempdir().unwrap();
let log = tmp.path().join("two.sarif");
std::fs::write(
&log,
r#"{"version":"2.1.0","runs":[
{"tool":{"driver":{"name":"lint","rules":[{"id":"R1"},{"id":"R2"}]}},
"results":[{"ruleId":"R1","level":"error","message":{"text":"bad"}},
{"ruleId":"R2","level":"note","message":{"text":"meh"}}]},
{"tool":{"driver":{"name":"other"}},
"results":[{"ruleId":"X","level":"note","message":{"text":"quiet"}}]}]}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&log).unwrap();
app.editor
.sarif
.as_mut()
.unwrap()
.filters
.hidden_levels
.insert(Level::Note);
app.submit_sarif_export("out.sarif");
assert!(app.status.contains("Exported 1 result"), "{}", app.status);
let out: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(tmp.path().join("out.sarif")).unwrap())
.unwrap();
assert_eq!(out["version"], "2.1.0");
let runs = out["runs"].as_array().unwrap();
assert_eq!(runs.len(), 1, "the run left empty is dropped");
assert_eq!(runs[0]["tool"]["driver"]["name"], "lint");
assert_eq!(
runs[0]["tool"]["driver"]["rules"].as_array().unwrap().len(),
2
);
let results = runs[0]["results"].as_array().unwrap();
assert_eq!(results.len(), 1);
assert_eq!(results[0]["ruleId"], "R1");
// And the exported log opens again in the viewer.
app.editor.open(&tmp.path().join("out.sarif")).unwrap();
assert_eq!(app.editor.sarif.as_ref().unwrap().entries.len(), 1);
app.editor.open(&log).unwrap();
app.submit_sarif_export("out.csv");
let csv = std::fs::read_to_string(tmp.path().join("out.csv")).unwrap();
assert!(csv.starts_with("rule,level,file"), "{csv}");
}
#[test]
fn sync_config_now_runs_the_cli_in_a_pane_for_a_plain_host_only() {
// #262: the palette command types `croft sync-config <host>` into a
// new terminal, so the host must be an alias, never shell text.
use crate::widgets::command_palette::Command;
assert_eq!(
Command::from_id("remote_sync_config_now"),
Some(Command::RemoteSyncConfigNow)
);
assert_eq!(
Command::RemoteSyncConfigNow.title(),
"Remote: Sync Config Now"
);
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for bad in ["dev box", "x;rm -rf ~", "-oProxyCommand=x", ""] {
app.sync_config_to(bad);
assert!(
app.status.contains("not an ssh host alias"),
"{bad:?}: {}",
app.status
);
}
app.sync_config_to("user@dev-box.lan");
assert_eq!(app.status, "Syncing config to user@dev-box.lan");
}
#[test]
fn the_outline_and_breadcrumbs_follow_the_scrubbed_commit() {
// #371: while scrubbing, the Outline lists the file as it was at the
// commit on screen, the breadcrumbs follow the historical caret, a
// symbol jump lands in the history, and leaving brings the live
// outline back.
let tmp = tempfile::tempdir().unwrap();
let git = |args: &[&str]| {
let ok = std::process::Command::new("git")
.arg("-C")
.arg(tmp.path())
.args(args)
.output()
.unwrap()
.status
.success();
assert!(ok, "git {args:?}");
};
git(&["init", "-q", "-b", "main"]);
git(&["config", "user.email", "a@b"]);
git(&["config", "user.name", "a"]);
let file = tmp.path().join("lib.rs");
std::fs::write(&file, "fn alpha() {\n let a = 1;\n}\n").unwrap();
git(&["add", "."]);
git(&["commit", "-q", "-m", "alpha"]);
std::fs::write(
&file,
"fn beta() {\n}\n\nfn alpha() {\n let a = 1;\n}\n\nfn gamma() {\n}\n",
)
.unwrap();
git(&["commit", "-q", "-am", "beta and gamma"]);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&file).unwrap();
let names = |app: &App| -> Vec<String> {
app.outline
.symbols()
.iter()
.map(|s| s.name.clone())
.collect()
};
app.sync_outline();
assert_eq!(
names(&app),
["beta", "alpha", "gamma"],
"control: live outline"
);
app.scrub_history();
assert!(app.handle_scrubber_key(KeyCode::Left), "HEAD");
assert!(app.handle_scrubber_key(KeyCode::Left), "the root commit");
settle_scrub_outline(&mut app);
assert_eq!(names(&app), ["alpha"], "the commit's outline");
// A jump to `alpha` lands in the historical view, where it is line 0,
// and the breadcrumbs name it from there.
let target = app.outline.jump_target(0).unwrap().1;
assert!(app.jump_in_scrub_view(target));
assert_eq!(app.scrub_view.as_ref().unwrap().cursor_row, 0);
app.editor.cursor_row = 7; // the live caret, inside `gamma`
let crumbs: Vec<String> = app
.build_breadcrumbs()
.into_iter()
.map(|c| c.label)
.collect();
assert_eq!(
crumbs.last().map(String::as_str),
Some("alpha"),
"{crumbs:?}"
);
// Switching to a file that did not exist at this commit: its outline
// is its own (none), never the previous file's history under its name.
let other = tmp.path().join("other.rs");
std::fs::write(&other, "fn zeta() {}\n").unwrap();
app.editor.open(&other).unwrap();
app.sync_outline();
assert!(names(&app).is_empty(), "{:?}", names(&app));
app.editor.open(&file).unwrap();
app.sync_outline();
assert_eq!(names(&app), ["alpha"]);
assert!(
app.handle_scrubber_key(KeyCode::Home),
"back to the working tree"
);
app.sync_outline();
assert_eq!(
names(&app),
["beta", "alpha", "gamma"],
"the live outline is back"
);
assert!(!app.jump_in_scrub_view(0), "no history on screen");
}
#[test]
fn review_mode_checks_the_pr_out_and_leaving_removes_a_clean_checkout() {
// #365: `c` fetches the PR head into a sibling worktree added to the
// workspace, and Esc takes it away again when nothing was changed.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let git = |dir: &Path, args: &[&str]| {
let out = std::process::Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "git {args:?}");
String::from_utf8_lossy(&out.stdout).trim().to_string()
};
// The "GitHub" repository, at a path ending in the PR's `o/r`, so
// the remote naming it is found without a network.
let up = tmp.path().join("o").join("r");
std::fs::create_dir_all(&up).unwrap();
git(&up, &["init", "-q", "-b", "main"]);
git(&up, &["config", "user.email", "a@b"]);
git(&up, &["config", "user.name", "a"]);
std::fs::write(up.join("a.txt"), "base").unwrap();
git(&up, &["add", "."]);
git(&up, &["commit", "-q", "-m", "base"]);
std::fs::write(up.join("a.txt"), "pr").unwrap();
git(&up, &["commit", "-q", "-am", "pr"]);
let head = git(&up, &["rev-parse", "HEAD"]);
git(&up, &["update-ref", "refs/pull/579/head", &head]);
git(&up, &["reset", "-q", "--hard", "HEAD~1"]);
git(tmp.path(), &["clone", "-q", up.to_str().unwrap(), "app"]);
let root = tmp.path().join("app").canonicalize().unwrap();
let mut app = App::new(root.clone()).unwrap();
app.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
app.handle_pr_review_key(key(KeyCode::Char('c'), KeyModifiers::NONE));
assert!(app.status.contains("Fetching PR #579"), "{}", app.status);
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"PR checkout",
|| {
app.poll_pr_checkout();
app.pr_checkout_rx.is_none()
},
);
let checkout = tmp.path().join("app-pr-579").canonicalize().unwrap();
assert!(app.status.contains("checked out"), "{}", app.status);
assert!(
app.roots.iter().any(|r| r == checkout),
"added to the workspace"
);
assert_eq!(
std::fs::read_to_string(checkout.join("a.txt")).unwrap(),
"pr"
);
app.handle_pr_review_key(key(KeyCode::Esc, KeyModifiers::NONE));
assert!(
app.status.contains("removed its checkout"),
"{}",
app.status
);
assert!(!checkout.exists(), "the worktree is gone");
assert!(!app.roots.iter().any(|r| r == checkout));
assert!(app.pr_checkout.is_none());
// Leaving before the fetch lands: nobody owns the result, so it is
// settled on arrival, never adopted.
app.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
app.handle_pr_review_key(key(KeyCode::Char('c'), KeyModifiers::NONE));
app.handle_pr_review_key(key(KeyCode::Esc, KeyModifiers::NONE));
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"PR checkout",
|| {
app.poll_pr_checkout();
app.pr_checkout_rx.is_none()
},
);
assert!(
app.status
.contains("after its review closed; removed its checkout"),
"{}",
app.status
);
assert!(app.pr_checkout.is_none() && !checkout.exists());
assert!(!app.roots.iter().any(|r| r == checkout));
// An unsaved tab under the checkout keeps it.
app.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
app.handle_pr_review_key(key(KeyCode::Char('c'), KeyModifiers::NONE));
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"PR checkout",
|| {
app.poll_pr_checkout();
app.pr_checkout_rx.is_none()
},
);
let checkout = tmp.path().join("app-pr-579").canonicalize().unwrap();
app.editor.open(&checkout.join("a.txt")).unwrap();
app.editor.dirty = true;
app.open_pr_review(crate::widgets::pr_review::tests::sample(), "o/r#579".into());
app.handle_pr_review_key(key(KeyCode::Esc, KeyModifiers::NONE));
assert!(
app.status.contains("a.txt has unsaved changes"),
"{}",
app.status
);
assert!(checkout.exists(), "kept");
});
}
#[test]
fn code_scanning_follows_the_branch_when_on_and_only_says_so_when_prompting() {
// #577: `code_scanning = on` loads the branch's newest analysis per
// tool at the nearest scanned commit, and again after a checkout of
// another branch; `prompt` names them and waits; `off` never asks.
use std::os::unix::fs::PermissionsExt;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let git = |args: &[&str]| {
let out = std::process::Command::new("git")
.arg("-C")
.arg(tmp.path())
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "git {args:?}");
String::from_utf8_lossy(&out.stdout).trim().to_string()
};
git(&["init", "-q", "-b", "main"]);
git(&["config", "user.email", "a@b"]);
git(&["config", "user.name", "a"]);
std::fs::write(tmp.path().join("a.txt"), "a").unwrap();
git(&["add", "."]);
git(&["commit", "-q", "-m", "scanned"]);
let scanned = git(&["rev-parse", "HEAD"]);
std::fs::write(tmp.path().join("a.txt"), "b").unwrap();
git(&["commit", "-q", "-am", "not scanned yet"]);
let log = tmp.path().join("gh-args");
let gh = tmp.path().join("gh");
std::fs::write(
&gh,
format!(
r#"#!/bin/sh
echo "$@" >> '{log}'
case "$*" in
*sarif+json*) echo '{{"version": "2.1.0", "runs": []}}' ;;
*) echo '[{{"id": 7, "ref": "refs/heads/main", "commit_sha": "{scanned}", "tool": {{"name": "CodeQL"}}, "created_at": "2026-09-01T00:00:00Z", "results_count": 0}}, {{"id": 6, "ref": "refs/heads/main", "commit_sha": "0000", "tool": {{"name": "CodeQL"}}, "created_at": "2026-09-02T00:00:00Z", "results_count": 0}}]' ;;
esac
"#,
log = log.display()
),
)
.unwrap();
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.gh_program = gh.clone();
app.source_control.status.in_repo = true;
app.source_control.status.branch = Some(String::from("main"));
// Off: nothing is asked.
app.poll_code_scanning();
assert!(
app.code_scan_list.is_none() && !log.exists(),
"off never calls gh"
);
app.code_scanning = crate::sarif::github::CodeScanningMode::On;
let settle = |app: &mut App| {
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"code scanning",
|| {
app.poll_code_scanning();
app.code_scan_list.is_none() && app.code_scan_fetch.is_none()
},
);
};
app.poll_code_scanning();
settle(&mut app);
assert_eq!(app.status, "Loaded 1 code scanning analysis");
assert!(
app.editor.sarif.is_some(),
"the analysis opened in the viewer"
);
let calls = std::fs::read_to_string(&log).unwrap();
assert!(
calls.contains("ref=refs%2Fheads%2Fmain") || calls.contains("ref=refs/heads/main"),
"{calls}"
);
assert!(
calls.contains("analyses/7"),
"the one at the nearest scanned commit: {calls}"
);
assert!(!calls.contains("analyses/6"), "{calls}");
// The same branch is not looked up again; another one is.
std::fs::remove_file(&log).unwrap();
app.poll_code_scanning();
assert!(app.code_scan_list.is_none() && !log.exists());
app.code_scanning = crate::sarif::github::CodeScanningMode::Prompt;
app.source_control.status.branch = None;
app.source_control.status.detached_hash = Some(scanned.clone());
app.poll_code_scanning();
settle(&mut app);
assert!(
app.status
.starts_with("Code scanning has 1 analysis for detached HEAD"),
"{}",
app.status
);
let calls = std::fs::read_to_string(&log).unwrap();
assert!(
!calls.contains("sarif+json"),
"prompt downloads nothing: {calls}"
);
});
}
/// #694: Developer: Show Memory Usage opens a tab attributing memory to
/// each subsystem, with the stored diagnostics counted per server.
#[test]
fn show_memory_usage_opens_a_per_subsystem_report() {
use crate::lsp::manager::DiagnosticSeverity;
use crate::widgets::command_palette::Command;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mut by_server = std::collections::HashMap::new();
by_server.insert(
String::from("ruff"),
vec![
diag(0, 1, DiagnosticSeverity::Warning),
diag(2, 3, DiagnosticSeverity::Error),
],
);
app.lsp_diagnostics
.insert(tmp.path().join("a.py"), by_server);
app.run_command(Command::DeveloperShowMemoryUsage);
assert_eq!(app.editor.path.as_deref(), Some(Path::new("Memory Usage")));
let text = app.editor.lines.join("\n");
for section in ["Terminal panes", "Undo history", "OUTPUT channels"] {
assert!(text.contains(section), "{text}");
}
assert!(text.contains("ruff: 2 diagnostics in 1 files"), "{text}");
}
/// #264: an adapter that refuses to start the program (delve and a Go too
/// old for it) ends the debug session with its reason in the status and
/// the Run and Debug feedback, not "Debug session ended", and not a
/// session left Initializing.
#[test]
fn a_refused_debug_launch_says_why() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let refused = r#"{"seq":1,"type":"response","request_seq":2,"success":false,"command":"launch","message":"Failed to launch","body":{"error":{"id":3000,"format":"Failed to launch /w: Go version go1.24.7 is too old for this version of Delve"}}}"#;
app.debug_sessions.push("go", stub_emitting(&[refused]));
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"the refusal to end the session",
|| {
app.poll_dap();
app.debug_sessions.is_empty()
},
);
assert!(
app.status
.starts_with("Could not start debugging: Failed to launch /w: Go version"),
"{}",
app.status
);
assert!(app.run_debug.feedback_is_error);
assert!(
app.run_debug
.feedback
.as_deref()
.is_some_and(|f| f.contains("too old for this version of Delve"))
);
}
/// #345: the agent review queue, and what was marked reviewed, survive a
/// restart and a re-root away and back; the Explorer's dots come back too.
#[test]
fn the_agent_review_queue_survives_a_restart_and_a_reroot() {
let tmp = tempfile::tempdir().unwrap();
let other = tempfile::tempdir().unwrap();
let store = tempfile::tempdir().unwrap().keep().join("agent_lane.json");
let a = tmp.path().join("a.rs");
let b = tmp.path().join("b.rs");
std::fs::write(&a, "a").unwrap();
std::fs::write(&b, "b").unwrap();
let working = [String::from("claude")];
let root = tmp.path().canonicalize().unwrap();
let (a, b) = (root.join("a.rs"), root.join("b.rs"));
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.agent_ledger_store = Some(store.clone());
app.agent_ledger.record_write(&a, 1, &working);
app.agent_ledger.record_write(&b, 2, &working);
app.agent_ledger.mark_reviewed("claude", &b, 2, None);
app.persist_agent_ledger(true);
drop(app);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.agent_ledger_store = Some(store.clone());
app.agent_ledger = app.load_agent_ledger(&root);
app.sync_agent_lane_decorations();
assert!(app.agent_ledger.is_unreviewed(&a), "the queue came back");
assert!(!app.agent_ledger.is_unreviewed(&b), "and b stays reviewed");
assert!(app.tree.agent_touched.contains(&a), "the Explorer's dot");
// Away and back: each workspace keeps its own queue.
app.change_workspace_root(other.path().to_path_buf());
assert!(app.agent_ledger.is_empty());
app.change_workspace_root(tmp.path().to_path_buf());
assert!(app.agent_ledger.is_unreviewed(&a));
// Reviewing everything empties the queue and drops its saved entry.
app.agent_ledger.mark_reviewed("claude", &a, 1, None);
app.agent_ledger.forget("claude");
app.persist_agent_ledger(true);
let saved = std::fs::read_to_string(&store).unwrap();
assert!(!saved.contains(&root.display().to_string()), "{saved}");
}
/// #345: the lane is reachable from the keyboard: "Agents: Review a Changed
/// File" lists every lane's files, and Enter opens the chosen one's diff.
#[test]
fn the_lane_file_picker_opens_the_chosen_files_diff() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let a = root.join("a.rs");
std::fs::write(&a, "a\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(crate::widgets::command_palette::Command::PickAgentLaneFile);
assert_eq!(app.status, "No agent has changed a file");
assert!(app.list_picker.is_none());
app.agent_ledger
.record_write(&a, 1, &[String::from("claude")]);
app.run_command(crate::widgets::command_palette::Command::PickAgentLaneFile);
let picker = app.list_picker.as_ref().expect("a picker");
assert_eq!(picker.rows.len(), 1);
assert!(
picker.rows[0].label.contains("a.rs"),
"{}",
picker.rows[0].label
);
assert!(picker.rows[0].label.contains("(claude)"));
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(app.list_picker.is_none());
// Never reviewed, so the diff is refused with the reason, as a click on
// the row is: the pick reached `diff_agent_lane_row`.
assert!(app.status.contains("review"), "{}", app.status);
}
#[test]
fn edit_then_approve_sends_the_saved_text_as_the_tools_input() {
// #347: `e` opens the proposal as a scratch file with the popup put
// away; closing it unsaved brings the popup back; saving it approves
// with input that makes the agent's own tool write the edited text.
use std::io::{BufRead, Write};
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("a.rs");
std::fs::write(&target, "let x = 1;\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let sock = tmp.path().join("hook.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
listener.set_nonblocking(true).unwrap();
app.hook_listener = Some(listener);
let mut hook = std::os::unix::net::UnixStream::connect(&sock).unwrap();
let input = serde_json::json!({"file_path": target, "old_string": "1", "new_string": "2"});
let req = crate::agent_hook::EditRequest {
agent: "claude-code".into(),
tool: "Edit".into(),
input,
cwd: tmp.path().into(),
};
writeln!(hook, "{}", serde_json::to_string(&req).unwrap()).unwrap();
// A tab with unsaved work, which opening the proposal must not
// replace.
let other = tmp.path().join("b.rs");
std::fs::write(&other, "fn b() {}\n").unwrap();
app.editor.open_pinned(&other).unwrap();
app.editor.lines[0] = String::from("fn b() { unsaved }");
app.editor.dirty = true;
app.drain_hook_requests();
let arm = |app: &mut App| {
app.approval_ui.as_mut().unwrap().shown_at -= crate::agent_approval::ARM_DELAY;
};
arm(&mut app);
app.handle_key(key(KeyCode::Char('e'), KeyModifiers::NONE))
.unwrap();
assert!(app.approval_ui.is_none(), "the popup is put away");
let scratch = app.approval_edit.as_ref().unwrap().1.clone();
assert_eq!(app.editor.path.as_deref(), Some(scratch.as_path()));
assert_eq!(app.editor.lines[0], "let x = 2;", "the proposal's text");
app.drain_hook_requests();
assert!(app.approval_ui.is_none(), "and stays away while editing");
// Closed unsaved: back to the popup, nothing answered.
app.editor.close_active();
app.drain_hook_requests();
assert!(app.approval_edit.is_none() && app.approval_ui.is_some());
assert_eq!(app.approvals.len(), 1);
arm(&mut app);
app.handle_key(key(KeyCode::Char('e'), KeyModifiers::NONE))
.unwrap();
app.editor.lines[0] = String::from("let x = 3;");
app.editor.dirty = true;
app.write_current_to_disk();
assert!(app.status.contains("as you changed it"), "{}", app.status);
assert!(app.approvals.is_empty() && app.approval_edit.is_none());
hook.set_read_timeout(Some(std::time::Duration::from_millis(500)))
.unwrap();
let mut line = String::new();
std::io::BufReader::new(hook).read_line(&mut line).unwrap();
let crate::agent_hook::Decision::AllowEdited { input } =
serde_json::from_str(line.trim()).unwrap()
else {
panic!("not an edited approval: {line}");
};
let read = |p: &std::path::Path| std::fs::read_to_string(p);
let replay =
crate::agent_approval::proposal_for("Edit", &input, tmp.path(), &read).unwrap();
assert_eq!(
replay.after, "let x = 3;\n",
"the agent's Edit writes what was saved"
);
app.editor.open_pinned(&other).unwrap();
assert!(app.editor.dirty, "the other tab kept its unsaved work");
assert_eq!(app.editor.lines[0], "fn b() { unsaved }");
});
}
#[test]
fn an_agent_edit_to_a_dirty_tab_goes_through_a_three_way_merge() {
// #347: the proposal is computed from disk, so approving it over a tab
// with unsaved edits would put the agent's write under them. Enter
// opens a merge (disk, yours, the agent's) instead; auto-approve never
// lets it through; saving with conflicts left approves nothing; the
// resolved result is what the agent writes, and the tab holds it too.
use std::io::{BufRead, Write};
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("a.rs");
std::fs::write(&target, "one\ntwo\nthree\nfour\nfive\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&target).unwrap();
app.editor.lines[0] = String::from("ONE"); // yours: line 1
app.editor.lines[2] = String::from("mine"); // yours: line 3, in conflict
app.editor.dirty = true;
app.editor.pin_active(); // as any real edit does
let sock = tmp.path().join("hook.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
listener.set_nonblocking(true).unwrap();
app.hook_listener = Some(listener);
// The agent's: lines 3 and 5 (Write, so the whole text).
let mut hook = std::os::unix::net::UnixStream::connect(&sock).unwrap();
let req = crate::agent_hook::EditRequest {
agent: "claude-code".into(),
tool: "Write".into(),
input: serde_json::json!({"file_path": target, "content": "one\ntwo\ntheirs\nfour\nFIVE\n"}),
cwd: tmp.path().into(),
};
writeln!(hook, "{}", serde_json::to_string(&req).unwrap()).unwrap();
// Auto-approving this agent does not approve an edit under unsaved text.
app.auto_approve = Some((
String::from("claude-code"),
std::time::Instant::now() + std::time::Duration::from_secs(60),
));
app.drain_hook_requests();
assert_eq!(app.approvals.len(), 1, "auto-approved over unsaved edits");
app.auto_approve = None;
assert!(app.approval_ui.as_ref().unwrap().target_dirty);
app.approval_ui.as_mut().unwrap().shown_at -= crate::agent_approval::ARM_DELAY;
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.approvals.len(), 1, "Enter approved over unsaved edits");
let scratch = app.approval_edit.as_ref().unwrap().1.clone();
assert_eq!(app.editor.path.as_deref(), Some(scratch.as_path()));
let mv = app.editor.merge.as_ref().expect("a merge view");
assert_eq!(mv.conflicts.len(), 1, "line 3 changed on both sides");
let conflict_row = mv.conflicts[0].result_start;
assert_eq!(
app.editor.lines,
["ONE", "two", "three", "four", "FIVE"],
"each side's own change applied, the conflict holding the base"
);
// Saving with the conflict open approves nothing.
app.editor.dirty = true;
app.write_current_to_disk();
assert!(app.status.contains("1 conflict left"), "{}", app.status);
assert_eq!(app.approvals.len(), 1);
app.editor.cursor_row = conflict_row;
app.merge_apply(crate::merge_editor::ConflictState::Incoming);
app.write_current_to_disk();
assert!(app.approvals.is_empty(), "{}", app.status);
assert!(
app.status.contains("your tab holds the same text"),
"{}",
app.status
);
hook.set_read_timeout(Some(std::time::Duration::from_millis(500)))
.unwrap();
let mut line = String::new();
std::io::BufReader::new(hook).read_line(&mut line).unwrap();
let crate::agent_hook::Decision::AllowEdited { input } =
serde_json::from_str(line.trim()).unwrap()
else {
panic!("not an edited approval: {line}");
};
assert_eq!(input["content"], "ONE\ntwo\ntheirs\nfour\nFIVE\n");
// The user's tab is still there, and holds what the agent is about
// to write.
app.editor.open_pinned(&target).unwrap();
assert_eq!(app.editor.lines, ["ONE", "two", "theirs", "four", "FIVE"]);
});
}
/// #371's criterion, measured: after a warm-up pass, holding an arrow key
/// back across up to 200 commits of this repository's own
/// `src/app/mod.rs` stays under a frame (16 ms) per step, the step and the
/// frame it paints. Highlighting that file takes over half a second, so a
/// step shows the plain text the builder already split and swaps the
/// finished view in behind it. Needs this checkout's history, so it is
/// ignored by default.
#[test]
#[ignore]
fn scrubbing_the_biggest_file_stays_under_a_frame_per_step() {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let mut app = App::new(root.clone()).unwrap();
app.editor.open(&root.join("src/app/mod.rs")).unwrap();
app.scrub_history();
let steps = app.scrubber.as_ref().map_or(0, |s| s.len()).min(200);
assert!(steps > 20, "only {steps} commits to scrub");
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 50)).unwrap();
term.draw(|f| app.render(f)).unwrap();
// A held arrow key repeats about 30 times a second; between repeats the
// main loop takes in what the builder produced.
let repeat = std::time::Duration::from_millis(33);
// Warm-up, as the criterion allows: one pass reads every version.
for _ in 0..steps {
std::thread::sleep(repeat);
app.drain_scrub_views();
app.handle_scrubber_key(KeyCode::Left);
app.sync_outline();
}
app.handle_scrubber_key(KeyCode::Home);
let mut times = Vec::with_capacity(steps);
for _ in 0..steps {
std::thread::sleep(repeat);
app.drain_scrub_views();
let t = std::time::Instant::now();
app.handle_scrubber_key(KeyCode::Left);
// What the main loop runs between the key and the frame: the
// Outline follows the commit on screen.
app.sync_outline();
term.draw(|f| app.render(f)).unwrap();
times.push(t.elapsed());
}
times.sort();
let p50 = times[times.len() / 2];
let p95 = times[times.len() * 95 / 100];
let max = *times.last().unwrap();
eprintln!("{steps} steps: p50 {p50:?} p95 {p95:?} max {max:?}");
assert!(p95 < std::time::Duration::from_millis(16), "p95 {p95:?}");
}
#[test]
fn codeql_variant_analysis_repositories_are_set_up_from_the_side_bar_and_palette() {
// The cache-dir override is process-global; serialize with the
// other tests that redirect it.
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
// #578: VS Code's Variant Analysis Repositories view: a controller
// repository, then lists, repositories and owners to run against.
use crate::codeql_variant::{Item, Selection, VariantConfig};
use crate::widgets::codeql::{Action, Line};
use crate::widgets::command_palette::Command;
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_codeql_view();
app.focus = Pane::Tree;
let press = |app: &mut App, code: KeyCode| {
app.handle_key(key(code, KeyModifiers::NONE)).unwrap();
};
let type_in = |app: &mut App, text: &str| {
for c in text.chars() {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
};
let saved = || VariantConfig::load(&App::codeql_variant_path()).unwrap();
// The welcome row asks for the controller and refuses a bad one.
app.codeql.select_action(Action::SetUpControllerRepository);
press(&mut app, KeyCode::Enter);
assert_eq!(
app.input_prompt.as_ref().map(|p| &p.purpose),
Some(&crate::widgets::input_prompt::InputPurpose::CodeqlControllerRepository)
);
type_in(&mut app, "not a repo");
assert!(
app.status.contains("is not a GitHub repository"),
"{}",
app.status
);
assert!(!App::codeql_variant_path().exists(), "nothing saved");
press(&mut app, KeyCode::Enter);
type_in(&mut app, "https://github.com/me/ctl.git");
assert_eq!(saved().controller_repo.as_deref(), Some("me/ctl"));
assert!(app.codeql.lines().contains(&Line::Action(
Action::SetUpControllerRepository,
"Controller: me/ctl".into()
)));
// `l` adds a list, `a` a repository into the selected list.
press(&mut app, KeyCode::Char('l'));
type_in(&mut app, "top");
assert_eq!(app.codeql.selected_variant_item(), Some(Item::List(0)));
press(&mut app, KeyCode::Char('a'));
assert_eq!(
app.input_prompt.as_ref().unwrap().title,
"Add Repository to top"
);
type_in(&mut app, "github/codeql");
assert_eq!(saved().lists[0].repos, ["github/codeql"]);
assert_eq!(
app.codeql.selected_variant_item(),
Some(Item::Repo(Some(0), 0))
);
press(&mut app, KeyCode::Char('a'));
type_in(&mut app, "GitHub/CodeQL");
assert!(app.status.contains("already in list top"), "{}", app.status);
// `o` adds an owner; the palette adds a single repository.
press(&mut app, KeyCode::Char('o'));
type_in(&mut app, "octo-org");
assert_eq!(saved().owners, ["octo-org"]);
assert_eq!(app.codeql.selected_variant_item(), Some(Item::Owner(0)));
app.run_command(Command::CodeqlAddVariantRepo);
type_in(&mut app, "https://github.com/e/f/tree/main");
assert_eq!(saved().repos, ["e/f"]);
// Enter selects what a run targets, marked in the side bar.
assert_eq!(
app.codeql.selected_variant_item(),
Some(Item::Repo(None, 0))
);
press(&mut app, KeyCode::Enter);
assert_eq!(
saved().selected,
Some(Selection::Repo {
nwo: "e/f".into(),
list: None
})
);
assert!(
app.codeql
.lines()
.contains(&Line::Action(Action::VariantRepo(None, 0), "● e/f".into()))
);
press(&mut app, KeyCode::Char('g'));
assert_eq!(app.status, "Open https://github.com/e/f");
// It persists for the next session.
let mut again = App::new(tmp.path().to_path_buf()).unwrap();
again.open_codeql_view();
assert_eq!(again.codeql.variant, saved());
// F2 renames a list; Space folds it.
app.codeql.select_variant_item(Item::List(0));
press(&mut app, KeyCode::F(2));
assert_eq!(app.input_prompt.as_ref().unwrap().value, "top");
for _ in 0.."top".len() {
press(&mut app, KeyCode::Backspace);
}
type_in(&mut app, "best");
assert_eq!(saved().lists[0].name, "best", "{}", app.status);
press(&mut app, KeyCode::Char(' '));
assert!(
!app.codeql
.lines()
.iter()
.any(|l| matches!(l, Line::Action(Action::VariantRepo(Some(_), _), _)))
);
assert_eq!(app.codeql.selected_variant_item(), Some(Item::List(0)));
// Delete removes an owner at once and asks before a list.
app.codeql.select_variant_item(Item::Owner(0));
press(&mut app, KeyCode::Delete);
assert!(saved().owners.is_empty(), "{}", app.status);
app.codeql.select_variant_item(Item::List(0));
press(&mut app, KeyCode::Delete);
assert!(
app.input_prompt
.as_ref()
.unwrap()
.title
.contains("and its 1 repository"),
"{}",
app.input_prompt.as_ref().unwrap().title
);
press(&mut app, KeyCode::Esc);
assert_eq!(saved().lists.len(), 1, "Esc keeps it");
press(&mut app, KeyCode::Delete);
press(&mut app, KeyCode::Enter);
assert!(saved().lists.is_empty(), "{}", app.status);
assert!(app.codeql.selected_hit().is_some(), "still on a row");
// A run needs a query open.
app.run_command(Command::CodeqlRunVariantAnalysis);
assert!(app.status.contains("Open a .ql query"), "{}", app.status);
// The config file opens in a tab.
app.run_command(Command::CodeqlOpenVariantConfig);
assert_eq!(
app.editor.path.as_deref(),
Some(App::codeql_variant_path().as_path())
);
// A corrupt file is reported and never saved over.
std::fs::write(App::codeql_variant_path(), "{ broken").unwrap();
app.run_command(Command::CodeqlAddVariantList);
type_in(&mut app, "x");
assert!(app.status.contains("unchanged"), "{}", app.status);
assert_eq!(
std::fs::read_to_string(App::codeql_variant_path()).unwrap(),
"{ broken"
);
app.open_codeql_view();
assert!(app.codeql.variant_error);
assert_eq!(
Command::from_id("codeql_set_up_controller_repository"),
Some(Command::CodeqlSetUpController)
);
});
}
#[test]
fn codeql_run_variant_analysis_bundles_the_query_and_posts_it_to_the_controller() {
// #578: VS Code's "CodeQL: Run Variant Analysis". The open query is
// bundled with its pack (default suite pointed at it) and posted with
// gh to the controller, against what the side bar selects.
use crate::codeql_submit::load_submitted;
use crate::codeql_variant::{Item, VariantConfig};
use crate::widgets::command_palette::Command;
use base64::Engine;
use std::os::unix::fs::PermissionsExt;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let ws = tmp.path().join("ws");
let pack = ws.join("mypack");
std::fs::create_dir_all(pack.join("src")).unwrap();
std::fs::write(
pack.join("qlpack.yml"),
"name: me/q\nversion: 0.0.1\ndependencies:\n codeql/python-all: \"*\"\ndefaultSuite:\n - queries: .\n",
)
.unwrap();
std::fs::write(pack.join("src/Lib.qll"), "predicate p() { any() }").unwrap();
let query = pack.join("src/Find.ql");
std::fs::write(&query, "import python\nselect 1").unwrap();
// `codeql pack bundle` writes the pack file and its file list as the
// "archive", so the test can read what was bundled.
let log = tmp.path().join("log");
let stub = |name: &str, body: String| {
let path = tmp.path().join(name);
std::fs::write(&path, body).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
};
let codeql = stub(
"codeql",
format!(
r#"#!/bin/sh
echo "codeql $*" >> '{log}'
case "$1 $2" in
"pack install") exit 0 ;;
"pack bundle") out="${{3#--output=}}"; dir="$5"
{{ cat "$dir/qlpack.yml"; (cd "$dir" && find . -type f | sort); }} > "$out" ;;
esac
"#,
log = log.display()
),
);
let body = tmp.path().join("body.json");
let gh = stub(
"gh",
format!(
r#"#!/bin/sh
echo "gh $*" >> '{log}'
case "$2" in
*/variant-analyses/4242)
# The first read finds the run going, every later one finished.
if [ -e '{polls}' ]; then
echo '{{"status": "succeeded", "scanned_repositories": [{{"repository": {{"full_name": "a/b"}}, "analysis_status": "succeeded", "result_count": 3}}, {{"repository": {{"full_name": "c/d"}}, "analysis_status": "succeeded", "result_count": 2}}]}}'
else
touch '{polls}'
echo '{{"status": "in_progress", "scanned_repositories": [{{"repository": {{"full_name": "a/b"}}, "analysis_status": "succeeded", "result_count": 3}}, {{"repository": {{"full_name": "c/d"}}, "analysis_status": "in_progress"}}]}}'
fi
exit 0 ;;
esac
while [ $# -gt 0 ]; do [ "$1" = --input ] && cp "$2" '{body}'; shift; done
echo '{{"id": 4242, "actions_workflow_run_id": 99, "skipped_repositories": {{"no_codeql_db_repos": {{"repository_count": 1}}}}}}'
"#,
log = log.display(),
body = body.display(),
polls = tmp.path().join("polled").display()
),
);
let mut app = App::new(ws.clone()).unwrap();
app.gh_program = gh;
app.set_codeql_program(codeql);
let finish = |app: &mut App| {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while !app.drain_codeql_variant_submit() {
assert!(
std::time::Instant::now() < deadline,
"the submission never finished"
);
std::thread::sleep(std::time::Duration::from_millis(10));
}
};
app.editor.open(&query).unwrap();
app.run_command(Command::CodeqlRunVariantAnalysis);
assert!(
app.status.contains("controller repository"),
"{}",
app.status
);
let mut config = VariantConfig::default();
config.set_controller("me/ctl").unwrap();
config.add_list("top").unwrap();
config.add_repo(Some(0), "a/b").unwrap();
config.add_repo(Some(0), "c/d").unwrap();
config.save(&App::codeql_variant_path()).unwrap();
app.run_command(Command::CodeqlRunVariantAnalysis);
assert!(
app.status.contains("Select a repository list"),
"{}",
app.status
);
config.select(Item::List(0)).unwrap();
config.save(&App::codeql_variant_path()).unwrap();
app.run_command(Command::CodeqlRunVariantAnalysis);
assert!(
app.status
.contains("Submitting Find.ql as a variant analysis against 2 repositories"),
"{}",
app.status
);
finish(&mut app);
assert_eq!(
app.status,
"Variant analysis 4242 of Find.ql submitted, 1 repository skipped: https://github.com/me/ctl/actions/runs/99"
);
let asked = std::fs::read_to_string(&log).unwrap();
assert!(asked.contains("codeql pack install"), "{asked}");
assert!(
asked.contains(
"gh api --method POST repos/me/ctl/code-scanning/codeql/variant-analyses --input"
),
"{asked}"
);
let sent: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&body).unwrap()).unwrap();
assert_eq!(sent["language"], "python", "from the pack's dependency");
assert_eq!(sent["repositories"], serde_json::json!(["a/b", "c/d"]));
let bundled = base64::engine::general_purpose::STANDARD
.decode(sent["query_pack"].as_str().unwrap())
.unwrap();
let bundled = String::from_utf8(bundled).unwrap();
assert!(
bundled.contains("defaultSuite:\n - query: \"src/Find.ql\"\n"),
"{bundled}"
);
assert!(
!bundled.contains("queries: ."),
"the pack's own suite is replaced: {bundled}"
);
assert!(bundled.contains("./src/Lib.qll"), "{bundled}");
let runs = load_submitted(&App::codeql_variant_runs_path());
assert_eq!(runs.len(), 1);
assert_eq!((runs[0].id, runs[0].controller.as_str()), (4242, "me/ctl"));
assert!(
!croft_cache_dir()
.join("codeql/variant")
.read_dir()
.is_ok_and(|mut d| d.next().is_some()),
"the work folder is cleaned up"
);
// The run shows in the side bar and is followed until it finishes.
assert_eq!(app.codeql.variant_runs, ["Find.ql · submitted"]);
let poll = |app: &mut App| {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
app.poll_codeql_variant_runs();
assert!(app.codeql_variant_poll.is_some(), "a read started");
while !app.poll_codeql_variant_runs() {
assert!(
std::time::Instant::now() < deadline,
"the read never finished"
);
std::thread::sleep(std::time::Duration::from_millis(10));
}
};
poll(&mut app);
assert_eq!(
app.codeql.variant_runs,
["Find.ql · running · 1/2 repos · 3 results"]
);
app.poll_codeql_variant_runs();
assert!(
app.codeql_variant_poll.is_none(),
"not again before the interval"
);
app.codeql_variant_polled = None;
poll(&mut app);
assert_eq!(
app.status,
"Variant analysis 4242 of Find.ql succeeded: 2/2 repositories, 5 results"
);
assert_eq!(
app.codeql.variant_runs,
["Find.ql · succeeded · 2/2 repos · 5 results"]
);
let reads = |log: &std::path::Path| {
std::fs::read_to_string(log)
.unwrap()
.lines()
.filter(|l| l.ends_with("variant-analyses/4242"))
.count()
};
assert_eq!(reads(&log), 2);
app.codeql_variant_polled = None;
app.poll_codeql_variant_runs();
assert!(
app.codeql_variant_poll.is_none(),
"a finished run is not read"
);
assert_eq!(reads(&log), 2);
// Enter on the run's row opens its report.
app.open_codeql_view();
app.codeql
.select_action(crate::widgets::codeql::Action::VariantRun(0));
app.focus = Pane::Tree;
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
let report = app.editor.lines.join("\n");
assert!(
report.starts_with("# Variant analysis 4242 of Find.ql"),
"{report}"
);
assert!(
report.contains("| [c/d](https://github.com/c/d) | succeeded | 2 | |"),
"{report}"
);
// An unsaved query is not sent as its last saved version.
app.editor.open(&query).unwrap();
app.editor.dirty = true;
app.run_command(Command::CodeqlRunVariantAnalysis);
assert!(app.status.contains("Save the query"), "{}", app.status);
});
}
#[test]
fn codeql_variant_results_are_fetched_once_and_opened_per_repository() {
// #578: a finished variant analysis's results. Each repository with
// results has its artifact downloaded (once), its alerts gathered into
// one SARIF log with a run per repository, its tables into one CSV.
use crate::codeql_submit::{parse_progress, parse_submission, record_submitted};
use crate::widgets::command_palette::Command;
use std::io::{BufRead, Write};
use std::os::unix::fs::PermissionsExt;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let zip_of = |name: &str, body: &str| {
let mut out = std::io::Cursor::new(Vec::new());
let mut z = zip::ZipWriter::new(&mut out);
let opts = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Stored);
z.start_file(name, opts).unwrap();
z.write_all(body.as_bytes()).unwrap();
z.finish().unwrap();
out.into_inner()
};
let sarif = r#"{"version": "2.1.0", "runs": [{"tool": {"driver": {"name": "CodeQL"}}, "results": [{"ruleId": "r", "message": {"text": "found it"}, "locations": [{"physicalLocation": {"artifactLocation": {"uri": "src/x.py"}, "region": {"startLine": 4}}}]}]}]}"#;
let files = std::sync::Arc::new(vec![
("/ab.zip", zip_of("results/results.sarif", sarif)),
("/cd.zip", zip_of("results.bqrs", "binary")),
]);
let served = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
{
let (files, served) = (files.clone(), served.clone());
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
let mut reader = std::io::BufReader::new(stream.try_clone().unwrap());
let mut line = String::new();
reader.read_line(&mut line).unwrap();
let path = line.split_whitespace().nth(1).unwrap_or("").to_string();
loop {
let mut h = String::new();
if reader.read_line(&mut h).unwrap_or(0) == 0 || h == "\r\n" {
break;
}
}
served.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let body = files
.iter()
.find(|(p, _)| *p == path)
.map(|(_, b)| b.clone());
let mut stream = stream;
match body {
Some(b) => {
let _ = write!(
stream,
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
b.len()
);
let _ = stream.write_all(&b);
}
None => {
let _ = write!(
stream,
"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
);
}
}
}
});
}
let log = tmp.path().join("log");
let stub = |name: &str, body: String| {
let path = tmp.path().join(name);
std::fs::write(&path, body).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
};
let gh = stub(
"gh",
format!(
r#"#!/bin/sh
echo "gh $*" >> '{log}'
case "$2" in
*/repos/a/b) echo '{{"analysis_status": "succeeded", "artifact_url": "http://127.0.0.1:{port}/ab.zip", "database_commit_sha": "abc"}}' ;;
*/repos/c/d) echo '{{"analysis_status": "succeeded", "artifact_url": "http://127.0.0.1:{port}/cd.zip"}}' ;;
create) echo "- Creating gist"; echo "https://gist.github.com/me/0123" ;;
*) echo 'HTTP 404: Not Found' >&2; exit 1 ;;
esac
"#,
log = log.display()
),
);
let codeql = stub(
"codeql",
format!(
r#"#!/bin/sh
echo "codeql $*" >> '{log}'
out="${{4#--output=}}"; printf '"name","count"\n"x","1"\n' > "$out"
"#,
log = log.display()
),
);
let mut run = parse_submission(
r#"{"id": 9}"#,
"me/ctl",
std::path::Path::new("/w/Find.ql"),
"python",
0,
)
.unwrap();
run.progress = parse_progress(
r#"{"status": "succeeded", "scanned_repositories": [
{"repository": {"full_name": "a/b"}, "analysis_status": "succeeded", "result_count": 1},
{"repository": {"full_name": "c/d"}, "analysis_status": "succeeded", "result_count": 1},
{"repository": {"full_name": "e/f"}, "analysis_status": "succeeded", "result_count": 4},
{"repository": {"full_name": "g/h"}, "analysis_status": "succeeded", "result_count": 0}]}"#,
)
.ok();
record_submitted(&App::codeql_variant_runs_path(), run).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.gh_program = gh;
app.set_codeql_program(codeql);
let finish = |app: &mut App| {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while !app.drain_codeql_variant_results() {
assert!(
std::time::Instant::now() < deadline,
"the fetch never finished"
);
std::thread::sleep(std::time::Duration::from_millis(10));
}
};
app.run_command(Command::CodeqlOpenVariantResults);
assert!(
app.status
.starts_with("Fetching the results of 3 repositories"),
"{}",
app.status
);
finish(&mut app);
let dir = croft_cache_dir().join("codeql/variant-results/me-ctl-9");
assert!(
app.status
.starts_with("Results of 2 repositories; tables in "),
"{}",
app.status
);
assert!(
app.status.ends_with("; e/f failed: HTTP 404: Not Found"),
"{}",
app.status
);
assert_eq!(
app.editor.path.as_deref(),
Some(dir.join("results.sarif").as_path())
);
assert_eq!(
std::fs::read_to_string(dir.join("results.csv")).unwrap(),
"\"repository\",\"name\",\"count\"\n\"c/d\",\"x\",\"1\"\n"
);
assert_eq!(served.load(std::sync::atomic::Ordering::SeqCst), 2);
// A location in another repository opens on GitHub at its commit.
let view = app.editor.sarif.as_mut().expect("the SARIF viewer is open");
assert_eq!(view.entries.len(), 1);
view.selected = view
.rows()
.iter()
.position(|r| matches!(r, crate::sarif::view::Row::Item { .. }))
.unwrap();
app.open_sarif_loc(&crate::sarif::details::LocRef {
label: "src/x.py".into(),
uri: "src/x.py".into(),
line: 4,
column: 1,
..Default::default()
});
assert_eq!(
app.status,
"Open https://github.com/a/b/blob/abc/src/x.py#L4"
);
// Opening again uses the downloaded copies.
let gh_calls = std::fs::read_to_string(&log)
.unwrap()
.matches("gh api")
.count();
app.run_command(Command::CodeqlOpenVariantResults);
finish(&mut app);
assert_eq!(
served.load(std::sync::atomic::Ordering::SeqCst),
2,
"nothing downloaded twice"
);
let again = std::fs::read_to_string(&log)
.unwrap()
.matches("gh api")
.count();
assert_eq!(
again,
gh_calls + 1,
"only the failed repository is asked again"
);
// Export: Markdown into a folder, offered in the workspace.
app.run_command(Command::CodeqlExportVariantResults);
let offered = tmp.path().join("codeql-variant-analysis-9");
assert_eq!(
app.input_prompt.as_ref().map(|p| p.value.clone()),
Some(offered.display().to_string())
);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
let export = |app: &mut App| {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while !app.drain_codeql_variant_export() {
assert!(
std::time::Instant::now() < deadline,
"the export never finished"
);
std::thread::sleep(std::time::Duration::from_millis(10));
}
};
export(&mut app);
assert!(
app.status
.starts_with(&format!("Exported 2 repositories to {}", offered.display())),
"{}",
app.status
);
assert_eq!(
app.editor.path.as_deref(),
Some(offered.join("_summary.md").as_path())
);
let summary = std::fs::read_to_string(offered.join("_summary.md")).unwrap();
assert!(summary.contains("| [a/b](a-b.md) | 1 |"), "{summary}");
assert!(summary.contains("| [c/d](c-d.md) | 1 |"), "{summary}");
let ab = std::fs::read_to_string(offered.join("a-b.md")).unwrap();
assert!(
ab.contains("- found it ([src/x.py:4](https://github.com/a/b/blob/abc/src/x.py#L4))"),
"{ab}"
);
assert!(
std::fs::read_to_string(offered.join("c-d.md"))
.unwrap()
.contains("| x | 1 |")
);
assert_eq!(
served.load(std::sync::atomic::Ordering::SeqCst),
2,
"export reuses the downloads"
);
// Or a secret gist, `_summary.md` first.
app.run_command(Command::CodeqlExportVariantResults);
if let Some(p) = app.input_prompt.as_mut() {
p.value = String::from("gist");
}
let _ = std::fs::write(&log, "");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
export(&mut app);
assert!(
app.status
.starts_with("Exported 2 repositories to https://gist.github.com/me/0123"),
"{}",
app.status
);
let asked = std::fs::read_to_string(&log).unwrap();
let gist = asked
.lines()
.find(|l| l.starts_with("gh gist create"))
.unwrap_or_default();
assert!(
gist.contains("--desc Find.ql (variant analysis 9 of 2 repositories)"),
"{gist}"
);
let first_file = gist
.split_whitespace()
.find(|w| w.ends_with(".md"))
.unwrap_or_default();
assert!(first_file.ends_with("/_summary.md"), "{gist}");
});
}
#[test]
fn codeql_code_search_adds_the_repositories_it_finds_to_the_selected_list() {
// #578: VS Code's "Add repositories with GitHub Code Search". The search
// runs off the UI thread, page by page, scoped to the side bar's
// language, and its distinct repositories join the selected list.
use crate::codeql_variant::{Item, VariantConfig};
use crate::widgets::command_palette::Command;
use std::os::unix::fs::PermissionsExt;
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let log = tmp.path().join("gh-args");
let gh = tmp.path().join("gh");
// Page 1 is full (100 results over 60 repositories, one already
// listed in another case); page 2 is short, so page 3 is never
// asked for. A query with "broken" in it fails; one with "cut"
// fills page 1 and then hits the rate limit.
std::fs::write(
&gh,
format!(
r#"#!/bin/sh
echo "$@" >> '{log}'
case "$*" in
*broken*) echo 'gh: Validation Failed (HTTP 422)' >&2; exit 1 ;;
*cut*" page=1 "*) i=0; while [ $i -lt 100 ]; do echo "c/r$i"; i=$((i+1)); done ;;
*cut*) echo 'API rate limit exceeded' >&2; exit 1 ;;
*" page=1 "*) i=0; while [ $i -lt 100 ]; do echo "o/r$((i % 60))"; i=$((i+1)); done; echo "A/B" ;;
*" page=2 "*) echo o/extra ;;
*) echo "asked for a page past the short one" >&2; exit 1 ;;
esac
"#,
log = log.display()
),
)
.unwrap();
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.gh_program = gh.clone();
app.open_codeql_view();
app.focus = Pane::Tree;
let press = |app: &mut App, code: KeyCode| {
app.handle_key(key(code, KeyModifiers::NONE)).unwrap();
};
let type_in = |app: &mut App, text: &str| {
for c in text.chars() {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
};
let finish = |app: &mut App| {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while !app.drain_codeql_code_search() {
assert!(
std::time::Instant::now() < deadline,
"the search never finished"
);
std::thread::sleep(std::time::Duration::from_millis(10));
}
};
let saved = || VariantConfig::load(&App::codeql_variant_path()).unwrap();
// With no list selected there is nowhere to put the results.
app.run_command(Command::CodeqlVariantCodeSearch);
assert!(app.input_prompt.is_none());
assert!(
app.status.contains("Select a repository list"),
"{}",
app.status
);
app.codeql
.select_action(crate::widgets::codeql::Action::SetUpControllerRepository);
press(&mut app, KeyCode::Char('l'));
type_in(&mut app, "found");
press(&mut app, KeyCode::Char('a'));
type_in(&mut app, "a/b");
// The language first: it filters rows, which moves the selection.
app.codeql.language = crate::widgets::codeql::LANGUAGE_IDS
.iter()
.position(|l| *l == "python");
app.codeql.select_variant_item(Item::List(0));
press(&mut app, KeyCode::Char('s'));
assert_eq!(
app.input_prompt.as_ref().unwrap().title,
"Add Repositories to found with GitHub Code Search"
);
type_in(&mut app, "import torch");
assert!(
app.status.starts_with("Searching GitHub code"),
"{}",
app.status
);
finish(&mut app);
let repos = saved().lists[0].repos.clone();
assert_eq!(repos.len(), 1 + 60 + 1, "{repos:?}");
assert_eq!(repos[..2], ["a/b", "o/r0"]);
assert_eq!(repos.last().map(String::as_str), Some("o/extra"));
assert_eq!(
app.status, "Added 61 repositories to found (1 already there)",
"{}",
app.status
);
let asked = std::fs::read_to_string(&log).unwrap();
assert_eq!(asked.lines().count(), 2, "stops at the short page: {asked}");
assert!(asked.contains("q=import torch language:python"), "{asked}");
// A failed search says why and changes nothing.
app.codeql.select_variant_item(Item::List(0));
app.run_command(Command::CodeqlVariantCodeSearch);
type_in(&mut app, "broken");
finish(&mut app);
assert!(
app.status.contains("GitHub Code Search failed"),
"{}",
app.status
);
assert!(app.status.contains("Validation Failed"), "{}", app.status);
assert_eq!(saved().lists[0].repos, repos);
// A later page failing keeps the earlier pages and says so.
app.codeql.select_variant_item(Item::List(0));
app.run_command(Command::CodeqlVariantCodeSearch);
type_in(&mut app, "cut");
finish(&mut app);
assert_eq!(saved().lists[0].repos.len(), repos.len() + 100);
assert!(
app.status.starts_with("Added 100 repositories to found; the search stopped early, page 2 failed: API rate limit exceeded"),
"{}",
app.status
);
});
}
/// A recorded row's width as a player draws it: its characters with the
/// SGR and cursor escapes (#356) taken out, since those occupy no column.
fn visible_width(row: &str) -> usize {
crate::remote_connect::strip_ansi(row.as_bytes())
.chars()
.count()
}
/// The output frames of the one cast `app` wrote into its workspace.
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()
}
/// #356: a recorded frame keeps the colours the pane showed, as SGR per
/// run, and ends by putting the player's cursor where the pane's was, or
/// hiding it, so each frame sets the cursor state rather than inheriting it.
#[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].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 shown = frame.rsplit_once('\u{1b}').map(|(_, tail)| tail);
assert!(
matches!(shown, Some("[?25h" | "[?25l")),
"the frame ends by setting the cursor: {frame:?}"
);
if shown == Some("[?25h") {
let (row, col) = app.terminals[0].screen_ansi_wrapped().1.unwrap();
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");
}
/// #356: a row a redact rule touches is written as its masked text and
/// gives up its colour, since a mask spliced between escapes could break
/// them; the rows around it keep theirs.
#[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:?}"
);
}
/// #377, as a user takes it: `croft demo`, then Enter and nothing else.
/// Every popup a step opens takes its own Enter, and that Enter must do the
/// harmless thing the caption says (open app.py, open the theme picker,
/// keep the theme), never whatever sorts first (the marker file, or Move
/// Line Up into the sample). The tour then ends with the sample's files as
/// they were created, and no tab left naming a deleted file.
#[test]
fn the_whole_tour_takes_enter_only_and_leaves_nothing_behind() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.start_demo();
let scratch = app.workspace_root().to_path_buf();
let mut opened = Vec::new();
let mut presses = 0;
let mut saw_theme_picker = false;
while app.tour.is_some() && presses < 30 {
if let Some(step) = app.tour.as_ref().and_then(|r| r.tour.current()) {
// The sample, as created, at every step: nothing typed into it.
for (rel, text) in crate::tour::sample_files() {
if let Ok(on_disk) = std::fs::read_to_string(scratch.join(rel)) {
assert_eq!(on_disk, text, "{rel} at {:?}", step.action);
}
}
}
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
presses += 1;
saw_theme_picker |= app.context_menu.is_some();
if let Some(path) = app.editor.path.clone()
&& !opened.contains(&path)
{
opened.push(path);
}
let dirty: Vec<_> = std::iter::once(&app.editor)
.chain(app.editor_layout.inactive_groups())
.flat_map(|g| g.editors.iter())
.filter(|e| e.dirty)
.filter_map(|e| e.path.clone())
.collect();
assert!(dirty.is_empty(), "Enter #{presses} edited {dirty:?}");
}
assert!(app.tour.is_none(), "Enter alone finishes the tour");
assert!(presses <= 12, "{presses} presses for an 8-step tour");
assert!(
app.context_menu.is_none() && app.command_palette.is_none(),
"no picker the tour opened outlives it"
);
assert!(
saw_theme_picker,
"the palette's Enter opened the theme picker, and Enter closed it"
);
assert!(
opened.contains(&scratch.join("app.py")),
"Quick Open's Enter opened app.py: {opened:?}"
);
assert!(
!opened.contains(&scratch.join(crate::tour::SCRATCH_MARKER)),
"never the marker file: {opened:?}"
);
assert!(!scratch.exists(), "the sample project is gone");
assert_eq!(app.workspace_root(), tmp.path());
let left: Vec<_> = std::iter::once(&app.editor)
.chain(app.editor_layout.inactive_groups())
.flat_map(|g| g.editors.iter())
.filter_map(|e| e.path.clone())
.filter(|p| p.starts_with(&scratch))
.collect();
assert!(left.is_empty(), "tabs naming the deleted sample: {left:?}");
});
}
/// #377: Esc mid-tour closes the sample's tabs too, an edited one
/// included, so no save can write a scratch file back.
#[test]
fn leaving_the_tour_closes_the_samples_tabs_even_edited_ones() {
let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
let home = tempfile::tempdir().unwrap();
with_relay_home(home.path(), || {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.start_demo();
let scratch = app.workspace_root().to_path_buf();
app.focus_pane(Pane::Editor);
app.editor.insert_char('x');
assert!(app.editor.dirty);
app.split_editor();
app.close_all_modals_for_test();
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert!(app.tour.is_none());
assert!(!scratch.exists());
let left: Vec<_> = std::iter::once(&app.editor)
.chain(app.editor_layout.inactive_groups())
.flat_map(|g| g.editors.iter())
.filter_map(|e| e.path.clone())
.filter(|p| p.starts_with(&scratch))
.collect();
assert!(left.is_empty(), "tabs naming the deleted sample: {left:?}");
});
}
/// #356: a run of one colour stays one SGR run across the soft-wrap column
/// and across a wide character. Both carry cell flags that are layout, not
/// style, and keyed on those the run was reset and set again around them.
#[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:?}"
);
}
/// Pick the launch.json configuration `label` in the Run and Debug picker,
/// which starts it, as the user's click does.
fn start_debug_config(app: &mut App, label: &str) {
app.open_debug_config_picker();
let idx = app
.list_picker
.as_ref()
.expect("picker open")
.rows
.iter()
.position(|r| r.label.starts_with(label))
.unwrap_or_else(|| panic!("{label} is listed"));
app.list_picker.as_mut().unwrap().selected = idx;
app.confirm_list_picker();
}
/// Drive the app's debug machinery (the preLaunchTask pane and the adapter)
/// until the focused session is stopped with `local` loaded, or `secs` pass.
fn debug_until_local(app: &mut App, local: &str, secs: u64) -> Option<String> {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(secs);
while std::time::Instant::now() < deadline {
app.drain_terminal_bells();
app.poll_dap();
if let Some(v) = app
.debug_sessions
.focused()
.and_then(|s| s.lookup_local(local))
{
return Some(v.value.clone());
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
None
}
/// #250, against a real debugpy: a VS Code launch.json config with `args`
/// and an `envFile` launches the program with both, so a breakpoint after
/// they are read sees their values. Needs `~/.croft/debug-venv`.
#[test]
#[ignore = "requires ~/.croft/debug-venv (uv + debugpy)"]
fn a_launch_json_python_config_passes_args_and_env_file() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::write(
root.join("app.py"),
"import os, sys\nwho = sys.argv[1]\ngreeting = os.environ[\"GREETING\"]\nprint(f\"{greeting}, {who}\")\n",
)
.unwrap();
std::fs::write(root.join(".env"), "GREETING=hi from envFile\n").unwrap();
std::fs::create_dir_all(root.join(".vscode")).unwrap();
std::fs::write(
root.join(".vscode/launch.json"),
r#"{ "version": "0.2.0", "configurations": [
// Written for VS Code: comments, and keys croft does not map.
{ "name": "Py", "type": "debugpy", "request": "launch",
"program": "${workspaceFolder}/app.py", "args": ["croft"],
"envFile": "${workspaceFolder}/.env", "console": "integratedTerminal",
"justMyCode": true }
]}"#,
)
.unwrap();
let mut app = App::new(root.clone()).unwrap();
app.editor
.breakpoints
.entry(root.join("app.py"))
.or_default()
.insert(4);
start_debug_config(&mut app, "Py");
let greeting = debug_until_local(&mut app, "greeting", 90);
let who = app
.debug_sessions
.focused()
.and_then(|s| s.lookup_local("who"))
.map(|v| v.value.clone());
app.debug_stop();
assert_eq!(
greeting.as_deref(),
Some("'hi from envFile'"),
"status {:?}, feedback {:?}",
app.status,
app.run_debug.feedback
);
assert_eq!(who.as_deref(), Some("'croft'"));
}
/// #250, against a real lldb-dap: a Rust binary that needs a CLI argument
/// and an env var is debugged from a config whose `cargo build`
/// preLaunchTask builds it first. Needs cargo and lldb-dap.
#[test]
#[ignore = "requires cargo and lldb-dap"]
fn a_launch_json_rust_config_builds_first_and_passes_args_and_env() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(
root.join("Cargo.toml"),
"[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n",
)
.unwrap();
std::fs::write(
root.join("src/main.rs"),
"fn main() {\n let n: i32 = std::env::args().nth(1).unwrap().parse().unwrap();\n \
let k: i32 = std::env::var(\"K\").unwrap().parse().unwrap();\n \
println!(\"{}\", n + k);\n}\n",
)
.unwrap();
std::fs::create_dir_all(root.join(".vscode")).unwrap();
std::fs::write(
root.join(".vscode/tasks.json"),
r#"{ "version": "2.0.0", "tasks": [
{ "label": "cargo build", "type": "shell", "command": "cargo build" }
]}"#,
)
.unwrap();
std::fs::write(
root.join(".vscode/launch.json"),
r#"{ "configurations": [
{ "name": "Rs", "type": "lldb", "request": "launch",
"program": "${workspaceFolder}/target/debug/t", "args": ["35"],
"env": { "K": "7" }, "cwd": "${workspaceFolder}",
"preLaunchTask": "cargo build", "sourceLanguages": ["rust"] }
]}"#,
)
.unwrap();
let mut app = App::new(root.clone()).unwrap();
app.editor
.breakpoints
.entry(root.join("src/main.rs"))
.or_default()
.insert(4);
start_debug_config(&mut app, "Rs");
assert!(
app.pending_debug_launch.is_some(),
"the launch waits for the build: {}",
app.status
);
let k = debug_until_local(&mut app, "k", 240);
let n = app
.debug_sessions
.focused()
.and_then(|s| s.lookup_local("n"))
.map(|v| v.value.clone());
app.debug_stop();
assert!(
root.join("target/debug/t").is_file(),
"the preLaunchTask built the binary"
);
assert_eq!(
k.as_deref(),
Some("7"),
"status {:?}, feedback {:?}",
app.status,
app.run_debug.feedback
);
assert_eq!(n.as_deref(), Some("35"));
}
/// #250, against a real vscode-js-debug: a `request: attach` config with a
/// `port` attaches to a running Node server and stops at a breakpoint in
/// it. Needs node and `~/.croft/js-debug`.
#[test]
#[ignore = "requires node and ~/.croft/js-debug"]
fn a_launch_json_node_attach_config_attaches_by_port() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::write(
root.join("server.js"),
"let n = 0;\nsetInterval(() => {\n n += 1;\n const label = `tick ${n}`;\n if (label === '') console.log(label);\n}, 100);\n",
)
.unwrap();
let port = std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
let mut node = std::process::Command::new("node")
.arg(format!("--inspect=127.0.0.1:{port}"))
.arg(root.join("server.js"))
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.expect("node runs");
std::fs::create_dir_all(root.join(".vscode")).unwrap();
std::fs::write(
root.join(".vscode/launch.json"),
format!(
r#"{{ "configurations": [
{{ "name": "Attach", "type": "node", "request": "attach",
"port": {port}, "skipFiles": ["<node_internals>/**"] }}
]}}"#
),
)
.unwrap();
std::thread::sleep(std::time::Duration::from_millis(500));
let mut app = App::new(root.clone()).unwrap();
app.editor
.breakpoints
.entry(root.join("server.js"))
.or_default()
.insert(5);
start_debug_config(&mut app, "Attach");
let label = debug_until_local(&mut app, "label", 90);
app.debug_stop();
let _ = node.kill();
let _ = node.wait();
let label = label.unwrap_or_else(|| {
panic!(
"no stop: status {:?}, feedback {:?}",
app.status, app.run_debug.feedback
)
});
assert!(label.contains("tick "), "{label}");
}
/// #263: the open file rewritten on disk under a clean buffer dims its
/// coverage marks, as an edit in the buffer does: they describe old text.
#[test]
fn an_external_rewrite_of_the_open_file_dims_its_coverage() {
use crate::testing::coverage::Coverage;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let file = root.join("f.rs");
std::fs::write(&file, "fn a() {}\nfn b() {}\n").unwrap();
let mut app = App::new(root.clone()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.testing.on_coverage(Ok(Coverage::from_lcov(
"SF:f.rs\nDA:1,3\nDA:2,0\nend_of_record\n",
&root,
)));
assert!(app.sync_coverage());
assert!(!app.editor.coverage.as_ref().unwrap().stale);
std::thread::sleep(std::time::Duration::from_millis(20));
std::fs::write(&file, "fn b() {}\n\nfn a() {}\n").unwrap();
assert!(app.reload_open_file_after_external_change());
app.sync_coverage();
assert!(
app.editor.coverage.as_ref().unwrap().stale,
"the reloaded file's marks are stale"
);
}
/// #263: a watched scope reruns on a source save, but not on a save of a
/// file git ignores (build output, a `.env`).
#[test]
fn a_save_of_an_ignored_file_does_not_rerun_watched_tests() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let git = |args: &[&str]| {
std::process::Command::new("git")
.arg("-C")
.arg(&root)
.args(args)
.output()
.unwrap()
};
git(&["init", "-q", "-b", "main"]);
std::fs::write(root.join(".gitignore"), "*.log\nout/\n").unwrap();
std::fs::create_dir_all(root.join("out")).unwrap();
let mut app = App::new(root.clone()).unwrap();
app.active_test_root = root.clone();
app.testing
.watch
.toggle(crate::testing::watch::WatchScope::All);
let later = std::time::Instant::now() + std::time::Duration::from_secs(5);
for ignored in ["run.log", "out/gen.rs"] {
app.record_history_snapshot_of(&root.join(ignored), Default::default(), None);
assert_eq!(
app.testing.watch.take_due(later, false),
None,
"{ignored} is ignored"
);
}
app.record_history_snapshot_of(&root.join("lib.rs"), Default::default(), None);
assert_eq!(
app.testing.watch.take_due(later, false),
Some(crate::testing::watch::WatchScope::All),
"a source save reruns"
);
}
/// #263 against a real cargo-llvm-cov: "Run All Tests with Coverage" on a
/// crate marks the lines its test ran green and a function no test calls
/// red, with a percentage between. Needs `cargo llvm-cov` (and the
/// `llvm-tools-preview` component it drives).
#[test]
#[ignore = "needs cargo-llvm-cov"]
fn a_real_cargo_llvm_cov_run_marks_the_covered_file() {
use crate::testing::coverage::LineCov;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(
root.join("Cargo.toml"),
"[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n",
)
.unwrap();
std::fs::write(
root.join("src/lib.rs"),
// Two literals, not one continued across a line: a continuation
// line opening with `#[` reads as an attribute to the doc gate's
// line classifier, which then never sees the closing quote.
concat!(
"pub fn add(a: i32, b: i32) -> i32 {\n a + b\n}\n\npub fn unused() -> i32 {\n 0\n}\n\n",
"#[cfg(test)]\nmod tests {\n #[test]\n fn adds() {\n assert_eq!(super::add(1, 2), 3);\n }\n}\n",
),
)
.unwrap();
let mut app = App::new(root.clone()).unwrap();
app.editor.open(&root.join("src/lib.rs")).unwrap();
app.run_all_tests_with_coverage();
let end = std::time::Instant::now() + std::time::Duration::from_secs(300);
while app.editor.coverage.is_none() {
assert!(std::time::Instant::now() < end, "status: {}", app.status);
let _ = app.test_worker.drain(&mut app.testing);
app.sync_coverage();
std::thread::sleep(std::time::Duration::from_millis(100));
}
let lens = app.editor.coverage.clone().unwrap();
assert_eq!(lens.lines.get(&1), Some(&LineCov::Covered), "`a + b` ran");
assert_eq!(
lens.lines.get(&5),
Some(&LineCov::Uncovered),
"`unused`'s body never ran: {:?}",
lens.lines
);
assert!(
lens.percent.is_some_and(|p| p > 0.0 && p < 100.0),
"{:?}",
lens.percent
);
}
/// #262: a `config.synced.json` that arrives by config sync is applied on
/// arrival: it is in the settings chain, so the config watch's reload of it
/// re-runs the merge.
#[test]
fn the_synced_settings_layer_is_in_the_reload_chain() {
let tmp = tempfile::tempdir().unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
let synced = crate::config_layers::synced_config_path();
assert!(
app.settings_chain.contains(&synced),
"{synced:?} in {:?}",
app.settings_chain
);
}