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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! Live Run: a Python file that runs itself as you type.
//!
//! The debugger answers "what is `x` here?" once you have set a breakpoint,
//! launched a session, and stepped to the line. Live Run answers it for every
//! line at once, continuously: each pause in typing re-runs the buffer and
//! paints what happened beside the code, the values each assignment produced
//! (with a loop's history, `i = 0, 1, 2 … 9 ×10`), what a line printed, what a
//! function returned, which lines never ran, and where the run died.
//!
//! # What runs, and where
//!
//! The BUFFER runs, not the file on disk: the point is to see the edit you
//! have not saved yet. It is piped to the project's interpreter (its `.venv`
//! python when there is one, so the project's imports resolve) with
//! [`INSTRUMENTER`], which rewrites the AST to record values and writes a JSON
//! report. The run has the file's own directory as cwd and `sys.path[0]`, so
//! relative opens and sibling imports behave as they would from a terminal.
//!
//! Running code on every keystroke is only acceptable because it is opt-in
//! per FILE: toggling Live Run arms the active file and no other, so opening
//! a script that deletes things never runs it on its own.
//!
//! # Why a stale annotation is never shown
//!
//! A run answers for the text it was given, and the buffer keeps moving while
//! it is in flight. Every report therefore carries the lines it ran, and the
//! editor paints a line's note only while that line is still byte-identical to
//! what ran. An edited line goes bare until the next run lands, rather than
//! wearing a value its current text never produced.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::mpsc::{Receiver, Sender};
use std::time::Duration;

/// The name of Live Run's runner thread, which the crash notice names.
pub const THREAD: &str = "croft-live-run";

use crate::jobs::{Start, Worker, WorkerPoll};

/// The Python side: an AST rewrite plus a JSON report writer.
pub const INSTRUMENTER: &str = include_str!("../assets/live_run/instrument.py");

/// How long a run may take before the instrumenter interrupts it and reports
/// the line it was stuck on. Long enough for real scripts, short enough that
/// an accidental `while True` costs a blink.
pub const RUN_BUDGET: Duration = Duration::from_secs(3);

/// Grace past [`RUN_BUDGET`] before the process is killed outright: the
/// interpreter's own alarm cannot interrupt a C call that ignores signals.
const KILL_GRACE: Duration = Duration::from_secs(2);

/// Quiet time after the last edit before a re-run, so a burst of typing costs
/// one run rather than one per key.
pub const DEBOUNCE: Duration = Duration::from_millis(350);

/// Longest single value shown before it is elided in the middle.
const MAX_VALUE_CHARS: usize = 40;

/// What a trailer segment reports, which picks its colour.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
    /// A value an assignment, loop, call, or return produced.
    Value,
    /// Text the line printed.
    Output,
    /// The exception the run died with.
    Error,
    /// The run was interrupted for taking too long.
    Timeout,
}

/// One line's trailer, as coloured segments painted left to right.
pub type Note = Vec<(String, Kind)>;

/// Whether a statement line ran, for the line-number colour.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Coverage {
    Ran,
    NeverRan,
}

/// A finished run, ready for the editor. Line keys are 0-based.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Report {
    pub notes: BTreeMap<usize, Note>,
    pub coverage: BTreeMap<usize, Coverage>,
    /// Everything the run printed, in order (capped by the instrumenter).
    pub stdout: String,
    /// The one-line summary of how the run ended, for the status bar.
    pub summary: String,
}

#[derive(serde::Deserialize)]
struct RawValue {
    k: String,
    n: u64,
    seen: Vec<String>,
    last: String,
}

#[derive(serde::Deserialize)]
struct RawLine {
    line: usize,
    #[serde(default)]
    vals: Vec<RawValue>,
    out: Option<String>,
    #[serde(default)]
    outn: u64,
}

#[derive(serde::Deserialize)]
struct RawError {
    line: usize,
    msg: String,
}

#[derive(serde::Deserialize)]
struct RawReport {
    lines: Vec<RawLine>,
    error: Option<RawError>,
    #[serde(default)]
    stmts: Vec<usize>,
    covered: Option<Vec<usize>>,
    #[serde(default)]
    stdout: String,
    #[serde(default)]
    ms: f64,
    #[serde(default)]
    timed_out: bool,
}

