use super::*;
const BACKGROUND_PASS_CALLS: &[&str] = &[
"app.sync_symbol_views",
"app.poll_background_panic",
"app.drain_fs_events",
"crate::startup_trace::mark",
"app.peek_terminals_dirty",
"app.cursor_visible_phase",
"app.update_spinner_phase",
"app.mcp_spinner_phase",
"app.problems_fix_spinner_phase",
"app.drain_ext_index_refresh",
"app.drain_codeql_run",
"app.drain_codeql_ast",
"app.drain_codeql_model",
"app.drain_codeql_doc",
"app.drain_codeql_upgrade",
"app.drain_codeql_version",
"app.drain_codeql_log_summary",
"app.drain_codeql_log_viewer",
"app.drain_codeql_perf_compare",
"app.drain_codeql_query_help",
"app.drain_codeql_pack_job",
"app.drain_codeql_db_job",
"app.drain_codeql_cli_download",
"app.drain_codeql_cli_check",
"app.drain_codeql_code_search",
"app.drain_codeql_variant_submit",
"app.poll_codeql_variant_runs",
"app.drain_codeql_variant_results",
"app.drain_codeql_variant_export",
"app.drain_codeql_queries",
"app.drain_search_results",
"app.poll_log_index",
"app.refresh_remote_if_config_changed",
"app.drain_remote_pulls",
"app.drain_relay_copies",
"app.sync_file_finder_open_lines",
"app.file_finder.as_mut",
"app.drain_view_requests",
"app.drain_hook_requests",
"app.poll_pr_gh",
"app.poll_pr_checkout",
"app.poll_code_scanning",
"crate::startup_trace::mark",
"app.sync_approval_check",
"app.persist_agent_ledger",
"app.poll_notebook_kernels",
"app.drain_ports_and_poll",
"app.poll_session_presence",
"app.poll_session_typing",
"app.poll_collab",
"crate::startup_trace::mark",
"app.sync_symbol_views",
"app.drain_terminal_bells",
"app.settle_block_captures",
"app.publish_block_outputs",
"app.refresh_terminal_labels",
"app.drain_agent_events",
"app.drain_fleet_results",
"app.flush_terminal_session",
"app.tick_auto_save",
"app.tick_hot_exit",
"app.sync_output_panel",
"crate::startup_trace::mark",
"app.poll_highlights",
"app.poll_chrome_bake",
"app.poll_welcome_bake",
"app.poll_saved_session",
"app.poll_pdf_previews",
"app.settle_bookmarks",
"crate::startup_trace::mark",
"app.tick_live_run",
"app.sync_markdown_side_previews",
"app.sync_markdown_scroll",
"app.tick_minimap",
"app.tick_code_lens",
"app.tick_config_watch",
"app.drain_lsp_code_lens",
"app.drain_search_editor",
"app.tick_inline_complete",
"app.drain_review_ops",
"app.poll_connect_dialog",
"app.drain_scrub_views",
"app.poll_install_session",
"app.poll_update_watch",
"app.drain_http_responses",
"app.tick_redaction_reveal",
"crate::startup_trace::mark",
"app.sync_lsp",
"app.send_due_completion_ask",
"app.send_due_completion_reask",
"crate::startup_trace::mark",
"app.sync_markdown_lint",
"app.sync_sarif_diagnostics",
"app.sync_sarif_selection_to_cursor",
"app.sync_sarif_step_marks",
"app.refresh_sarif_preview",
"app.poll_sarif_download",
"app.sync_git_gutters",
"app.sync_blame",
"app.sync_provenance",
"app.drain_blame",
"app.drain_git_net",
"app.drain_git_view",
"app.drain_git_file_lookup",
"crate::startup_trace::mark",
"app.sync_outline",
"app.drain_lsp_document_symbols",
"app.workspace_symbols_dispatch_due",
"app.drain_lsp_workspace_symbols",
"app.sync_explorer_panels",
"crate::startup_trace::mark",
"app.refresh_semantic_tokens_if_requested",
"app.refresh_inlay_hints_if_requested",
"app.refresh_workspace_diagnostics_if_requested",
"app.drain_lsp_completion",
"app.refresh_signature_help_if_moved",
"app.drain_lsp_signature_help",
"app.poll_hover",
"app.drain_lsp_hover",
"app.drain_lsp_rust_analyzer",
"app.drain_blame_hover",
"app.poll_tab_hover",
"app.poll_ui_tooltip",
"app.drain_lsp_definition",
"app.drain_lsp_declaration",
"app.drain_lsp_type_definition",
"app.drain_lsp_implementation",
"app.drain_lsp_references",
"app.drain_lsp_call_hierarchy",
"app.tick_sidebar_auto_hide",
"app.tick_occurrences",
"app.tick_linked_editing",
"app.drain_lsp_linked_editing",
"app.tick_on_type_formatting",
"app.drain_lsp_on_type_format",
"app.drain_lsp_prepare_rename",
"app.drain_lsp_document_highlights",
"app.drain_lsp_rename",
"app.tick_file_moves",
"app.drain_lsp_format",
"app.drain_prettier_format",
"app.drain_lsp_code_actions",
"app.drain_lsp_semantic_tokens",
"app.drain_lsp_inlay_hints",
"app.drain_lsp_document_links",
"app.drain_lsp_folding_ranges",
"app.drain_lsp_selection_ranges",
"app.drain_lsp_document_colors",
"app.drain_lsp_color_presentations",
"app.drain_lsp_diagnostics",
"app.drain_lsp_progress",
"crate::startup_trace::mark",
"app.poll_dap",
"app.poll_debug_build",
"app.poll_debug_setups",
"app.test_worker.drain",
"app.drain_pending_test_debug",
"app.drain_pending_cargo_launch",
"app.say_why_test_runs_ended",
"app.sync_coverage",
"app.tick_test_watch",
"app.testing.take_failed_run",
"app.testing.counts",
"app.notifier.emit",
"app.testing.run_reported_failed",
"app.roots.primary",
"crate::startup_trace::mark",
"app.poll_mcp",
"app.maybe_seat_navigator",
"app.poll_pair",
"app.tick_proactive_navigator",
"crate::startup_trace::mark",
"app.drain_voice",
"app.expire_zen_hint",
"app.expire_cmd_k",
"app.screencast.expire",
"app.poll_zoxide_install",
"crate::lsp::install::take_status",
"crate::lsp::install::take_just_installed",
"app.lsp.last_seen.retain",
];
fn background_pass_calls() -> Vec<String> {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/app/tick.rs");
let text = std::fs::read_to_string(&path)
.unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display()));
let mut calls = Vec::new();
read_pass_calls(&text, "tick_background", &mut calls);
calls
}
fn read_pass_calls(text: &str, name: &str, calls: &mut Vec<String>) {
let signature = format!("fn {name}(");
let start = text
.find(&signature)
.unwrap_or_else(|| panic!("tick.rs defines {name}"));
let open = start
+ text[start..]
.find("{\n")
.unwrap_or_else(|| panic!("{name} has a body"));
let end = open
+ text[open..]
.find("\n}\n")
.unwrap_or_else(|| panic!("{name} ends"));
let body: String = text[open..end]
.lines()
.map(|line| line.split("//").next().unwrap_or(""))
.collect::<Vec<_>>()
.join("\n");
let call = regex::Regex::new(
r"\b(?:app|crate)(?:\s*(?:\.|::)\s*[a-z_][a-z0-9_]*)+\s*\(|\b([a-z_][a-z0-9_]*)\s*\(\s*app\b",
)
.expect("call pattern");
for found in call.captures_iter(&body) {
match found.get(1) {
Some(step) => read_pass_calls(text, step.as_str(), calls),
None => calls.push(
found[0]
.chars()
.filter(|c| !c.is_whitespace() && *c != '(')
.collect(),
),
}
}
}
#[test]
fn the_background_pass_keeps_its_order() {
let expected: Vec<String> = BACKGROUND_PASS_CALLS
.iter()
.map(|c| c.to_string())
.collect();
pretty_assertions::assert_eq!(background_pass_calls(), expected);
}
fn let_startup_land(app: &mut App) {
let started = app.last_label_refresh;
crate::test_budget::await_spawned(
std::time::Duration::from_secs(5),
"startup's background work to land",
|| {
let quiet = !tick_background(app).changed;
quiet
&& !app.fs_watch.installing()
&& app.file_finder_index.is_some()
&& app.last_label_refresh > started
&& app.label_pass.is_none()
},
);
}
#[test]
fn an_idle_background_pass_asks_for_no_redraw() {
let _slot = crash_slot_lock();
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let_startup_land(&mut app);
for pass in 1..=20 {
std::thread::sleep(std::time::Duration::from_millis(8));
assert!(
!tick_background(&mut app).changed,
"idle pass {pass} asked for a redraw"
);
}
}
#[test]
fn a_pass_that_restores_who_typed_each_line_asks_for_a_redraw() {
use crate::provenance::Seat;
let _slot = crash_slot_lock();
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
let other = tmp.path().join("other.txt");
std::fs::write(&f, "one\n").unwrap();
std::fs::write(&other, "two\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.split_editor();
app.editor.open_pinned(&other).unwrap();
assert_eq!(app.editor.path.as_deref(), Some(other.as_path()));
let_startup_land(&mut app);
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();
app.history_done_tx.send(f.clone()).unwrap();
let split_has_marks = |app: &App| {
app.editor_layout.inactive_groups().any(|g| {
g.editors
.iter()
.any(|ed| ed.path.as_deref() == Some(f.as_path()) && ed.provenance == seats)
})
};
let restoring_pass = (1..=3).find_map(|_| {
let changed = tick_background(&mut app).changed;
split_has_marks(&app).then_some(changed)
});
assert_eq!(
restoring_pass,
Some(true),
"the pass that restored the split's marks asks for a redraw"
);
}
mod budget {
pub(super) const IDLE_PASS: u64 = 0;
pub(super) const IDLE_PASS_WITH_FILE: u64 = 0;
pub(super) const FRAME_WELCOME: u64 = 13;
pub(super) const FRAME_WITH_FILE: u64 = 45;
}
fn within_budget(what: &str, made: u64, budget: u64) -> Option<String> {
let slack = (budget / 50).max(2);
if made > budget {
Some(format!(
"{what} made {made} allocations, over its budget of {budget}: find the new allocation, \
or raise the budget in `budget` with the reason"
))
} else if made + slack < budget {
Some(format!(
"{what} made {made} allocations, under its budget of {budget}: lower the budget in `budget` to {made}"
))
} else {
None
}
}
fn fewest_allocations(runs: usize, mut f: impl FnMut()) -> u64 {
(0..runs)
.map(|_| crate::alloc_count::allocations_in(&mut f).1)
.min()
.unwrap_or(0)
}
fn most_allocations(runs: usize, mut f: impl FnMut()) -> u64 {
(0..runs)
.map(|_| crate::alloc_count::allocations_in(&mut f).1)
.max()
.unwrap_or(0)
}
#[test]
fn the_idle_loop_and_a_frame_keep_to_their_allocation_budgets() {
let _slot = crash_slot_lock();
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("budget.rs");
let text: String = (0..2000)
.map(|i| format!("fn f{i}(x: u32) -> u32 {{ x + {i} }} // line {i}\n"))
.collect();
std::fs::write(&file, text).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.welcome.set_test_notes(vec![
crate::release_notes::ReleaseNote {
kind: crate::release_notes::NoteKind::Feature,
summary: "Allocation budgets hold **every frame** to a count",
},
crate::release_notes::ReleaseNote {
kind: crate::release_notes::NoteKind::Fix,
summary: "An idle pass makes `no` allocations",
},
]);
let_startup_land(&mut app);
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from("sleep 600")],
tmp.path(),
)
.unwrap();
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 48)).unwrap();
let mut over = Vec::new();
let pass = fewest_allocations(30, || {
tick_background(&mut app);
});
over.extend(within_budget("an idle pass", pass, budget::IDLE_PASS));
term.draw(|f| app.render_for_terminal(f)).unwrap();
let frame = most_allocations(5, || {
term.draw(|f| app.render_for_terminal(f)).unwrap();
});
over.extend(within_budget(
"a frame of the welcome page",
frame,
budget::FRAME_WELCOME,
));
app.editor.open_pinned(&file).unwrap();
crate::test_budget::await_spawned(
std::time::Duration::from_secs(5),
"opened file's background outline to land",
|| {
tick_background(&mut app);
app.outline.path() == Some(file.as_path())
&& !app.outline.symbols().is_empty()
&& app.outline_parse.is_none()
},
);
app.status = String::from("Ready");
for _ in 0..10 {
tick_background(&mut app);
term.draw(|f| app.render_for_terminal(f)).unwrap();
}
let pass = fewest_allocations(30, || {
tick_background(&mut app);
});
over.extend(within_budget(
"an idle pass with a file open",
pass,
budget::IDLE_PASS_WITH_FILE,
));
let frame = most_allocations(5, || {
term.draw(|f| app.render_for_terminal(f)).unwrap();
});
over.extend(within_budget(
"a frame with a file open",
frame,
budget::FRAME_WITH_FILE,
));
assert!(over.is_empty(), "{}", over.join("\n"));
}
#[test]
fn a_line_written_to_the_shown_output_channel_redraws_with_it() {
use crate::output::OutputLevel;
let _slot = crash_slot_lock();
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let channel = "Live Follow 2861";
crate::output::push(channel, OutputLevel::Info, "the first line");
app.output.sync();
assert!(app.output.select_by_name(channel));
app.bottom_panel_tab = BottomPanelTab::Output;
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 50)).unwrap();
let screen = |term: &mut ratatui::Terminal<ratatui::backend::TestBackend>, app: &mut App| {
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let area = buf.area;
(area.y..area.bottom())
.flat_map(|y| (area.x..area.right()).map(move |x| (x, y)))
.map(|(x, y)| buf[(x, y)].symbol().to_string())
.collect::<String>()
};
assert!(screen(&mut term, &mut app).contains("the first line"));
let_startup_land(&mut app);
crate::output::push(
"Live Follow 2861 (elsewhere)",
OutputLevel::Info,
"not shown",
);
assert!(
!tick_background(&mut app).changed,
"a line in a channel OUTPUT is not showing asks for no redraw"
);
crate::output::push(channel, OutputLevel::Info, "the second line");
assert!(
tick_background(&mut app).changed,
"a line written to the channel OUTPUT shows asks for a redraw"
);
assert!(
screen(&mut term, &mut app).contains("the second line"),
"the redrawn OUTPUT shows the line"
);
}