croft-software 0.2.232

VSCode-style TUI written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! The main loop's background pass (#2062), called the way the loop calls it.

use super::*;

/// Every poll and drain the background pass calls on the app, in order, its
/// steps included. The order is part of what the pass does: a crash notice
/// comes before the polls that settle its task (#2609), the language servers
/// are synced before the outline reads their edit count, a run's failure is
/// announced after the Testing panel takes its results, and so on. A call added to the pass is
/// added here where it runs; moving calls between steps keeps this list as
/// it is.
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",
];

/// The `app.` and `crate::` calls the background pass makes, in the order it
/// makes them: the body of `tick_background`, with each of its steps (a
/// function of `tick.rs` handed the app) read in where it is called.
/// Comments are left out.
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
}

/// Append the calls in the body of `tick.rs`'s function `name` to `calls`,
/// reading a step's calls in where the body calls the step.
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(),
            ),
        }
    }
}

/// The background pass runs every poll and drain in its pinned order.
#[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);
}

/// Run passes until startup's own background work has landed. Each lands in
/// a pass that asks for a redraw: the file watcher's install, Go to File's
/// index, and the terminal pane's first label lookup, which starts one label
/// interval (1.5 s) after startup. A single quiet pass is not enough to say
/// it has all landed: the label lookup comes well after the others.
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()
        },
    );
}

/// An idle croft draws nothing: once startup's background work has landed, a
/// pass that finds nothing new asks for no redraw. A poll that reported a
/// change on every pass would redraw the whole screen on every tick, 125
/// times a second, and over SSH send it all each time.
#[test]
fn an_idle_background_pass_asks_for_no_redraw() {
    // A pass takes any crash notice waiting in the process-wide slot: the
    // tests that put one there on purpose must not lose it to this one, nor
    // this one see theirs.
    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"
        );
    }
}

/// A pass that restores who typed each line of an open file asks for a
/// redraw (#2925 review). A save's record is read a pass after its worker
/// says it is done; when the file shows in a split beside the one being
/// worked in, nothing else on that pass draws, and a restore that did not
/// say so left the split's marks off screen until something else drew.
#[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();
    // note.txt in a split, and the group being worked in on another file.
    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);
    // A save's worker records the snapshot and who typed it, then says so.
    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"
    );
}

/// The allocations croft may make, at most, in an idle background pass and
/// in one frame (#2062): the counts of today's code, which can only go down.
/// A change that makes croft allocate less fails
/// `the_idle_loop_and_a_frame_keep_to_their_allocation_budgets` until its
/// number here is lowered to match; raising one is a review decision, made
/// here with the reason.
mod budget {
    /// An idle pass with no file open: nothing. Each step finds it has no
    /// work by comparing in place, so any allocation here is new work done
    /// for nothing on every pass.
    pub(super) const IDLE_PASS: u64 = 0;
    /// An idle pass with a 2,000-line file open: nothing, likewise.
    pub(super) const IDLE_PASS_WITH_FILE: u64 = 0;
    /// A redraw of the welcome page, with two release notes.
    pub(super) const FRAME_WELCOME: u64 = 13;
    /// A redraw with a 2,000-line file open.
    pub(super) const FRAME_WITH_FILE: u64 = 45;
}

/// Hold a measured count to its budget: over it fails, and so does a count
/// well under it, which asks for the lower budget, so a budget only goes
/// down. "Well under" leaves room for the odd allocation one run makes and
/// another does not (2%, at least 2).
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
    }
}

/// The fewest allocations any of `runs` calls of `f` made: an idle pass now
/// and then collects a timer's or a background job's result, which is not
/// what the budget holds.
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)
}

/// The most allocations any of `runs` calls of `f` made. Frames are held by
/// their worst: each one redraws the same screen, so a frame that allocates
/// where another did not (every other frame, or a cache refilled now and
/// then) is what the budget is there to catch.
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)
}

/// An idle croft allocates on every pass of its loop, 125 a second, and on
/// every frame; nothing measured it, so any change could add to it unseen
/// (#2062). Each count is held to its budget in `budget`.
#[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();
    // The welcome page shows the release notes built into the binary, which
    // every change adds to; fixed ones keep its count to the page's own.
    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);
    // The panel's pane runs the machine's own shell, whose name, prompt and
    // timing differ from machine to machine: a pane that runs a silent
    // program in its place keeps the count the same everywhere.
    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));
    // Frames are drawn the way the main loop draws them: the screen, then
    // the fit to the terminal's colours.
    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();
    // Wait for the background outline parse of the 2,000-line file to land
    // before sampling steady-state frames: otherwise fast machines measure
    // before the symbol breadcrumb appears while slower/CI runners measure
    // after it lands, shifting the count by 5 allocations.
    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()
        },
    );
    // Keep the status line independent of whether a local language server
    // (such as rust-analyzer) happens to be installed on the test machine.
    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"));
}

/// OUTPUT follows its channel while it is on screen (#2861): a line written
/// there asks the next pass for a redraw, and that frame shows it. The view
/// used to refresh only when focus moved, so a log being written stood still
/// on screen until the next click elsewhere. A push to a channel the view is
/// not showing asks for nothing: other tests write to the process-wide bus
/// all the while, and the idle passes above stay quiet.
#[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"
    );
}