/// Elide a long value in the middle, keeping both ends: the start says what
/// it is and the end is where a growing list's newest element lives.
fn elide(value: &str) -> String {
    let count = value.chars().count();
    if count <= MAX_VALUE_CHARS {
        return value.to_string();
    }
    let head: String = value.chars().take(MAX_VALUE_CHARS / 2).collect();
    let tail: String = value
        .chars()
        .skip(count - (MAX_VALUE_CHARS / 2 - 1))
        .collect();
    format!("{head}\u{2026}{tail}")
}

/// One recorded name as the trailer shows it. A single hit is just its value;
/// repeated hits show the first few and the last, so a loop reads as the
/// sequence it walked: `i = 0, 1, 2 … 9 ×10`.
fn format_value(v: &RawValue) -> String {
    let values = if v.n <= 1 || v.seen.is_empty() {
        elide(&v.last)
    } else {
        let firsts: Vec<String> = v.seen.iter().map(|s| elide(s)).collect();
        let mut s = firsts.join(", ");
        if v.n as usize > v.seen.len() {
            s.push_str(" \u{2026} ");
            s.push_str(&elide(&v.last));
        }
        s.push_str(&format!(" \u{00d7}{}", v.n));
        s
    };
    match v.k.as_str() {
        // Return value and bare expression result: the instrumenter's
        // sentinel labels, never valid identifiers.
        "\u{21a9}" | "\u{2192}" => format!("{} {values}", v.k),
        name => format!("{name} = {values}"),
    }
}

/// Parse the instrumenter's JSON into a [`Report`].
pub fn parse_report(json: &str) -> Result<Report, String> {
    let raw: RawReport =
        serde_json::from_str(json).map_err(|e| format!("unreadable Live Run report: {e}"))?;
    let mut report = Report {
        stdout: raw.stdout,
        ..Report::default()
    };
    for line in raw.lines {
        let Some(idx) = line.line.checked_sub(1) else {
            continue;
        };
        let mut note: Note = Vec::new();
        let values: Vec<String> = line.vals.iter().map(format_value).collect();
        if !values.is_empty() {
            note.push((values.join("  "), Kind::Value));
        }
        if let Some(out) = line.out {
            let mut text = format!("\u{25b8} {out}");
            if line.outn > 1 {
                text.push_str(&format!(" \u{00d7}{}", line.outn));
            }
            note.push((text, Kind::Output));
        }
        if !note.is_empty() {
            report.notes.insert(idx, note);
        }
    }
    if let Some(covered) = raw.covered {
        let ran: BTreeSet<usize> = covered.into_iter().collect();
        for line in raw.stmts {
            let Some(idx) = line.checked_sub(1) else {
                continue;
            };
            let state = if ran.contains(&line) {
                Coverage::Ran
            } else {
                Coverage::NeverRan
            };
            report.coverage.insert(idx, state);
        }
    }
    let ms = if raw.ms >= 100.0 {
        format!("{:.0} ms", raw.ms)
    } else {
        format!("{:.1} ms", raw.ms)
    };
    report.summary = match raw.error {
        Some(err) => {
            let idx = err.line.saturating_sub(1);
            let (glyph, kind) = if raw.timed_out {
                ("\u{23f1}", Kind::Timeout)
            } else {
                ("\u{2716}", Kind::Error)
            };
            // The failure goes LAST on its line: the values that line
            // produced before dying are still true.
            report
                .notes
                .entry(idx)
                .or_default()
                .push((format!("{glyph} {}", err.msg), kind));
            format!("Live Run: {} (line {}, {ms})", err.msg, err.line)
        }
        None => {
            let ran = report
                .coverage
                .values()
                .filter(|c| **c == Coverage::Ran)
                .count();
            format!(
                "Live Run: ok in {ms}, {ran}/{} statements ran",
                report.coverage.len()
            )
        }
    };
    Ok(report)
}

/// A report as one editor tab holds it, with the text it answers for.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct View {
    /// The buffer lines the run executed.
    pub lines: Vec<String>,
    pub report: Report,
}

impl View {
    /// Whether 0-based `idx` still reads exactly as it did when it ran.
    fn current(&self, idx: usize, line: &str) -> bool {
        self.lines.get(idx).is_some_and(|ran| ran == line)
    }

    /// The trailer for `idx`, unless the line has changed since it ran.
    pub fn note(&self, idx: usize, line: &str) -> Option<&Note> {
        self.report
            .notes
            .get(&idx)
            .filter(|_| self.current(idx, line))
    }

    /// Whether `idx` ran, unless the line has changed since.
    pub fn coverage(&self, idx: usize, line: &str) -> Option<Coverage> {
        self.report
            .coverage
            .get(&idx)
            .copied()
            .filter(|_| self.current(idx, line))
    }
}

/// One request: run `lines` as the file at `path`.
#[derive(Clone, Debug)]
pub struct Job {
    pub path: PathBuf,
    pub lines: Vec<String>,
    pub python: PathBuf,
}

/// A run's answer, tagged with exactly what ran so the caller can tell a
/// report for the current text from one for text that has since changed.
#[derive(Debug)]
pub struct Done {
    pub path: PathBuf,
    pub lines: Vec<String>,
    pub outcome: Result<Report, String>,
}

/// The background runner: one thread, newest job per file wins. A thread
/// that crashed is started again, and one that crashes again soon after
/// stops until Live Run is next turned on (#2597).
pub struct Runner {
    worker: Worker<Job, Done>,
}

impl Runner {
    pub fn spawn() -> Self {
        Self::spawn_with(run)
    }

    /// A runner whose thread runs each job with `run_job`: [`run`] outside
    /// tests.
    fn spawn_with(
        run_job: impl Fn(&Job) -> Result<Report, String> + Send + Sync + 'static,
    ) -> Self {
        let worker = Worker::spawn(THREAD, Start::Now, move |job_rx, done_tx| {
            serve(&job_rx, &done_tx, &run_job)
        })
        .expect("spawn live-run thread");
        Runner { worker }
    }

    /// A runner whose first `crashes` threads panic on their first job,
    /// and whose later ones answer every job with an empty report that
    /// says it ran (#2597).
    #[cfg(test)]
    pub fn crashing(crashes: usize) -> Self {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let runs = AtomicUsize::new(0);
        Self::spawn_with(move |_| {
            if runs.fetch_add(1, Ordering::SeqCst) < crashes {
                panic!("Live Run's runner crashed (on purpose, in a test)");
            }
            Ok(Report {
                summary: String::from("Live Run: ok (stand-in)"),
                ..Report::default()
            })
        })
    }

    pub fn submit(&self, job: Job) {
        self.worker.send(job);
    }

    /// A finished run, nothing more for now, or what happened to a thread
    /// that ended (see [`WorkerPoll`]).
    pub fn poll(&mut self) -> WorkerPoll<Done> {
        self.worker.poll()
    }

    /// Start the runner again as Live Run is turned on, if it stopped after
    /// crashing twice or its thread has ended where no tick saw it yet;
    /// true when a fresh thread started, so what the old one was sent must
    /// be sent again.
    pub fn restart_if_down(&mut self) -> std::io::Result<bool> {
        self.worker.restart_if_down()
    }

    /// Whether it stopped after crashing twice: nothing is sent to it then.
    pub fn is_stopped(&self) -> bool {
        self.worker.is_stopped()
    }

    /// Whether its thread has ended, for a test that must see a crash no
    /// tick has seen.
    #[cfg(test)]
    pub fn has_ended(&mut self) -> bool {
        self.worker.has_ended()
    }
}

/// The runner thread's loop. Typing outpaces runs: only the newest buffer of
/// each file matters, but every armed file with a pending job still runs (the
/// app won't resubmit a file whose text it already sent).
fn serve(
    job_rx: &Receiver<Job>,
    done_tx: &Sender<Done>,
    run_job: &dyn Fn(&Job) -> Result<Report, String>,
) {
    let mut pending: Vec<Job> = Vec::new();
    loop {
        if pending.is_empty() {
            match job_rx.recv() {
                Ok(job) => pending.push(job),
                Err(_) => return,
            }
        }
        while let Ok(newer) = job_rx.try_recv() {
            pending.retain(|j| j.path != newer.path);
            pending.push(newer);
        }
        let job = pending.remove(0);
        let outcome = run_job(&job);
        let done = Done {
            path: job.path,
            lines: job.lines,
            outcome,
        };
        if done_tx.send(done).is_err() {
            return;
        }
    }
}

/// The file the instrumenter writes its report to: created exclusively (so a
/// pre-planted symlink at the name cannot redirect the write), owner-only,
/// and removed when the run is done with it.
struct ReportFile(PathBuf);

impl ReportFile {
    fn create() -> std::io::Result<Self> {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.subsec_nanos())
            .unwrap_or(0);
        let name = format!(
            "croft-live-run-{}-{}-{nanos}.json",
            std::process::id(),
            COUNTER.fetch_add(1, Ordering::Relaxed)
        );
        let path = std::env::temp_dir().join(name);
        let mut opts = std::fs::OpenOptions::new();
        opts.write(true).create_new(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            opts.mode(0o600);
        }
        opts.open(&path)?;
        Ok(ReportFile(path))
    }

    fn path(&self) -> &Path {
        &self.0
    }
}

impl Drop for ReportFile {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.0);
    }
}

/// How much of a failed run's stderr is kept for its error line.
const STDERR_TAIL: usize = 16 * 1024;

/// Run one job to completion (or to the kill deadline) and parse its report.
fn run(job: &Job) -> Result<Report, String> {
    let report_file = ReportFile::create().map_err(|e| format!("Live Run: no temp file: {e}"))?;
    let cwd = job
        .path
        .parent()
        .filter(|p| p.is_dir())
        .map(Path::to_path_buf)
        .unwrap_or_else(std::env::temp_dir);
    let mut cmd = Command::new(&job.python);
    cmd.arg("-c")
        .arg(INSTRUMENTER)
        .arg(&job.path)
        .arg(report_file.path())
        .arg(RUN_BUDGET.as_secs_f64().to_string())
        .current_dir(cwd)
        // A live run must not litter the project with bytecode caches.
        .env("PYTHONDONTWRITEBYTECODE", "1");
    let mut source = job.lines.join("\n");
    source.push('\n');
    let limit = RUN_BUDGET + KILL_GRACE;
    // A session of its own, so what the script started (a server, `sleep`
    // in a subprocess) is killed with it when it ends, on time or at the
    // deadline: Live Run re-runs on every pause in typing, and each run left
    // one more behind (#2776). A program the script deliberately detaches
    // into a session of its own (`start_new_session=True`, a daemon) is out
    // of reach, as for the node probe (#2755). The source goes in on stdin only as fast as
    // the interpreter reads it, and stderr is drained while it runs, so
    // neither a script that never reads nor one that floods stderr can hold
    // the run past the deadline.
    crate::proc::Bounded {
        stdout: crate::proc::Keep::Nothing,
        stderr: crate::proc::Keep::Tail(STDERR_TAIL),
        apart: crate::proc::Apart::Session,
        limit,
        retry_busy: false,
    }
    .run_fed(&mut cmd, source.as_bytes())
    .map_err(|e| match e {
        crate::proc::RunError::Spawn(e) => {
            format!("Live Run: cannot start {}: {e}", job.python.display())
        }
        crate::proc::RunError::TimedOut => format!(
            "Live Run: killed after {}s (a call ignored the interrupt)",
            limit.as_secs()
        ),
        crate::proc::RunError::Wait(e) | crate::proc::RunError::Pipe(e) => format!("Live Run: {e}"),
        // Neither stream is kept whole, so neither can be too long.
        crate::proc::RunError::TooLong { .. } => String::from("Live Run: too much output"),
    })
    .and_then(|ran| {
        let json = std::fs::read_to_string(report_file.path()).unwrap_or_default();
        if !json.trim().is_empty() {
            return parse_report(&json);
        }
        let err = ran.stderr.text();
        let last = err.lines().rev().find(|l| !l.trim().is_empty());
        Err(match last {
            Some(line) => format!("Live Run: {}", line.trim()),
            None => String::from("Live Run: the script exited before reporting (os._exit?)"),
        })
    })
}

/// Whether Live Run can run this file at all.
pub fn supports(path: &Path) -> bool {
    matches!(
        path.extension().and_then(|e| e.to_str()),
        Some("py") | Some("pyw")
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Instant;

    fn report(json: &str) -> Report {
        parse_report(json).expect("parses")
    }

    #[test]
    fn a_single_assignment_reads_name_equals_value() {
        let r = report(
            r#"{"lines":[{"line":2,"vals":[{"k":"x","n":1,"seen":["5"],"last":"5"}]}],
                "error":null,"stmts":[2],"covered":[2],"stdout":"","ms":1.0}"#,
        );
        assert_eq!(r.notes[&1], vec![(String::from("x = 5"), Kind::Value)]);
        assert_eq!(r.coverage[&1], Coverage::Ran);
    }

    #[test]
    fn a_loop_shows_its_first_values_and_last_with_a_count() {
        let r = report(
            r#"{"lines":[{"line":1,"vals":[{"k":"i","n":10,"seen":["0","1","2"],"last":"9"}]}],
                "error":null,"stmts":[1],"covered":[1]}"#,
        );
        assert_eq!(r.notes[&0][0].0, "i = 0, 1, 2 \u{2026} 9 \u{00d7}10");
    }

    #[test]
    fn a_short_loop_lists_every_value_without_an_ellipsis() {
        let r = report(
            r#"{"lines":[{"line":1,"vals":[{"k":"i","n":2,"seen":["0","1"],"last":"1"}]}],
                "error":null}"#,
        );
        assert_eq!(r.notes[&0][0].0, "i = 0, 1 \u{00d7}2");
    }

    #[test]
    fn returns_and_expressions_use_their_arrows_not_a_name() {
        let r = report(
            r#"{"lines":[{"line":3,"vals":[{"k":"↩","n":1,"seen":["55"],"last":"55"}]},
                         {"line":4,"vals":[{"k":"→","n":1,"seen":["5.0"],"last":"5.0"}]}],
                "error":null}"#,
        );
        assert_eq!(r.notes[&2][0].0, "\u{21a9} 55");
        assert_eq!(r.notes[&3][0].0, "\u{2192} 5.0");
    }

    #[test]
    fn printed_output_follows_the_values_on_its_line() {
        let r = report(r#"{"lines":[{"line":1,"vals":[],"out":"hello","outn":3}],"error":null}"#);
        assert_eq!(
            r.notes[&0],
            vec![(String::from("\u{25b8} hello \u{00d7}3"), Kind::Output)]
        );
    }

    #[test]
    fn the_error_lands_on_its_line_after_that_lines_values() {
        let r = report(
            r#"{"lines":[{"line":5,"vals":[{"k":"y","n":1,"seen":["1"],"last":"1"}]}],
                "error":{"line":5,"msg":"ZeroDivisionError: division by zero"},
                "stmts":[5],"covered":[5]}"#,
        );
        let note = &r.notes[&4];
        assert_eq!(note[0].1, Kind::Value);
        assert_eq!(
            note[1],
            (
                String::from("\u{2716} ZeroDivisionError: division by zero"),
                Kind::Error
            )
        );
        assert!(r.summary.contains("line 5"), "{}", r.summary);
    }

    #[test]
    fn a_timeout_is_its_own_kind() {
        let r = report(
            r#"{"lines":[],"error":{"line":3,"msg":"still running after 3s"},"timed_out":true}"#,
        );
        assert_eq!(r.notes[&2][0].1, Kind::Timeout);
    }

    #[test]
    fn statements_that_never_ran_are_marked() {
        let r = report(r#"{"lines":[],"error":null,"stmts":[1,2,3],"covered":[1,3]}"#);
        assert_eq!(r.coverage[&0], Coverage::Ran);
        assert_eq!(r.coverage[&1], Coverage::NeverRan);
        assert!(r.summary.contains("2/3 statements"), "{}", r.summary);
    }

    #[test]
    fn missing_coverage_marks_nothing_rather_than_everything_unrun() {
        let r = report(r#"{"lines":[],"error":null,"stmts":[1,2],"covered":null}"#);
        assert!(r.coverage.is_empty());
    }

    #[test]
    fn an_edited_line_drops_its_note_until_the_next_run() {
        let view = View {
            lines: vec![String::from("x = 1"), String::from("y = 2")],
            report: report(
                r#"{"lines":[{"line":1,"vals":[{"k":"x","n":1,"seen":["1"],"last":"1"}]}],
                    "error":null,"stmts":[1,2],"covered":[1,2]}"#,
            ),
        };
        assert!(view.note(0, "x = 1").is_some());
        assert!(
            view.note(0, "x = 10").is_none(),
            "the value is for the old text"
        );
        assert_eq!(view.coverage(1, "y = 2"), Some(Coverage::Ran));
        assert_eq!(view.coverage(1, "y = 3"), None);
        assert_eq!(view.coverage(5, ""), None, "past the end of what ran");
    }

    #[test]
    fn long_values_elide_in_the_middle() {
        let long = "a".repeat(30) + &"b".repeat(30);
        let shown = elide(&long);
        assert_eq!(shown.chars().count(), MAX_VALUE_CHARS);
        assert!(shown.starts_with('a') && shown.ends_with('b'));
    }

    #[test]
    fn only_python_files_are_supported() {
        assert!(supports(Path::new("/p/a.py")));
        assert!(!supports(Path::new("/p/a.rs")));
        assert!(!supports(Path::new("/p/Makefile")));
    }

    /// End to end against a real interpreter, when the machine has one: the
    /// instrumenter and the parser must agree on the report's shape.
    #[test]
    fn runs_a_real_script_when_python3_is_available() {
        let Ok(out) = Command::new("python3").arg("--version").output() else {
            return;
        };
        if !out.status.success() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("demo.py");
        let lines: Vec<String> = [
            "total = 0",
            "for k in range(4):",
            "    total += k",
            "print('sum', total)",
            "if total > 100:",
            "    print('never')",
            "1 / 0",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        let job = Job {
            path: path.clone(),
            lines,
            python: PathBuf::from("python3"),
        };
        let r = run(&job).expect("runs");
        assert!(
            !r.notes.contains_key(&0),
            "a literal assignment is not echoed back"
        );
        assert_eq!(r.notes[&1][0].0, "k = 0, 1, 2 \u{2026} 3 \u{00d7}4");
        assert_eq!(r.notes[&2][0].0, "total = 0, 1, 3 \u{2026} 6 \u{00d7}4");
        assert_eq!(
            r.notes[&3][0],
            (String::from("\u{25b8} sum 6"), Kind::Output)
        );
        assert_eq!(r.coverage[&5], Coverage::NeverRan);
        assert_eq!(r.notes[&6].last().unwrap().1, Kind::Error);
        assert_eq!(r.stdout, "sum 6\n");
    }

    /// A script that floods stderr past the pipe's buffer still reports.
    #[test]
    fn a_script_that_floods_stderr_still_reports() {
        let Ok(out) = Command::new("python3").arg("--version").output() else {
            return;
        };
        if !out.status.success() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let job = Job {
            path: dir.path().join("loud.py"),
            lines: vec![
                String::from("import sys"),
                String::from("sys.stderr.write('x' * 1_000_000)"),
                String::from("n = len('done')"),
            ],
            python: PathBuf::from("python3"),
        };
        let started = Instant::now();
        let r = run(&job).expect("reports instead of being killed");
        assert!(started.elapsed() < RUN_BUDGET);
        assert_eq!(r.notes[&2][0].0, "n = 4");
    }

    /// What a script starts and leaves running is killed when its run ends,
    /// not left behind: Live Run re-runs the file on every pause in typing,
    /// so a script that starts a server would otherwise leave one more each
    /// time (#2776).
    #[cfg(target_os = "linux")]
    #[test]
    fn what_a_script_leaves_running_is_killed_when_it_ends() {
        let Ok(out) = Command::new("python3").arg("--version").output() else {
            return;
        };
        if !out.status.success() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let pid_file = dir.path().join("helper.pid");
        let job = Job {
            path: dir.path().join("server.py"),
            lines: vec![
                String::from("import subprocess"),
                String::from(
                    "p = subprocess.Popen(['sleep', '30'], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)",
                ),
                format!(
                    "open({:?}, 'w').write(str(p.pid))",
                    pid_file.display().to_string()
                ),
                String::from("n = 1"),
            ],
            python: PathBuf::from("python3"),
        };
        run(&job).expect("the script reports");
        let pid: i32 = std::fs::read_to_string(&pid_file)
            .unwrap()
            .trim()
            .parse()
            .unwrap();
        let until = Instant::now() + Duration::from_secs(5);
        let alive = |pid: i32| {
            // SAFETY: signal 0 only asks whether the process exists.
            let exists = unsafe { libc::kill(pid, 0) } == 0;
            let zombie = std::fs::read_to_string(format!("/proc/{pid}/stat"))
                .ok()
                .and_then(|stat| {
                    let after = stat.rsplit_once(')')?.1.to_owned();
                    after.split_whitespace().next().map(|state| state == "Z")
                })
                .unwrap_or(false);
            exists && !zombie
        };
        while alive(pid) && Instant::now() < until {
            std::thread::sleep(Duration::from_millis(20));
        }
        let left = alive(pid);
        if left {
            // SAFETY: a plain signal to the helper this test's script started.
            unsafe { libc::kill(pid, libc::SIGKILL) };
        }
        assert!(!left, "the script's helper outlived its run");
    }
}